agentic-qe 3.9.17 → 3.9.19

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 (312) hide show
  1. package/.claude/helpers/statusline-v3.cjs +1 -1
  2. package/.claude/skills/skills-manifest.json +1 -1
  3. package/CHANGELOG.md +56 -0
  4. package/README.md +65 -0
  5. package/assets/skills/skills-manifest.json +1 -1
  6. package/dist/cli/bundle.js +5 -5
  7. package/dist/cli/chunks/adapter-5NI3IO42.js +2 -0
  8. package/dist/cli/chunks/{agent-booster-wasm-JN7W7O5X.js → agent-booster-wasm-HVBKHNIS.js} +2 -2
  9. package/dist/cli/chunks/{agent-handler-F6Q75SJQ.js → agent-handler-XNBDYRSJ.js} +2 -2
  10. package/dist/cli/chunks/{agent-memory-branch-3GGTDVR4.js → agent-memory-branch-YCVTQEMJ.js} +2 -2
  11. package/dist/cli/chunks/aqe-learning-engine-JOUK5HMO.js +2 -0
  12. package/dist/cli/chunks/{audit-R7KN45HM.js → audit-6C2PE7OY.js} +2 -2
  13. package/dist/cli/chunks/base-DCAB7AHK.js +2 -0
  14. package/dist/cli/chunks/{better-sqlite3-2LTGEMYR.js → better-sqlite3-HZPCHUQU.js} +2 -2
  15. package/dist/cli/chunks/{brain-handler-PML5L6WQ.js → brain-handler-OV75Q2NM.js} +3 -3
  16. package/dist/cli/chunks/{branch-enumerator-OKUPS2XC.js → branch-enumerator-QW6D42HJ.js} +2 -2
  17. package/dist/cli/chunks/{browser-KOQOTSAT.js → browser-5BA7Q7OR.js} +2 -2
  18. package/dist/cli/chunks/browser-workflow-A4UV73SZ.js +2 -0
  19. package/dist/cli/chunks/{chunk-ZLOMFM25.js → chunk-255CWHTF.js} +2 -2
  20. package/dist/cli/chunks/{chunk-QW554DTP.js → chunk-2SIQ742L.js} +1 -1
  21. package/dist/cli/chunks/{chunk-XMMKAV5R.js → chunk-2SSDY6OE.js} +2 -2
  22. package/dist/cli/chunks/{chunk-HMT6LKHH.js → chunk-2WJLEZKP.js} +2 -2
  23. package/dist/cli/chunks/{chunk-VX6XHAG2.js → chunk-2WM4NYM5.js} +2 -2
  24. package/dist/cli/chunks/{chunk-6PRIY3HT.js → chunk-2XATUQIG.js} +2 -2
  25. package/dist/cli/chunks/{chunk-BCBC3DVN.js → chunk-3546SG2L.js} +2 -2
  26. package/dist/cli/chunks/{chunk-ORNWQXEX.js → chunk-37DTXQ6P.js} +2 -2
  27. package/dist/cli/chunks/{chunk-3GYAIW2P.js → chunk-3HQ4AZDH.js} +2 -2
  28. package/dist/cli/chunks/{chunk-YUCMGFHE.js → chunk-3X3QQZ7Q.js} +2 -2
  29. package/dist/cli/chunks/{chunk-ZQKNVZPD.js → chunk-44SPMVML.js} +2 -2
  30. package/dist/cli/chunks/{chunk-65Z6HMDA.js → chunk-5KGFDNYI.js} +2 -2
  31. package/dist/cli/chunks/{chunk-OUSQ4KQN.js → chunk-5LXWEAEJ.js} +2 -2
  32. package/dist/cli/chunks/{chunk-DJXYFFGA.js → chunk-5MGRZ4YD.js} +2 -2
  33. package/dist/cli/chunks/{chunk-6YFEWIL5.js → chunk-5R2DUR3A.js} +2 -2
  34. package/dist/cli/chunks/{chunk-QMVGGG4B.js → chunk-5X2AUPK2.js} +1 -1
  35. package/dist/cli/chunks/{chunk-QYDBV5MD.js → chunk-6BRUQTC7.js} +1 -1
  36. package/dist/cli/chunks/{chunk-RP2RHB7H.js → chunk-7IV2RK5M.js} +2 -2
  37. package/dist/cli/chunks/{chunk-A3WC5KTG.js → chunk-7WMHLBNZ.js} +1 -1
  38. package/dist/cli/chunks/{chunk-VYCFMW64.js → chunk-AEET2WOI.js} +68 -67
  39. package/dist/cli/chunks/{chunk-V4DMYY6P.js → chunk-AG7J7DTM.js} +2 -2
  40. package/dist/cli/chunks/{chunk-JT2KLBDB.js → chunk-ALYUJEYA.js} +2 -2
  41. package/dist/cli/chunks/{chunk-L6ZJSFAA.js → chunk-AOASQYOO.js} +1 -1
  42. package/dist/cli/chunks/{chunk-6YCZDIGF.js → chunk-AZKVGH5I.js} +2 -2
  43. package/dist/cli/chunks/{chunk-3UGV2XWF.js → chunk-B2EHSFUW.js} +2 -2
  44. package/dist/cli/chunks/{chunk-TATCL3AK.js → chunk-B65GTWF3.js} +2 -2
  45. package/dist/cli/chunks/{chunk-PMH52K5J.js → chunk-BB3KUX6C.js} +1 -1
  46. package/dist/cli/chunks/{chunk-EGBRCXYT.js → chunk-BFBR2ZZJ.js} +2 -2
  47. package/dist/cli/chunks/{chunk-LD4OYOX2.js → chunk-BGTYOZRK.js} +2 -2
  48. package/dist/cli/chunks/{chunk-KUEG6K4A.js → chunk-BOUCIIUI.js} +1 -1
  49. package/dist/cli/chunks/{chunk-AZWCJFT6.js → chunk-C5YFCM2H.js} +2 -2
  50. package/dist/cli/chunks/{chunk-F5X3U57Y.js → chunk-CYLQTVIA.js} +2 -2
  51. package/dist/cli/chunks/{chunk-G3G5QEHL.js → chunk-D2EHD2KF.js} +1 -1
  52. package/dist/cli/chunks/{chunk-AFLTMVMT.js → chunk-D74RGYKI.js} +1 -1
  53. package/dist/cli/chunks/{chunk-QVJQXRHU.js → chunk-DAPBSAVT.js} +2 -2
  54. package/dist/cli/chunks/{chunk-BGY4CHZA.js → chunk-DZS7XQ2Z.js} +2 -2
  55. package/dist/cli/chunks/{chunk-RYATPB5L.js → chunk-EW5TQQBR.js} +2 -2
  56. package/dist/cli/chunks/{chunk-L5JZIORJ.js → chunk-EZZJ5XD6.js} +2 -2
  57. package/dist/cli/chunks/{chunk-MNSF47HC.js → chunk-FJJLNCSL.js} +3 -3
  58. package/dist/cli/chunks/{chunk-6F6BNLVP.js → chunk-FL2DMHOQ.js} +1 -1
  59. package/dist/cli/chunks/{chunk-EVQYUUQ3.js → chunk-FNVA7U7X.js} +2 -2
  60. package/dist/cli/chunks/{chunk-I3NUJ6KJ.js → chunk-FPVXXQVX.js} +3 -3
  61. package/dist/cli/chunks/{chunk-K4FG3CRS.js → chunk-FT3MAIRW.js} +3 -3
  62. package/dist/cli/chunks/{chunk-CZXV3JAF.js → chunk-G2V4GMPR.js} +3 -3
  63. package/dist/cli/chunks/chunk-GJ5FON37.js +15 -0
  64. package/dist/cli/chunks/{chunk-6PCGUJCG.js → chunk-GL742O2V.js} +4 -4
  65. package/dist/cli/chunks/{chunk-X66N7E7D.js → chunk-GVDLCJC5.js} +1 -1
  66. package/dist/cli/chunks/{chunk-3KIUCAVI.js → chunk-GYDE5TCN.js} +1 -1
  67. package/dist/cli/chunks/{chunk-2K7GRX5U.js → chunk-GYESQBDU.js} +2 -2
  68. package/dist/cli/chunks/{chunk-63ERVKIO.js → chunk-H4QM37XS.js} +1 -1
  69. package/dist/cli/chunks/{chunk-VI2I5R6C.js → chunk-HCSTXZYE.js} +2 -2
  70. package/dist/cli/chunks/{chunk-6HGRJPD6.js → chunk-HJ7CRPZY.js} +1 -1
  71. package/dist/cli/chunks/{chunk-G5DEPXD4.js → chunk-HQFREZRX.js} +2 -2
  72. package/dist/cli/chunks/{chunk-7VGZDTY4.js → chunk-HVNW3TZS.js} +1 -1
  73. package/dist/cli/chunks/{chunk-W5HTZ3VZ.js → chunk-I3JRRFVT.js} +2 -2
  74. package/dist/cli/chunks/{chunk-Y47U7ICT.js → chunk-IG2RCBHJ.js} +1 -1
  75. package/dist/cli/chunks/{chunk-4TDIA2EN.js → chunk-IPLQPBJA.js} +2 -2
  76. package/dist/cli/chunks/{chunk-ARN2KDLJ.js → chunk-IV74GAZN.js} +2 -2
  77. package/dist/cli/chunks/{chunk-I64R2D4U.js → chunk-J7F65KKG.js} +4 -4
  78. package/dist/cli/chunks/{chunk-A67FRRPJ.js → chunk-JCPJG2KU.js} +3 -3
  79. package/dist/cli/chunks/{chunk-HQXRCW7Z.js → chunk-JLX35EPX.js} +2 -2
  80. package/dist/cli/chunks/{chunk-42TUEMH7.js → chunk-JYHZK44T.js} +1 -1
  81. package/dist/cli/chunks/{chunk-63V33NAB.js → chunk-K554X3T4.js} +2 -2
  82. package/dist/cli/chunks/{chunk-P2V5ZG3Q.js → chunk-KTDGHN2J.js} +1 -1
  83. package/dist/cli/chunks/{chunk-FVVZWNLV.js → chunk-KU7OXAFY.js} +1 -1
  84. package/dist/cli/chunks/{chunk-5J444NJR.js → chunk-LDBHCOM3.js} +2 -2
  85. package/dist/cli/chunks/{chunk-PGTMLW5K.js → chunk-LTE3CDOY.js} +2 -2
  86. package/dist/cli/chunks/{chunk-WP55YBB2.js → chunk-M6EP724N.js} +1 -1
  87. package/dist/cli/chunks/{chunk-Z5R46W6Q.js → chunk-MIQAFOFO.js} +1 -1
  88. package/dist/cli/chunks/{chunk-OSBJWQZL.js → chunk-MMVSIESL.js} +2 -2
  89. package/dist/cli/chunks/{chunk-WGEJ646F.js → chunk-MN4366PQ.js} +2 -2
  90. package/dist/cli/chunks/{chunk-7PWW2OXP.js → chunk-MTHO6A3V.js} +1 -1
  91. package/dist/cli/chunks/{chunk-UTO2M76W.js → chunk-N2PLNYEV.js} +1 -1
  92. package/dist/cli/chunks/{chunk-BCIEQ4IP.js → chunk-NBBIA3QA.js} +2 -2
  93. package/dist/cli/chunks/{chunk-2LXXYKAP.js → chunk-NMYZSZHW.js} +2 -2
  94. package/dist/cli/chunks/{chunk-V3VJNWOF.js → chunk-NPSWRGNT.js} +2 -2
  95. package/dist/cli/chunks/{chunk-PEHHOJE6.js → chunk-NXO7CT5K.js} +2 -2
  96. package/dist/cli/chunks/{chunk-42HSEBOH.js → chunk-O5ZP3CBF.js} +2 -2
  97. package/dist/cli/chunks/{chunk-DR6SJ6P3.js → chunk-O6UMETOH.js} +2 -2
  98. package/dist/cli/chunks/{chunk-CPZUNBSQ.js → chunk-OEQCZBBM.js} +2 -2
  99. package/dist/cli/chunks/{chunk-PJZHNAUT.js → chunk-P6EYD4V3.js} +2 -2
  100. package/dist/cli/chunks/{chunk-DDJUVCKF.js → chunk-PS72GF4R.js} +3 -3
  101. package/dist/cli/chunks/{chunk-LA565BGJ.js → chunk-PUUTYV32.js} +2 -2
  102. package/dist/cli/chunks/{chunk-AZQ476BM.js → chunk-QOK4TIE4.js} +2 -2
  103. package/dist/cli/chunks/chunk-R5IL3XD5.js +69 -0
  104. package/dist/cli/chunks/{chunk-BUWZOMC7.js → chunk-RL5CBCBV.js} +1 -1
  105. package/dist/cli/chunks/{chunk-FYNDV2NZ.js → chunk-SKDDAPBV.js} +1 -1
  106. package/dist/cli/chunks/{chunk-K44EQV74.js → chunk-SKNHAGYP.js} +2 -2
  107. package/dist/cli/chunks/{chunk-CQSU7NTG.js → chunk-SLDYG7LC.js} +2 -2
  108. package/dist/cli/chunks/{chunk-PV6WBC2D.js → chunk-SRKBR4DU.js} +2 -2
  109. package/dist/cli/chunks/{chunk-XZOJWFLH.js → chunk-TCUIYIZ4.js} +1 -1
  110. package/dist/cli/chunks/{chunk-JVDYHVF2.js → chunk-TMAIHTE3.js} +4 -4
  111. package/dist/cli/chunks/{chunk-B36RPXAQ.js → chunk-TXCOK5DC.js} +2 -2
  112. package/dist/cli/chunks/{chunk-KTUSZRS3.js → chunk-U257SS7D.js} +2 -2
  113. package/dist/cli/chunks/{chunk-32FWC6G3.js → chunk-U2WMCNNR.js} +2 -2
  114. package/dist/cli/chunks/{chunk-I5BLJ2QQ.js → chunk-UIASVDYG.js} +2 -2
  115. package/dist/cli/chunks/{chunk-CY73RJJJ.js → chunk-V7ZPTEP7.js} +1 -1
  116. package/dist/cli/chunks/{chunk-YE5AYBHX.js → chunk-VHG67L7O.js} +2 -2
  117. package/dist/cli/chunks/{chunk-FCWB2FJG.js → chunk-VLQYU7ZQ.js} +1 -1
  118. package/dist/cli/chunks/{chunk-R3COBKOP.js → chunk-VPDZTMMB.js} +3 -3
  119. package/dist/cli/chunks/{chunk-QFFSQWXP.js → chunk-VRGXYOIN.js} +1 -1
  120. package/dist/cli/chunks/{chunk-PMNZN4K7.js → chunk-VSI45JCP.js} +1 -1
  121. package/dist/cli/chunks/{chunk-DVEQOD74.js → chunk-VWWLJBRA.js} +45 -44
  122. package/dist/cli/chunks/{chunk-6MRUG5G2.js → chunk-VXUIIZNG.js} +1 -1
  123. package/dist/cli/chunks/{chunk-QXOAFWWK.js → chunk-W3IO4FQ5.js} +2 -2
  124. package/dist/cli/chunks/{chunk-XB4JRJU4.js → chunk-WULMXLNN.js} +1 -1
  125. package/dist/cli/chunks/{chunk-MER7IHAZ.js → chunk-WZUQT2BE.js} +2 -2
  126. package/dist/cli/chunks/{chunk-USORP6QK.js → chunk-XF32XZMY.js} +2 -2
  127. package/dist/cli/chunks/{chunk-ZI3UBCIN.js → chunk-XKD6AFY5.js} +1 -1
  128. package/dist/cli/chunks/{chunk-Z77BVREU.js → chunk-XP4T7CZY.js} +2 -2
  129. package/dist/cli/chunks/{chunk-APWO3FI3.js → chunk-XQZ63XSL.js} +1 -1
  130. package/dist/cli/chunks/{chunk-MPEQXXXR.js → chunk-XXHJKAE6.js} +2 -2
  131. package/dist/cli/chunks/{chunk-N64PBOR5.js → chunk-Y3GX66VZ.js} +2 -2
  132. package/dist/cli/chunks/{chunk-B3M3JEFD.js → chunk-YXLQJ226.js} +2 -2
  133. package/dist/cli/chunks/chunk-Z2E5DTKX.js +2 -0
  134. package/dist/cli/chunks/{ci-TRWQ33L2.js → ci-FTZE4PD3.js} +2 -2
  135. package/dist/cli/chunks/{ci-output-TCFNHOTU.js → ci-output-C3ORCIHU.js} +2 -2
  136. package/dist/cli/chunks/{circuit-breaker-GO2TIL7E.js → circuit-breaker-GS5OTOJZ.js} +2 -2
  137. package/dist/cli/chunks/{claude-flow-setup-U77JVSVU.js → claude-flow-setup-RWOFP5L2.js} +2 -2
  138. package/dist/cli/chunks/client-UTNF2C5K.js +2 -0
  139. package/dist/cli/chunks/{cline-installer-XFD3SMGS.js → cline-installer-D7RGRAUH.js} +2 -2
  140. package/dist/cli/chunks/{code-V3VE2TMW.js → code-HBDMMYHY.js} +2 -2
  141. package/dist/cli/chunks/{code-index-extractor-C6DHOOWA.js → code-index-extractor-B2KUPAEH.js} +2 -2
  142. package/dist/cli/chunks/{codex-installer-IUR7MVE6.js → codex-installer-MPXV4AOD.js} +2 -2
  143. package/dist/cli/chunks/{completions-R7FZHNJJ.js → completions-QJS6QOZQ.js} +2 -2
  144. package/dist/cli/chunks/{complexity-analyzer-EP4QF5CS.js → complexity-analyzer-YQQXWZIL.js} +2 -2
  145. package/dist/cli/chunks/{continuedev-installer-6DW2SBMQ.js → continuedev-installer-Z6PBKYMB.js} +2 -2
  146. package/dist/cli/chunks/{copilot-installer-U3UOX7D5.js → copilot-installer-RWVD44CV.js} +2 -2
  147. package/dist/cli/chunks/{cost-tracker-5QZ5A46I.js → cost-tracker-DFPBFYWL.js} +2 -2
  148. package/dist/cli/chunks/{coverage-QOOOITLD.js → coverage-DYST26FK.js} +3 -3
  149. package/dist/cli/chunks/cross-domain-router-FCM34JOR.js +2 -0
  150. package/dist/cli/chunks/{cursor-installer-SY3TRE2I.js → cursor-installer-LL6UWKTZ.js} +2 -2
  151. package/dist/cli/chunks/{daemon-HBSBIPUZ.js → daemon-6PIHFZNR.js} +3 -3
  152. package/dist/cli/chunks/{dag-attention-scheduler-ZNLUW2HL.js → dag-attention-scheduler-WS3HJW4F.js} +2 -2
  153. package/dist/cli/chunks/{detect-DMUJPGNC.js → detect-J4OITSUD.js} +2 -2
  154. package/dist/cli/chunks/{dist-node-4RPPRXUH.js → dist-node-QSLD5K6K.js} +2 -2
  155. package/dist/cli/chunks/{domain-handler-XJFDML77.js → domain-handler-BD53QZ4Q.js} +2 -2
  156. package/dist/cli/chunks/{domain-transfer-MXPKJ2A2.js → domain-transfer-VZBWINQL.js} +2 -2
  157. package/dist/cli/chunks/dream-6KCS7EWS.js +2 -0
  158. package/dist/cli/chunks/embed-and-insert-pattern-5UAFXNDX.js +3 -0
  159. package/dist/cli/chunks/{eval-DHBZ74RL.js → eval-GBKU6VTD.js} +2 -2
  160. package/dist/cli/chunks/{fast-paths-WTNFCV2I.js → fast-paths-MYZ6GITZ.js} +2 -2
  161. package/dist/cli/chunks/{feature-flags-VC7BQNHU.js → feature-flags-2WVV66AO.js} +2 -2
  162. package/dist/cli/chunks/{feature-flags-264QUQ3E.js → feature-flags-6ALWBTHS.js} +2 -2
  163. package/dist/cli/chunks/{file-discovery-LXQPIRKG.js → file-discovery-FOYCPGD6.js} +2 -2
  164. package/dist/cli/chunks/{fleet-4OAZWNXG.js → fleet-JROEDHAT.js} +3 -3
  165. package/dist/cli/chunks/{gnn-wrapper-MAXAOMTP.js → gnn-wrapper-KAXTFFEE.js} +2 -2
  166. package/dist/cli/chunks/{heartbeat-handler-ZTUI75EB.js → heartbeat-handler-PG24CBMQ.js} +4 -4
  167. package/dist/cli/chunks/{heartbeat-scheduler-VWPA7XKA.js → heartbeat-scheduler-LSS3RD6E.js} +2 -2
  168. package/dist/cli/chunks/hnsw-adapter-PG6O67CQ.js +2 -0
  169. package/dist/cli/chunks/hnsw-index-AHYZHLNZ.js +2 -0
  170. package/dist/cli/chunks/{hnsw-legacy-bridge-EQDYPKGL.js → hnsw-legacy-bridge-HYH4AJAO.js} +2 -2
  171. package/dist/cli/chunks/{hnswlib-node-G4QGTGIB.js → hnswlib-node-WTTST5LC.js} +2 -2
  172. package/dist/cli/chunks/hooks-RDZSAFQG.js +214 -0
  173. package/dist/cli/chunks/{hybrid-router-XODWORQ3.js → hybrid-router-HNPS6EFL.js} +2 -2
  174. package/dist/cli/chunks/{hypergraph-engine-T73DH7N6.js → hypergraph-engine-JUFXRXCC.js} +2 -2
  175. package/dist/cli/chunks/{hypergraph-handler-OZJJJW5B.js → hypergraph-handler-YFRF53TF.js} +3 -3
  176. package/dist/cli/chunks/impact-analyzer-USAJVJY5.js +2 -0
  177. package/dist/cli/chunks/{init-handler-YXXNCXM4.js → init-handler-P4W5F57S.js} +6 -6
  178. package/dist/cli/chunks/init-wizard-GL7LAZID.js +2 -0
  179. package/dist/cli/chunks/kernel-2YAIESTR.js +2 -0
  180. package/dist/cli/chunks/{kilocode-installer-3RCK2JPW.js → kilocode-installer-5VWY4DMH.js} +2 -2
  181. package/dist/cli/chunks/{kiro-installer-LKC42QRS.js → kiro-installer-PZC3BQII.js} +2 -2
  182. package/dist/cli/chunks/knowledge-graph-QSIYZRAG.js +2 -0
  183. package/dist/cli/chunks/{learning-BIBRKCYL.js → learning-4OH4ZG25.js} +3 -3
  184. package/dist/cli/chunks/{llm-router-Z6Z7TTBI.js → llm-router-LZBR6SZQ.js} +4 -4
  185. package/dist/cli/chunks/{load-T2QUB663.js → load-SPWP6VB3.js} +2 -2
  186. package/dist/cli/chunks/load-test-UEHSHLVN.js +2 -0
  187. package/dist/cli/chunks/{mcp-QBOL6TK4.js → mcp-QYPQMM7L.js} +2 -2
  188. package/dist/cli/chunks/{memory-7RQ2SF36.js → memory-54ILJMWQ.js} +5 -5
  189. package/dist/cli/chunks/memory-backend-4NE4ADPG.js +2 -0
  190. package/dist/cli/chunks/{memory-handlers-5OHDUBJS.js → memory-handlers-YK7H5UCX.js} +2 -2
  191. package/dist/cli/chunks/{multi-model-executor-PGSNT3NO.js → multi-model-executor-XAOAVPPI.js} +2 -2
  192. package/dist/cli/chunks/{opencode-installer-AEOXTTFG.js → opencode-installer-CNS4XMUF.js} +2 -2
  193. package/dist/cli/chunks/{orchestrator-6K2L36JA.js → orchestrator-SSEMSKUI.js} +6 -6
  194. package/dist/cli/chunks/{pipeline-MFQCW7JD.js → pipeline-DS3AENTB.js} +2 -2
  195. package/dist/cli/chunks/{platform-DM6RQ3FM.js → platform-BL6LH5NF.js} +2 -2
  196. package/dist/cli/chunks/{plugin-CCTGDC55.js → plugin-FNXPEQ2C.js} +2 -2
  197. package/dist/cli/chunks/{prime-radiant-advanced-wasm-J4FXB63L.js → prime-radiant-advanced-wasm-E6S6BGNA.js} +2 -2
  198. package/dist/cli/chunks/protocol-executor-YI4HNXND.js +2 -0
  199. package/dist/cli/chunks/{protocol-handler-7UOBNLET.js → protocol-handler-D4WIUU3W.js} +2 -2
  200. package/dist/cli/chunks/{prove-VAPGITFF.js → prove-OLB3PKW6.js} +2 -2
  201. package/dist/cli/chunks/{provider-manager-F6TLUJFW.js → provider-manager-GKTQ75DT.js} +2 -2
  202. package/dist/cli/chunks/qe-reasoning-bank-ANBAXQXC.js +2 -0
  203. package/dist/cli/chunks/{quality-7LJQI3SB.js → quality-ZYJVYTUL.js} +2 -2
  204. package/dist/cli/chunks/queen-coordinator-MYYUSWVX.js +2 -0
  205. package/dist/cli/chunks/{real-embeddings-NHWAUSV3.js → real-embeddings-SKJRHLCS.js} +2 -2
  206. package/dist/cli/chunks/{roocode-installer-HQFQJJPU.js → roocode-installer-WZGKOLWE.js} +2 -2
  207. package/dist/cli/chunks/router-RYCLZ7A4.js +2 -0
  208. package/dist/cli/chunks/routing-feedback-5KSRG2UI.js +2 -0
  209. package/dist/cli/chunks/{routing-handler-VH66WSPU.js → routing-handler-4GIMINCI.js} +2 -2
  210. package/dist/cli/chunks/{ruvector-commands-IPUWLJFU.js → ruvector-commands-YZONXZ2W.js} +2 -2
  211. package/dist/cli/chunks/{rvf-dual-writer-KRFEM6JH.js → rvf-dual-writer-WSS5GF54.js} +2 -2
  212. package/dist/cli/chunks/{rvf-migration-adapter-SVCZ72IU.js → rvf-migration-adapter-WS4HHVEU.js} +2 -2
  213. package/dist/cli/chunks/{rvf-migration-coordinator-FYBIF3SX.js → rvf-migration-coordinator-6BY5GI47.js} +2 -2
  214. package/dist/cli/chunks/rvf-native-adapter-NEIOLJRF.js +2 -0
  215. package/dist/cli/chunks/safe-db-3JQP4EPU.js +2 -0
  216. package/dist/cli/chunks/schedule-2QKCL64E.js +2 -0
  217. package/dist/cli/chunks/scheduler-FMOP45FC.js +2 -0
  218. package/dist/cli/chunks/{security-C2I6CG7B.js → security-HCNOL2K3.js} +3 -3
  219. package/dist/cli/chunks/shared-rvf-adapter-BMFIVWMJ.js +2 -0
  220. package/dist/cli/chunks/{shared-rvf-dual-writer-BPIFGN7I.js → shared-rvf-dual-writer-QRNLSDS7.js} +2 -2
  221. package/dist/cli/chunks/sqlite-persistence-I5RYLFOE.js +2 -0
  222. package/dist/cli/chunks/{status-handler-57UA6GNR.js → status-handler-QXZ442MY.js} +2 -2
  223. package/dist/cli/chunks/{structural-health-KMHBG6FO.js → structural-health-OFYZ3Z4A.js} +2 -2
  224. package/dist/cli/chunks/{sync-53YM6U4S.js → sync-J4BG65NF.js} +2 -2
  225. package/dist/cli/chunks/{task-handler-W2XPS5WW.js → task-handler-UBSFCKK3.js} +2 -2
  226. package/dist/cli/chunks/{task-handlers-BG4IAMBJ.js → task-handlers-JFUT2FQ7.js} +2 -2
  227. package/dist/cli/chunks/{test-QJBBVPL2.js → test-WTNAHJHH.js} +4 -4
  228. package/dist/cli/chunks/{test-scheduling-Y4J6EY2K.js → test-scheduling-QREBYRGW.js} +3 -3
  229. package/dist/cli/chunks/{token-bootstrap-3TKR3UIE.js → token-bootstrap-HE5H77OL.js} +2 -2
  230. package/dist/cli/chunks/{token-usage-5FUNHHVZ.js → token-usage-V5B6K3JL.js} +2 -2
  231. package/dist/cli/chunks/{transformers-KVPA35SR.js → transformers-HIVMQP4O.js} +2 -2
  232. package/dist/cli/chunks/{tree-sitter-wasm-parser-LTBBLY5U.js → tree-sitter-wasm-parser-WP2SF2M5.js} +2 -2
  233. package/dist/cli/chunks/{types-Y2BHPD6B.js → types-7ZBTAO5Z.js} +2 -2
  234. package/dist/cli/chunks/unified-memory-2ETCY22B.js +2 -0
  235. package/dist/cli/chunks/unified-memory-hnsw-OALJW537.js +2 -0
  236. package/dist/cli/chunks/unified-persistence-SQMP7A3O.js +2 -0
  237. package/dist/cli/chunks/{upgrade-E4VAQZQR.js → upgrade-WIFAJDBG.js} +2 -2
  238. package/dist/cli/chunks/{validate-4ICDQCKJ.js → validate-W63V36GA.js} +2 -2
  239. package/dist/cli/chunks/{validate-swarm-AIEOQOUF.js → validate-swarm-CK5BM3YY.js} +2 -2
  240. package/dist/cli/chunks/{vibium-AF2K6YXR.js → vibium-MJCCO36E.js} +2 -2
  241. package/dist/cli/chunks/visual-security-JUJPF2QO.js +2 -0
  242. package/dist/cli/chunks/{web-tree-sitter-PM67K5SP.js → web-tree-sitter-ESERXLPK.js} +2 -2
  243. package/dist/cli/chunks/{windsurf-installer-4MKUQ2KT.js → windsurf-installer-FDWQ5BWI.js} +2 -2
  244. package/dist/cli/chunks/{witness-chain-FLPF7CS6.js → witness-chain-L5KSYE2S.js} +2 -2
  245. package/dist/cli/chunks/witness-chain-QJVKAAZT.js +2 -0
  246. package/dist/cli/chunks/{workflow-DHTCI6QD.js → workflow-34GYJDFW.js} +4 -4
  247. package/dist/cli/chunks/workflow-orchestrator-WXB2RVVW.js +2 -0
  248. package/dist/cli/chunks/{wrappers-5K6UGI3T.js → wrappers-VGKEBQLW.js} +2 -2
  249. package/dist/cli/commands/hooks-handlers/command-hooks.js +104 -11
  250. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.d.ts +98 -0
  251. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +285 -1
  252. package/dist/cli/commands/hooks-handlers/hooks-shared.d.ts +20 -1
  253. package/dist/cli/commands/hooks-handlers/hooks-shared.js +35 -3
  254. package/dist/cli/commands/hooks-handlers/routing-hooks.js +15 -5
  255. package/dist/cli/commands/hooks-handlers/task-hooks.js +216 -5
  256. package/dist/coordination/handlers/test-execution-handlers.d.ts +18 -0
  257. package/dist/coordination/handlers/test-execution-handlers.js +77 -9
  258. package/dist/coordination/task-executor.js +11 -2
  259. package/dist/domains/test-generation/generators/jest-vitest-generator.js +13 -3
  260. package/dist/domains/test-generation/interfaces.d.ts +12 -0
  261. package/dist/domains/test-generation/services/test-generator.js +5 -1
  262. package/dist/governance/continue-gate-integration.d.ts +13 -0
  263. package/dist/governance/continue-gate-integration.js +31 -8
  264. package/dist/init/phases/07-hooks.js +2 -2
  265. package/dist/integrations/ruvector/hypergraph-engine.js +63 -4
  266. package/dist/integrations/ruvector/hypergraph-schema.d.ts +6 -2
  267. package/dist/learning/embed-and-insert-pattern.d.ts +36 -0
  268. package/dist/learning/embed-and-insert-pattern.js +52 -0
  269. package/dist/learning/pattern-store.d.ts +8 -0
  270. package/dist/learning/pattern-store.js +66 -43
  271. package/dist/mcp/bundle.js +400 -392
  272. package/dist/mcp/entry.js +21 -1
  273. package/dist/mcp/protocol-server.js +6 -1
  274. package/dist/mcp/tools/coverage-analysis/index.js +11 -2
  275. package/dist/workers/workers/learning-consolidation.js +6 -1
  276. package/package.json +1 -1
  277. package/dist/cli/chunks/adapter-2BIT6BGH.js +0 -2
  278. package/dist/cli/chunks/aqe-learning-engine-B5G3RG4W.js +0 -2
  279. package/dist/cli/chunks/base-A3ZRMSIZ.js +0 -2
  280. package/dist/cli/chunks/browser-workflow-C6Z53ZH6.js +0 -2
  281. package/dist/cli/chunks/chunk-2ARCG4XJ.js +0 -2
  282. package/dist/cli/chunks/chunk-JC4O47QG.js +0 -66
  283. package/dist/cli/chunks/chunk-KTJWRVFR.js +0 -15
  284. package/dist/cli/chunks/client-B3QSCZSJ.js +0 -2
  285. package/dist/cli/chunks/cross-domain-router-OYBTXKCV.js +0 -2
  286. package/dist/cli/chunks/dream-R2F6L47W.js +0 -2
  287. package/dist/cli/chunks/hnsw-adapter-TQPQE4OJ.js +0 -2
  288. package/dist/cli/chunks/hnsw-index-2X3NMTDU.js +0 -2
  289. package/dist/cli/chunks/hooks-RBVHAPBL.js +0 -101
  290. package/dist/cli/chunks/impact-analyzer-B7GBDSA3.js +0 -2
  291. package/dist/cli/chunks/init-wizard-7N6MCER4.js +0 -2
  292. package/dist/cli/chunks/kernel-6CJ4FP5Z.js +0 -2
  293. package/dist/cli/chunks/knowledge-graph-4XYLO6ZW.js +0 -2
  294. package/dist/cli/chunks/load-test-UODCPBYF.js +0 -2
  295. package/dist/cli/chunks/memory-backend-PUPAE4QQ.js +0 -2
  296. package/dist/cli/chunks/protocol-executor-X3EYJINP.js +0 -2
  297. package/dist/cli/chunks/qe-reasoning-bank-3RDWPSYG.js +0 -2
  298. package/dist/cli/chunks/queen-coordinator-XIQZIYAZ.js +0 -2
  299. package/dist/cli/chunks/router-AFEFPU2A.js +0 -2
  300. package/dist/cli/chunks/routing-feedback-AGYMQFMV.js +0 -2
  301. package/dist/cli/chunks/rvf-native-adapter-AFOWXCZH.js +0 -2
  302. package/dist/cli/chunks/safe-db-NNF5DE5T.js +0 -2
  303. package/dist/cli/chunks/schedule-HJUZSHEA.js +0 -2
  304. package/dist/cli/chunks/scheduler-DZ53RPJQ.js +0 -2
  305. package/dist/cli/chunks/shared-rvf-adapter-5UQSTUSR.js +0 -2
  306. package/dist/cli/chunks/sqlite-persistence-27ESC5DX.js +0 -2
  307. package/dist/cli/chunks/unified-memory-O7GFUSD3.js +0 -2
  308. package/dist/cli/chunks/unified-memory-hnsw-XBLROJEN.js +0 -2
  309. package/dist/cli/chunks/unified-persistence-YBHEAL2S.js +0 -2
  310. package/dist/cli/chunks/visual-security-4F7VYCAU.js +0 -2
  311. package/dist/cli/chunks/witness-chain-AXJ44BGW.js +0 -2
  312. package/dist/cli/chunks/workflow-orchestrator-UAFUPHD3.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.9.17");process.exit(0)}
2
- import{b as dl,c as ml}from"./chunk-QW554DTP.js";import{a as pl}from"./chunk-K4FG3CRS.js";import{a as hl}from"./chunk-Y47U7ICT.js";import{d as Tl}from"./chunk-EVQYUUQ3.js";import{a as D,b as $r,c as Ee,d as Yi,e as Xi,f as Zi,g as tt,h as Ma,i as Ge}from"./chunk-OSBJWQZL.js";import{a as fl,c as yl}from"./chunk-42TUEMH7.js";import{a as Fa,b as en,c as La,d as Nr,e as $a,f as Oa,g as Vr,h as Na,i as tn}from"./chunk-KTJWRVFR.js";import{a as al}from"./chunk-WP55YBB2.js";import{a as bl,b as wl,e as Cl}from"./chunk-CZXV3JAF.js";import{o as Sl,s as Rl}from"./chunk-6PCGUJCG.js";import{a as ll}from"./chunk-HQXRCW7Z.js";import{e as sn,l as an,q as Gm}from"./chunk-PV6WBC2D.js";import{a as gl,j as Ie}from"./chunk-ORNWQXEX.js";import{c as _r}from"./chunk-W5HTZ3VZ.js";import{g as vl}from"./chunk-PEHHOJE6.js";import{a as Br}from"./chunk-CQSU7NTG.js";import{a as x,b as Or,c as Ct,d as St,e as zr,f as De,g as Rt}from"./chunk-I3NUJ6KJ.js";import{c as nn}from"./chunk-JC4O47QG.js";import{b as _a}from"./chunk-QVJQXRHU.js";import{f as qm}from"./chunk-CPZUNBSQ.js";import{c as Ji,d as ul}from"./chunk-L5JZIORJ.js";import{f as cl,o as Yt}from"./chunk-B36RPXAQ.js";import{a as M}from"./chunk-2ARCG4XJ.js";import{c as R}from"./chunk-65Z6HMDA.js";import{b as Va,d as rn}from"./chunk-32FWC6G3.js";import{b as E,d as H}from"./chunk-6YFEWIL5.js";import{a as be,b as f,c as p}from"./chunk-UTO2M76W.js";import{a as T,b as y,c as A}from"./chunk-DJXYFFGA.js";import{i as v}from"./chunk-Z5R46W6Q.js";import{a as Da}from"./chunk-6PRIY3HT.js";import{a as L,b as le,d as se}from"./chunk-K44EQV74.js";import{a as ol,c as Lr,d as ka,e as Ia}from"./chunk-MER7IHAZ.js";import{a as et,b as vt,c as Qi,d as Ki}from"./chunk-ARN2KDLJ.js";import{S as qe,b as bt,n as wt}from"./chunk-QXOAFWWK.js";import{a as Pa,c as Be,e as Kt,g as Jt}from"./chunk-XB4JRJU4.js";var Il={};Kt(Il,{ALL_SUPPORTED_LANGUAGES:()=>Ym,ALL_TEST_FRAMEWORKS:()=>mn,DEFAULT_FRAMEWORKS:()=>Ga,FRAMEWORK_ALIASES:()=>Pl,FRAMEWORK_TO_LANGUAGE:()=>Jm,LANGUAGE_FILE_EXTENSIONS:()=>kl,getLanguageFromExtension:()=>rt,resolveFrameworkAlias:()=>pn});function pn(u){let t=u.toLowerCase().trim();return mn.includes(t)?t:Pl[t]}function rt(u){return kl[u.startsWith(".")?u:`.${u}`]}var Ga,Pl,Jm,kl,mn,Ym,Zt=Be(()=>{"use strict";Ga={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"},Pl={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"},Jm={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"},kl={".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"},mn=["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"],Ym=["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]});function Ja(u,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.9.19");process.exit(0)}
2
+ import{b as dl,c as ml}from"./chunk-2SIQ742L.js";import{a as pl}from"./chunk-FT3MAIRW.js";import{a as hl}from"./chunk-IG2RCBHJ.js";import{d as Tl}from"./chunk-FNVA7U7X.js";import{a as D,b as $r,c as Ee,d as Yi,e as Xi,f as Zi,g as tt,h as Ma,i as Ge}from"./chunk-MMVSIESL.js";import{a as fl,c as yl}from"./chunk-JYHZK44T.js";import{a as Fa,b as en,c as La,d as Nr,e as $a,f as Oa,g as Vr,h as Na,i as tn}from"./chunk-GJ5FON37.js";import{a as al}from"./chunk-M6EP724N.js";import{a as bl,b as wl,e as Cl}from"./chunk-G2V4GMPR.js";import{o as Sl,s as Rl}from"./chunk-GL742O2V.js";import{a as ll}from"./chunk-JLX35EPX.js";import{e as sn,l as an,q as Gm}from"./chunk-SRKBR4DU.js";import{a as gl,j as Ie}from"./chunk-37DTXQ6P.js";import{c as _r}from"./chunk-I3JRRFVT.js";import{g as vl}from"./chunk-NXO7CT5K.js";import{a as Br}from"./chunk-SLDYG7LC.js";import{a as x,b as Or,c as Ct,d as St,e as zr,f as De,g as Rt}from"./chunk-FPVXXQVX.js";import{c as nn}from"./chunk-R5IL3XD5.js";import{b as _a}from"./chunk-DAPBSAVT.js";import{f as qm}from"./chunk-OEQCZBBM.js";import{c as Ji,d as ul}from"./chunk-EZZJ5XD6.js";import{f as cl,o as Yt}from"./chunk-TXCOK5DC.js";import{a as M}from"./chunk-Z2E5DTKX.js";import{c as R}from"./chunk-5KGFDNYI.js";import{b as Va,d as rn}from"./chunk-U2WMCNNR.js";import{b as E,d as H}from"./chunk-5R2DUR3A.js";import{a as be,b as f,c as p}from"./chunk-N2PLNYEV.js";import{a as T,b as y,c as A}from"./chunk-5MGRZ4YD.js";import{i as v}from"./chunk-MIQAFOFO.js";import{a as Da}from"./chunk-2XATUQIG.js";import{a as L,b as le,d as se}from"./chunk-SKNHAGYP.js";import{a as ol,c as Lr,d as ka,e as Ia}from"./chunk-WZUQT2BE.js";import{a as et,b as vt,c as Qi,d as Ki}from"./chunk-IV74GAZN.js";import{S as qe,b as bt,n as wt}from"./chunk-W3IO4FQ5.js";import{a as Pa,c as Be,e as Kt,g as Jt}from"./chunk-WULMXLNN.js";var Il={};Kt(Il,{ALL_SUPPORTED_LANGUAGES:()=>Ym,ALL_TEST_FRAMEWORKS:()=>mn,DEFAULT_FRAMEWORKS:()=>Ga,FRAMEWORK_ALIASES:()=>Pl,FRAMEWORK_TO_LANGUAGE:()=>Jm,LANGUAGE_FILE_EXTENSIONS:()=>kl,getLanguageFromExtension:()=>rt,resolveFrameworkAlias:()=>pn});function pn(u){let t=u.toLowerCase().trim();return mn.includes(t)?t:Pl[t]}function rt(u){return kl[u.startsWith(".")?u:`.${u}`]}var Ga,Pl,Jm,kl,mn,Ym,Zt=Be(()=>{"use strict";Ga={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"},Pl={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"},Jm={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"},kl={".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"},mn=["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"],Ym=["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]});function Ja(u,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
 
@@ -114,7 +114,7 @@ Always explain your reasoning clearly.
114
114
  Format your response with: verdict (confirmed/rejected/uncertain), confidence (0-100), and reasoning.`}}});import{randomUUID as Jv}from"crypto";Ia();var za={LOOP_WARNING:"loop.warning",LOOP_DETECTED:"loop.detected"},on=class{subscriptions=new Map;subscriptionsByEventType=new Map;subscriptionsByChannel=new Map;wildcardSubscriptions=new Set;eventHistory;maxHistorySize=ka.MAX_HISTORY_SIZE;subscriptionCounter=0;middlewares=[];constructor(t=ka.MAX_HISTORY_SIZE){this.maxHistorySize=t,this.eventHistory=new al(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 c=this.subscriptions.get(o);!c||!c.active||c.channel&&c.channel!==e.source||c.eventType!=="*"&&c.eventType!==e.type||s.push(c)}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=[]}};Ia();var cn=class{agents=new Map;maxAgents;memoryBranch=null;constructor(t=Lr.MAX_CONCURRENT_AGENTS){this.maxAgents=t}setMemoryBranch(t){this.memoryBranch=t}async spawn(t){if(!this.canSpawn())return p(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 c=new Ba(t.progressiveContext).predictFilesForTask(s,a);e={...e,availableFiles:c,contextFiles:c,initialFiles:c,progressiveContextApplied:!0}}}catch{}let i=v(),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"?p(new Error(`Agent ${t} is not running (status: ${e.status})`)):(e.status="completed",e.completedAt=new Date,f(void 0)):p(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=Lr.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}},Hm={strategy:"full",maxInitialFiles:10,predictionThreshold:.7,trackFileRequests:!0},Ba=class{config;fileRequests=[];preloadedFiles=new Set;constructor(t){this.config={...Hm,...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}};M();var Wm=R.create("plugin-loader"),qr=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 c of o)t.includes(c)&&n(c);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){Wm.debug("Plugin unload failed, force removing",{domain:e,error:r instanceof Error?r.message:String(r)}),this.plugins.delete(e)}}};Ki();M();var qa=R.create("anti-drift-middleware"),jm={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 Al(u){let t=2166136261;for(let e=0;e<u.length;e++)t^=u.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}var ln=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(t){this.config={...jm,...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(c=>c.timestamp>=s);a>0?n.splice(0,a):a===-1&&(n.length=0,n.push(i));let o=n.filter(c=>c.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=Al(r),n=`${t}:${r}`;return{hash:Al(n),toolName:t,argsFingerprint:i,timestamp:Date.now()}}},xl={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},Um={thresholds:xl,agentId:"unknown",maxHistorySize:200,fallbackDimension:64};function Qm(u,t){let e=new Float64Array(t),r=2166136261,i=16777619;for(let a=0;a<u.length;a++){let o=u.charCodeAt(a);r^=o,r=Math.imul(r,16777619),i^=o,i=Math.imul(i,2166136261);let c=(r>>>0)%t;e[c]+=(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 El=!1,Xt=!1,un=null;async function Km(){if(El)return Xt;El=!0;try{let u=await import("./real-embeddings-NHWAUSV3.js");if(typeof u.isTransformerAvailable=="function"&&u.isTransformerAvailable())un=u.computeRealEmbedding,Xt=!0;else try{await u.computeRealEmbedding("probe"),un=u.computeRealEmbedding,Xt=!0}catch(t){qa.debug("Transformer probe embedding failed",{error:t instanceof Error?t.message:String(t)}),Xt=!1}}catch(u){qa.debug("Transformer module import failed",{error:u instanceof Error?u.message:String(u)}),Xt=!1}return Xt}var dn=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;constructor(t){this.config={...Um,...t,thresholds:{...xl,...t?.thresholds}}}async onEmit(t){let e=JSON.stringify(t.payload),r=await this.embed(e),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{...t,semanticFingerprint:s}}async onReceive(t){let e=t.semanticFingerprint;if(!e)return t;let r=JSON.stringify(t.payload),i=await this.embed(r),n=et(i,e.embedding),a=1-n>e.driftThreshold;this.totalChecked++,this.similaritySum+=n;let o={drifted:a,cosineSimilarity:n,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)return this.driftCount++,await this.emitDriftEvent(t,o),null;let c={...e,hopCount:e.hopCount+1};return{...t,semanticFingerprint:c}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0}}validateConfig(){for(let[t,e]of Object.entries(this.config.thresholds))if(typeof e!="number"||e<0||e>1)return p(new Error(`Invalid threshold for "${t}": must be between 0 and 1, got ${e}`));return this.config.maxHistorySize<=0?p(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?p(new Error("fallbackDimension must be positive")):f(void 0)}async embed(t){return await Km()&&un?un(t):Qm(t,this.config.fallbackDimension)}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"}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){qa.debug("onDriftDetected callback failed",{error:i instanceof Error?i.message:String(i)})}}};Ia();Yt();import*as Qt from"path";import*as xa from"fs";A();var W=class{constructor(t,e){this.eventBus=t;this.memory=e}eventBus;memory;_initialized=!1;_health={status:"idle",agents:{total:0,active:0,idle:0,failed:0},errors:[]};_minCutBridge;_consensusConfig;isReady(){return this._initialized}getHealth(){return{...this._health}}async initialize(){this._initialized||(await this.onInitialize(),this.subscribeToEvents(),this._initialized=!0)}async dispose(){await this.onDispose(),this._initialized=!1}async handleEvent(t){await this.onEvent(t)}async onInitialize(){}async onDispose(){}async onEvent(t){}subscribeToEvents(){}async publishEvent(t,e){let r={id:crypto.randomUUID(),type:t,timestamp:new Date,source:this.name,payload:e};await this.eventBus.publish(r)}updateHealth(t){this._health={...this._health,...t}}setMinCutBridge(t){this._minCutBridge=t,this.onMinCutBridgeSet(t)}getMinCutBridge(){return this._minCutBridge}setConsensusConfig(t){this._consensusConfig=t,this.onConsensusConfigSet(t)}getConsensusConfig(){return this._consensusConfig}setIntegrationConfig(t){t.minCutBridge&&this.setMinCutBridge(t.minCutBridge),t.consensusConfig&&this.setConsensusConfig(t.consensusConfig)}hasMinCutIntegration(){return this._minCutBridge!==void 0}hasConsensusEnabled(){return this._consensusConfig?.enabled===!0}onMinCutBridgeSet(t){}onConsensusConfigSet(t){}getTaskHandlers(){return new Map}canHandleTask(t){return this.getTaskHandlers().has(t)}async executeTask(t,e){let i=this.getTaskHandlers().get(t.taskType);return i?(this.runTaskAsync(t,i,e),f(void 0)):p(new Error(`Domain ${this.name} has no handler for task type: ${t.taskType}`))}async runTaskAsync(t,e,r){let i=Date.now();try{let n=await e(t.payload),s=Date.now()-i,a={taskId:t.taskId,success:n.success,data:n.success?n.value:void 0,error:n.success?void 0:n.error?.message,duration:s};if(await r(a),n.success)this.updateHealth({lastActivity:new Date,agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),idle:this._health.agents.idle+1}});else{let o=n.error?.message??"Unknown error";this.updateHealth({lastActivity:new Date,errors:[...this._health.errors.slice(-9),o],agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),failed:this._health.agents.failed+1}})}}catch(n){let s=Date.now()-i,a=T(n);await r({taskId:t.taskId,success:!1,error:a,duration:s}),this.updateHealth({lastActivity:new Date,errors:[...this._health.errors.slice(-9),a],agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),failed:this._health.agents.failed+1}})}}};M();A();M();import*as Gl from"fs";import*as ri from"path";Zt();import{randomBytes as Xm,randomInt as it,randomUUID as Zm}from"node:crypto";function Dl(u){return Xm(u).toString("hex")}var I={uuid:()=>Zm(),email:()=>`user_${Dl(3)}@example.com`,fullName:()=>{let u=["Alice","Bob","Carol","Dave","Eve","Frank"],t=["Smith","Jones","Lee","Garcia","Chen","Novak"];return`${u[it(u.length)]} ${t[it(t.length)]}`},url:()=>`https://example.com/${Dl(4)}`,recentDate:()=>new Date(Date.now()-it(7*864e5)).toISOString(),phone:()=>`+1${String(it(2e9,9999999999))}`,streetAddress:()=>`${it(1,9999)} Main St`,word:()=>{let u=["alpha","bravo","charlie","delta","echo","foxtrot","golf","hotel"];return u[it(u.length)]},int:(u=1,t=100)=>{if(u>t){let e=u;u=t,t=e}return it(u,t+1)},float:(u=0,t=100,e=2)=>{if(u>t){let i=u;u=t,t=i}if(u===t)return u;let r=u+it(0,1000001)/1e6*(t-u);return Number(r.toFixed(e))}};var J=class u{static NAME_VALUE_TABLE=[["id",()=>`'${I.uuid()}'`],["email",()=>`'${I.email()}'`],["name",()=>`'${I.fullName()}'`],["url",()=>`'${I.url()}'`],["date",()=>`new Date('${I.recentDate()}')`],["phone",()=>`'${I.phone()}'`],["address",()=>`'${I.streetAddress()}'`]];static TYPE_VALUE_TABLE=[["string",()=>`'${I.word()}'`],["number",()=>String(I.int(1,100))],["boolean",()=>"true"],["[]",()=>"[]"],["array",()=>"[]"],["object",()=>"{}"],["{",()=>"{}"],["function",()=>"() => {}"],["promise",()=>"Promise.resolve()"],["date",()=>"new Date()"]];generateTestValue(t){if(t.defaultValue)return t.defaultValue;let e=t.type?.toLowerCase()||"unknown",r=t.name.toLowerCase();for(let[i,n]of u.NAME_VALUE_TABLE)if(r.includes(i))return n();for(let[i,n]of u.TYPE_VALUE_TABLE)if(e.includes(i))return n();return`{} /* TODO: provide ${t.name}: ${t.type||"unknown"} */`}generateTestCasesForFunction(t){let e=[],r=t.parameters.map(c=>this.generateTestValue(c)).join(", "),i=t.isAsync?`await ${t.name}(${r})`:`${t.name}(${r})`,n=t.returnType==="void"||t.returnType==="Promise<void>",s="expect(result).toBeDefined();";if(!n){if(/^(is|has|can)[A-Z]/.test(t.name))s="expect(typeof result).toBe('boolean');";else if(/^(get|fetch|find)[A-Z]/.test(t.name))s="expect(result).not.toBeUndefined();";else if(/^(create|build|make)[A-Z]/.test(t.name))s="expect(result).toBeTruthy();";else if(t.returnType){let c=t.returnType.toLowerCase().replace(/promise<(.+)>/,"$1");c.includes("{")?s="expect(typeof result).toBe('object');":c==="boolean"?s="expect(typeof result).toBe('boolean');":c==="number"?s="expect(typeof result).toBe('number');":c==="string"?s="expect(typeof result).toBe('string');":c.includes("[]")||c.includes("array")?s="expect(Array.isArray(result)).toBe(true);":c.includes("boolean")?s="expect(typeof result).toBe('boolean');":c.includes("number")?s="expect(typeof result).toBe('number');":c.includes("string")&&(s="expect(typeof result).toBe('string');")}}e.push({description:"should handle valid input correctly",type:"happy-path",action:n?`${i};`:`const result = ${i};`,assertion:n?"// void function \u2014 no return value to assert":s});let a=t.body||"",o=/\bthrow\b/.test(a)||/\bvalidat/i.test(a);for(let c of t.parameters){if(!c.optional){let l=t.parameters.map(d=>d.name===c.name?"undefined":this.generateTestValue(d)).join(", ");if(o)e.push({description:`should handle undefined ${c.name}`,type:"error-handling",action:t.isAsync?`const action = async () => await ${t.name}(${l});`:`const action = () => ${t.name}(${l});`,assertion:"expect(action).toThrow();"});else{let d=t.isAsync?`await ${t.name}(${l})`:`${t.name}(${l})`;e.push({description:`should handle undefined ${c.name}`,type:"edge-case",action:t.isAsync?`let threw = false;
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 c of o)t.includes(c)&&n(c);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){Wm.debug("Plugin unload failed, force removing",{domain:e,error:r instanceof Error?r.message:String(r)}),this.plugins.delete(e)}}};Ki();M();var qa=R.create("anti-drift-middleware"),jm={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 Al(u){let t=2166136261;for(let e=0;e<u.length;e++)t^=u.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}var ln=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(t){this.config={...jm,...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(c=>c.timestamp>=s);a>0?n.splice(0,a):a===-1&&(n.length=0,n.push(i));let o=n.filter(c=>c.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=Al(r),n=`${t}:${r}`;return{hash:Al(n),toolName:t,argsFingerprint:i,timestamp:Date.now()}}},xl={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},Um={thresholds:xl,agentId:"unknown",maxHistorySize:200,fallbackDimension:64};function Qm(u,t){let e=new Float64Array(t),r=2166136261,i=16777619;for(let a=0;a<u.length;a++){let o=u.charCodeAt(a);r^=o,r=Math.imul(r,16777619),i^=o,i=Math.imul(i,2166136261);let c=(r>>>0)%t;e[c]+=(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 El=!1,Xt=!1,un=null;async function Km(){if(El)return Xt;El=!0;try{let u=await import("./real-embeddings-SKJRHLCS.js");if(typeof u.isTransformerAvailable=="function"&&u.isTransformerAvailable())un=u.computeRealEmbedding,Xt=!0;else try{await u.computeRealEmbedding("probe"),un=u.computeRealEmbedding,Xt=!0}catch(t){qa.debug("Transformer probe embedding failed",{error:t instanceof Error?t.message:String(t)}),Xt=!1}}catch(u){qa.debug("Transformer module import failed",{error:u instanceof Error?u.message:String(u)}),Xt=!1}return Xt}var dn=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;constructor(t){this.config={...Um,...t,thresholds:{...xl,...t?.thresholds}}}async onEmit(t){let e=JSON.stringify(t.payload),r=await this.embed(e),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{...t,semanticFingerprint:s}}async onReceive(t){let e=t.semanticFingerprint;if(!e)return t;let r=JSON.stringify(t.payload),i=await this.embed(r),n=et(i,e.embedding),a=1-n>e.driftThreshold;this.totalChecked++,this.similaritySum+=n;let o={drifted:a,cosineSimilarity:n,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)return this.driftCount++,await this.emitDriftEvent(t,o),null;let c={...e,hopCount:e.hopCount+1};return{...t,semanticFingerprint:c}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0}}validateConfig(){for(let[t,e]of Object.entries(this.config.thresholds))if(typeof e!="number"||e<0||e>1)return p(new Error(`Invalid threshold for "${t}": must be between 0 and 1, got ${e}`));return this.config.maxHistorySize<=0?p(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?p(new Error("fallbackDimension must be positive")):f(void 0)}async embed(t){return await Km()&&un?un(t):Qm(t,this.config.fallbackDimension)}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"}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){qa.debug("onDriftDetected callback failed",{error:i instanceof Error?i.message:String(i)})}}};Ia();Yt();import*as Qt from"path";import*as xa from"fs";A();var W=class{constructor(t,e){this.eventBus=t;this.memory=e}eventBus;memory;_initialized=!1;_health={status:"idle",agents:{total:0,active:0,idle:0,failed:0},errors:[]};_minCutBridge;_consensusConfig;isReady(){return this._initialized}getHealth(){return{...this._health}}async initialize(){this._initialized||(await this.onInitialize(),this.subscribeToEvents(),this._initialized=!0)}async dispose(){await this.onDispose(),this._initialized=!1}async handleEvent(t){await this.onEvent(t)}async onInitialize(){}async onDispose(){}async onEvent(t){}subscribeToEvents(){}async publishEvent(t,e){let r={id:crypto.randomUUID(),type:t,timestamp:new Date,source:this.name,payload:e};await this.eventBus.publish(r)}updateHealth(t){this._health={...this._health,...t}}setMinCutBridge(t){this._minCutBridge=t,this.onMinCutBridgeSet(t)}getMinCutBridge(){return this._minCutBridge}setConsensusConfig(t){this._consensusConfig=t,this.onConsensusConfigSet(t)}getConsensusConfig(){return this._consensusConfig}setIntegrationConfig(t){t.minCutBridge&&this.setMinCutBridge(t.minCutBridge),t.consensusConfig&&this.setConsensusConfig(t.consensusConfig)}hasMinCutIntegration(){return this._minCutBridge!==void 0}hasConsensusEnabled(){return this._consensusConfig?.enabled===!0}onMinCutBridgeSet(t){}onConsensusConfigSet(t){}getTaskHandlers(){return new Map}canHandleTask(t){return this.getTaskHandlers().has(t)}async executeTask(t,e){let i=this.getTaskHandlers().get(t.taskType);return i?(this.runTaskAsync(t,i,e),f(void 0)):p(new Error(`Domain ${this.name} has no handler for task type: ${t.taskType}`))}async runTaskAsync(t,e,r){let i=Date.now();try{let n=await e(t.payload),s=Date.now()-i,a={taskId:t.taskId,success:n.success,data:n.success?n.value:void 0,error:n.success?void 0:n.error?.message,duration:s};if(await r(a),n.success)this.updateHealth({lastActivity:new Date,agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),idle:this._health.agents.idle+1}});else{let o=n.error?.message??"Unknown error";this.updateHealth({lastActivity:new Date,errors:[...this._health.errors.slice(-9),o],agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),failed:this._health.agents.failed+1}})}}catch(n){let s=Date.now()-i,a=T(n);await r({taskId:t.taskId,success:!1,error:a,duration:s}),this.updateHealth({lastActivity:new Date,errors:[...this._health.errors.slice(-9),a],agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),failed:this._health.agents.failed+1}})}}};M();A();M();import*as Gl from"fs";import*as ri from"path";Zt();import{randomBytes as Xm,randomInt as it,randomUUID as Zm}from"node:crypto";function Dl(u){return Xm(u).toString("hex")}var I={uuid:()=>Zm(),email:()=>`user_${Dl(3)}@example.com`,fullName:()=>{let u=["Alice","Bob","Carol","Dave","Eve","Frank"],t=["Smith","Jones","Lee","Garcia","Chen","Novak"];return`${u[it(u.length)]} ${t[it(t.length)]}`},url:()=>`https://example.com/${Dl(4)}`,recentDate:()=>new Date(Date.now()-it(7*864e5)).toISOString(),phone:()=>`+1${String(it(2e9,9999999999))}`,streetAddress:()=>`${it(1,9999)} Main St`,word:()=>{let u=["alpha","bravo","charlie","delta","echo","foxtrot","golf","hotel"];return u[it(u.length)]},int:(u=1,t=100)=>{if(u>t){let e=u;u=t,t=e}return it(u,t+1)},float:(u=0,t=100,e=2)=>{if(u>t){let i=u;u=t,t=i}if(u===t)return u;let r=u+it(0,1000001)/1e6*(t-u);return Number(r.toFixed(e))}};var J=class u{static NAME_VALUE_TABLE=[["id",()=>`'${I.uuid()}'`],["email",()=>`'${I.email()}'`],["name",()=>`'${I.fullName()}'`],["url",()=>`'${I.url()}'`],["date",()=>`new Date('${I.recentDate()}')`],["phone",()=>`'${I.phone()}'`],["address",()=>`'${I.streetAddress()}'`]];static TYPE_VALUE_TABLE=[["string",()=>`'${I.word()}'`],["number",()=>String(I.int(1,100))],["boolean",()=>"true"],["[]",()=>"[]"],["array",()=>"[]"],["object",()=>"{}"],["{",()=>"{}"],["function",()=>"() => {}"],["promise",()=>"Promise.resolve()"],["date",()=>"new Date()"]];generateTestValue(t){if(t.defaultValue)return t.defaultValue;let e=t.type?.toLowerCase()||"unknown",r=t.name.toLowerCase();for(let[i,n]of u.NAME_VALUE_TABLE)if(r.includes(i))return n();for(let[i,n]of u.TYPE_VALUE_TABLE)if(e.includes(i))return n();return`{} /* TODO: provide ${t.name}: ${t.type||"unknown"} */`}generateTestCasesForFunction(t){let e=[],r=t.parameters.map(c=>this.generateTestValue(c)).join(", "),i=t.isAsync?`await ${t.name}(${r})`:`${t.name}(${r})`,n=t.returnType==="void"||t.returnType==="Promise<void>",s="expect(result).toBeDefined();";if(!n){if(/^(is|has|can)[A-Z]/.test(t.name))s="expect(typeof result).toBe('boolean');";else if(/^(get|fetch|find)[A-Z]/.test(t.name))s="expect(result).not.toBeUndefined();";else if(/^(create|build|make)[A-Z]/.test(t.name))s="expect(result).toBeTruthy();";else if(t.returnType){let c=t.returnType.toLowerCase().replace(/promise<(.+)>/,"$1");c.includes("{")?s="expect(typeof result).toBe('object');":c==="boolean"?s="expect(typeof result).toBe('boolean');":c==="number"?s="expect(typeof result).toBe('number');":c==="string"?s="expect(typeof result).toBe('string');":c.includes("[]")||c.includes("array")?s="expect(Array.isArray(result)).toBe(true);":c.includes("boolean")?s="expect(typeof result).toBe('boolean');":c.includes("number")?s="expect(typeof result).toBe('number');":c.includes("string")&&(s="expect(typeof result).toBe('string');")}}e.push({description:"should handle valid input correctly",type:"happy-path",action:n?`${i};`:`const result = ${i};`,assertion:n?"// void function \u2014 no return value to assert":s});let a=t.body||"",o=/\bthrow\b/.test(a)||/\bvalidat/i.test(a);for(let c of t.parameters){if(!c.optional){let l=t.parameters.map(d=>d.name===c.name?"undefined":this.generateTestValue(d)).join(", ");if(o)e.push({description:`should handle undefined ${c.name}`,type:"error-handling",action:t.isAsync?`const action = async () => await ${t.name}(${l});`:`const action = () => ${t.name}(${l});`,assertion:"expect(action).toThrow();"});else{let d=t.isAsync?`await ${t.name}(${l})`:`${t.name}(${l})`;e.push({description:`should handle undefined ${c.name}`,type:"edge-case",action:t.isAsync?`let threw = false;
118
118
  try {
119
119
  await ${t.name}(${l});
120
120
  } catch (e) {
@@ -137,15 +137,15 @@ Fix: Add '${t}' to domains.enabled in .agentic-qe/config.yaml, or run 'aqe init
137
137
  } catch (e) {
138
138
  expect(e).toBeInstanceOf(Error);
139
139
  }`;if(i.includes("string")){let s=t.parameters.map(o=>o.name===e.name?"''":this.generateTestValue(o)).join(", "),a=`${t.name}(${s})`;r.push({description:`should handle empty string for ${e.name}`,type:"boundary",action:n(a,t.isAsync),assertion:""})}if(i.includes("number")){let s=t.parameters.map(l=>l.name===e.name?"0":this.generateTestValue(l)).join(", "),a=`${t.name}(${s})`;r.push({description:`should handle zero for ${e.name}`,type:"boundary",action:n(a,t.isAsync),assertion:""});let o=t.parameters.map(l=>l.name===e.name?"-1":this.generateTestValue(l)).join(", "),c=`${t.name}(${o})`;r.push({description:`should handle negative value for ${e.name}`,type:"edge-case",action:n(c,t.isAsync),assertion:""})}if(i.includes("[]")||i.includes("array")){let s=t.parameters.map(o=>o.name===e.name?"[]":this.generateTestValue(o)).join(", "),a=t.isAsync?`await ${t.name}(${s})`:`${t.name}(${s})`;r.push({description:`should handle empty array for ${e.name}`,type:"boundary",action:`const result = ${a};`,assertion:"expect(result).toBeDefined();"})}return r}extractExports(t,e){let r=[];for(let i of t)i.isExported&&r.push(i.name);for(let i of e)i.isExported&&r.push(i.name);return r}generateImportStatement(t,e,r){return t.length>0?`import { ${t.join(", ")} } from '${e}';`:`import * as ${r} from '${e}';`}generatePatternComment(t){return t.length===0?"":`// Applied patterns: ${t.map(e=>e.name).join(", ")}
140
- `}camelCase(t){return t.replace(/[^a-zA-Z0-9]+(.)/g,(e,r)=>r.toUpperCase()).replace(/^./,e=>e.toLowerCase())}pascalCase(t){return t.replace(/[^a-zA-Z0-9]+(.)/g,(e,r)=>r.toUpperCase()).replace(/^./,e=>e.toUpperCase())}formatLineRange(t){return t.length===1?`line ${t[0]}`:`lines ${t[0]}-${t[t.length-1]}`}};var er=class extends J{framework;constructor(t="vitest"){super(),this.framework=t}get mockUtil(){return this.framework==="vitest"?"vi":"jest"}generateTests(t){let{moduleName:e,importPath:r,testType:i,patterns:n,analysis:s,dependencies:a}=t;if(!s||s.functions.length===0&&s.classes.length===0)return this.generateStubTests(t);let o=this.generatePatternComment(n),c=this.extractExports(s.functions,s.classes),l=this.generateImportStatement(c,r,e),d=this.framework==="vitest"?", vi":"",m=`${o}import { describe, it, expect, beforeEach${d} } from '${this.framework}';
140
+ `}camelCase(t){return t.replace(/[^a-zA-Z0-9]+(.)/g,(e,r)=>r.toUpperCase()).replace(/^./,e=>e.toLowerCase())}pascalCase(t){return t.replace(/[^a-zA-Z0-9]+(.)/g,(e,r)=>r.toUpperCase()).replace(/^./,e=>e.toUpperCase())}formatLineRange(t){return t.length===1?`line ${t[0]}`:`lines ${t[0]}-${t[t.length-1]}`}};var er=class extends J{framework;constructor(t="vitest"){super(),this.framework=t}get mockUtil(){return this.framework==="vitest"?"vi":"jest"}generateTests(t){let{moduleName:e,importPath:r,testType:i,patterns:n,analysis:s,dependencies:a}=t;if(!s||s.functions.length===0&&s.classes.length===0)return this.generateStubTests(t);let o=this.generatePatternComment(n),c=this.extractExports(s.functions,s.classes),l=this.generateImportStatement(c,r,e),d=this.framework==="vitest"?", vi":", jest",m=this.framework==="vitest"?"vitest":"@jest/globals",g=`${o}import { describe, it, expect, beforeEach${d} } from '${m}';
141
141
  ${l}
142
- `;if(a&&a.imports.length>0){let b=this.framework==="vitest"?"vi.fn()":"jest.fn()",w=a.imports.filter(C=>!C.startsWith("."));if(w.length>0){m+=`
142
+ `;if(a&&a.imports.length>0){let w=this.framework==="vitest"?"vi.fn()":"jest.fn()",C=a.imports.filter(S=>!S.startsWith("."));if(C.length>0){g+=`
143
143
  // Auto-generated mocks from Knowledge Graph dependency analysis
144
- `;for(let C of w.slice(0,10))m+=`${this.framework==="vitest"?"vi":"jest"}.mock('${C}', () => ({ default: ${b} }));
145
- `;m+=`
146
- `}else m+=`
147
- `}else m+=`
148
- `;let g=s.functions.filter(b=>b.isExported),h=s.classes.filter(b=>b.isExported);for(let b of g)m+=this.generateFunctionTests(b,i);for(let b of h)m+=this.generateClassTests(b,i);return m}generateFunctionTests(t,e){let r=this.generateTestCasesForFunction(t),i=`describe('${t.name}', () => {
144
+ `;for(let S of C.slice(0,10))g+=`${this.framework==="vitest"?"vi":"jest"}.mock('${S}', () => ({ default: ${w} }));
145
+ `;g+=`
146
+ `}else g+=`
147
+ `}else g+=`
148
+ `;let h=s.functions.filter(w=>w.isExported),b=s.classes.filter(w=>w.isExported);for(let w of h)g+=this.generateFunctionTests(w,i);for(let w of b)g+=this.generateClassTests(w,i);return g}generateFunctionTests(t,e){let r=this.generateTestCasesForFunction(t),i=`describe('${t.name}', () => {
149
149
  `;for(let n of r){n.setup&&(i+=` ${n.setup}
150
150
 
151
151
  `);let s=t.isAsync?"async ":"";i+=` it('${n.description}', ${s}() => {
@@ -193,11 +193,11 @@ ${l}
193
193
  `,i+=` });
194
194
  `)}return i+=` });
195
195
 
196
- `,i}generateStubTests(t){let{moduleName:e,importPath:r,testType:i,patterns:n,dependencies:s,similarCode:a}=t,o=this.generatePatternComment(n),c=this.generateBasicOpsTest(e,n),l=this.generateEdgeCaseTest(e,n),d=this.generateErrorHandlingTest(e,n),m="";if(s&&s.imports.length>0){let w=this.framework==="vitest"?"vi.fn()":"jest.fn()",C=s.imports.filter(S=>!S.startsWith("."));if(C.length>0){m+=`
196
+ `,i}generateStubTests(t){let{moduleName:e,importPath:r,testType:i,patterns:n,dependencies:s,similarCode:a}=t,o=this.generatePatternComment(n),c=this.generateBasicOpsTest(e,n),l=this.generateEdgeCaseTest(e,n),d=this.generateErrorHandlingTest(e,n),m="";if(s&&s.imports.length>0){let S=this.framework==="vitest"?"vi.fn()":"jest.fn()",k=s.imports.filter(P=>!P.startsWith("."));if(k.length>0){m+=`
197
197
  // Auto-generated mocks from Knowledge Graph dependency analysis
198
- `;for(let S of C.slice(0,10))m+=`${this.mockUtil}.mock('${S}', () => ({ default: ${w} }));
198
+ `;for(let P of k.slice(0,10))m+=`${this.mockUtil}.mock('${P}', () => ({ default: ${S} }));
199
199
  `}}let g="";if(a&&a.snippets.length>0){g+=` // KG: Similar modules found - consider testing shared patterns:
200
- `;for(let w of a.snippets.slice(0,3))g+=` // - ${w.file} (${(w.score*100).toFixed(0)}% similar)
200
+ `;for(let S of a.snippets.slice(0,3))g+=` // - ${S.file} (${(S.score*100).toFixed(0)}% similar)
201
201
  `;g+=`
202
202
  `}let h="";s&&s.imports.length>0&&(h+=`
203
203
  it('should interact with dependencies correctly', () => {
@@ -207,7 +207,7 @@ ${l}
207
207
  `,h+=` : ${e};
208
208
  `,h+=` expect(instance).toBeDefined();
209
209
  `,h+=` });
210
- `);let b="";return s&&s.importedBy.length>0&&(b+=`
210
+ `);let b="";s&&s.importedBy.length>0&&(b+=`
211
211
  it('should expose stable API for ${s.importedBy.length} consumers', () => {
212
212
  `,b+=` // KG-informed: used by ${s.importedBy.slice(0,3).join(", ")}
213
213
  `,b+=` const publicKeys = Object.keys(typeof ${e} === 'function'
@@ -215,7 +215,8 @@ ${l}
215
215
  `,b+=` : ${e});
216
216
  `,b+=` expect(publicKeys.length).toBeGreaterThan(0);
217
217
  `,b+=` });
218
- `),`${o}import { ${e} } from '${r}';
218
+ `);let w=this.framework==="vitest"?"vitest":"@jest/globals",C=this.framework==="vitest"?", vi":", jest";return`${o}import { describe, it, expect, beforeEach${C} } from '${w}';
219
+ import { ${e} } from '${r}';
219
220
  ${m}
220
221
  describe('${e}', () => {
221
222
  ${g} describe('${i} tests', () => {
@@ -359,7 +360,7 @@ describe('${t} coverage', () => {
359
360
 
360
361
  `,m+=` beforeEach(function() {
361
362
  `,m+=` stubs = {
362
- `;for(let S of C){let P=S.split("/").pop()?.replace(/[^a-zA-Z0-9_]/g,"_")||S;m+=` ${P}: sinon.stub(),
363
+ `;for(let S of C){let k=S.split("/").pop()?.replace(/[^a-zA-Z0-9_]/g,"_")||S;m+=` ${k}: sinon.stub(),
363
364
  `}m+=` };
364
365
  `,m+=` });
365
366
 
@@ -417,7 +418,7 @@ ${m}`,b=s.functions.filter(C=>C.isExported),w=s.classes.filter(C=>C.isExported);
417
418
 
418
419
  `,m+=` beforeEach(function() {
419
420
  `,m+=` stubs = {
420
- `;for(let P of S){let k=P.split("/").pop()?.replace(/[^a-zA-Z0-9_]/g,"_")||P;m+=` ${k}: sinon.stub(),
421
+ `;for(let k of S){let P=k.split("/").pop()?.replace(/[^a-zA-Z0-9_]/g,"_")||k;m+=` ${P}: sinon.stub(),
421
422
  `}m+=` };
422
423
  `,m+=` });
423
424
 
@@ -512,15 +513,15 @@ describe('${t} coverage', function() {
512
513
  });
513
514
  });
514
515
  });
515
- `}};var nt=class extends J{framework="pytest";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})),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==="__init__"||r.name==="constructor"),constructorParams:e.methods.find(r=>r.name==="__init__"||r.name==="constructor")?.parameters.map(r=>({name:r.name,type:r.type,optional:r.isOptional,defaultValue:r.defaultValue}))}))}}generateTests(t){let{moduleName:e,importPath:r,testType:i,patterns:n,analysis:s,dependencies:a}=t;if(!s||s.functions.length===0&&s.classes.length===0)return this.generateStubTests(t);let o=this.generatePythonPatternComment(n),c=this.extractExports(s.functions,s.classes),l=r.replace(/\//g,".").replace(/\.(ts|js)$/,""),d=c.length>0?`from ${l} import ${c.join(", ")}`:`import ${l} as ${e}`,m=a?.imports.filter(P=>!P.startsWith("."))||[],g="";m.length>0&&(g=`from unittest.mock import patch, MagicMock
516
- `);let b=m.slice(0,5).map(P=>`@patch('${P.replace(/\//g,".").replace(/\.py$/,"")}')`),w=`${o}import pytest
516
+ `}};var nt=class extends J{framework="pytest";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})),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==="__init__"||r.name==="constructor"),constructorParams:e.methods.find(r=>r.name==="__init__"||r.name==="constructor")?.parameters.map(r=>({name:r.name,type:r.type,optional:r.isOptional,defaultValue:r.defaultValue}))}))}}generateTests(t){let{moduleName:e,importPath:r,testType:i,patterns:n,analysis:s,dependencies:a}=t;if(!s||s.functions.length===0&&s.classes.length===0)return this.generateStubTests(t);let o=this.generatePythonPatternComment(n),c=this.extractExports(s.functions,s.classes),l=r.replace(/\//g,".").replace(/\.(ts|js)$/,""),d=c.length>0?`from ${l} import ${c.join(", ")}`:`import ${l} as ${e}`,m=a?.imports.filter(k=>!k.startsWith("."))||[],g="";m.length>0&&(g=`from unittest.mock import patch, MagicMock
517
+ `);let b=m.slice(0,5).map(k=>`@patch('${k.replace(/\//g,".").replace(/\.py$/,"")}')`),w=`${o}import pytest
517
518
  ${g}${d}
518
519
 
519
520
 
520
521
  class Test${this.pascalCase(e)}:
521
522
  """${i} tests for ${e}"""
522
523
 
523
- `,C=s.functions.filter(P=>P.isExported),S=s.classes.filter(P=>P.isExported);for(let P of C)w+=this.generateFunctionTestsWithPatches(P,i,b);for(let P of S)w+=this.generateClassTests(P,i);return w}generateFunctionTests(t,e){return this.generateFunctionTestsWithPatches(t,e,[])}generateFunctionTestsWithPatches(t,e,r){let i=t.parameters.map(d=>this.generatePythonTestValue(d)).join(", "),n=r.map((d,m)=>`mock_dep_${m}`).reverse().join(", "),s=n?`self, ${n}`:"self",a=r.map(d=>` ${d}
524
+ `,C=s.functions.filter(k=>k.isExported),S=s.classes.filter(k=>k.isExported);for(let k of C)w+=this.generateFunctionTestsWithPatches(k,i,b);for(let k of S)w+=this.generateClassTests(k,i);return w}generateFunctionTests(t,e){return this.generateFunctionTestsWithPatches(t,e,[])}generateFunctionTestsWithPatches(t,e,r){let i=t.parameters.map(d=>this.generatePythonTestValue(d)).join(", "),n=r.map((d,m)=>`mock_dep_${m}`).reverse().join(", "),s=n?`self, ${n}`:"self",a=r.map(d=>` ${d}
524
525
  `).join(""),o=t.returnType==="void"||t.returnType==="Promise<void>"||t.returnType==="None",c=`${a} def test_${t.name}_valid_input(${s}):
525
526
  `;c+=` """Test ${t.name} with valid input"""
526
527
  `;let l="assert result is not None";if(!o){if(/^(is|has|can)[A-Z]/.test(t.name))l="assert isinstance(result, bool)";else if(/^(create|build|make)[A-Z]/.test(t.name))l="assert result";else if(t.returnType){let d=t.returnType.toLowerCase().replace(/promise<(.+)>/,"$1");d.includes("{")?l="assert isinstance(result, dict)":d==="boolean"||d==="bool"?l="assert isinstance(result, bool)":d==="number"||d==="int"||d==="float"?l="assert isinstance(result, (int, float))":d==="string"||d==="str"?l="assert isinstance(result, str)":d.includes("[]")||d.includes("array")||d.includes("list")?l="assert isinstance(result, list)":d.includes("boolean")||d.includes("bool")?l="assert isinstance(result, bool)":d.includes("number")||d.includes("int")||d.includes("float")?l="assert isinstance(result, (int, float))":(d.includes("string")||d.includes("str"))&&(l="assert isinstance(result, str)")}}o?c+=` ${t.name}(${i}) # void function
@@ -552,15 +553,15 @@ class Test${t.name}:
552
553
 
553
554
  `)}return i}generateStubTests(t){let{moduleName:e,importPath:r,testType:i,patterns:n,dependencies:s,similarCode:a}=t,o=this.generatePythonPatternComment(n),c=n.some(S=>S.name.toLowerCase().includes("async")||S.name.toLowerCase().includes("promise")),l=c?`@pytest.mark.asyncio
554
555
  `:"",d=c?"async def":"def",m="",g="",h=s?.imports.filter(S=>!S.startsWith("."))||[];if(h.length>0){m=`from unittest.mock import patch, MagicMock
555
- `;for(let S of h.slice(0,5)){let P=S.replace(/\//g,".").replace(/\.py$/,"");g+=` @patch('${P}')
556
+ `;for(let S of h.slice(0,5)){let k=S.replace(/\//g,".").replace(/\.py$/,"");g+=` @patch('${k}')
556
557
  `}}let b="";if(a&&a.snippets.length>0){b=` # KG: Similar modules found - consider testing shared patterns:
557
558
  `;for(let S of a.snippets.slice(0,3))b+=` # - ${S.file} (${(S.score*100).toFixed(0)}% similar)
558
559
  `;b+=`
559
560
  `}let w="";if(s&&s.imports.length>0){w+=`
560
561
  def test_dependencies_importable(self):
561
562
  `,w+=` """Verify all dependencies are importable (KG-informed)."""
562
- `;for(let S of s.imports.slice(0,5)){let P=S.replace(/\//g,".").replace(/\.py$/,"");w+=` import importlib
563
- `,w+=` mod = importlib.import_module('${P}')
563
+ `;for(let S of s.imports.slice(0,5)){let k=S.replace(/\//g,".").replace(/\.py$/,"");w+=` import importlib
564
+ `,w+=` mod = importlib.import_module('${k}')
564
565
  `,w+=` assert mod is not None
565
566
  `}w+=`
566
567
  def test_dependency_interactions(self):
@@ -1721,8 +1722,8 @@ void main() {
1721
1722
  `),d&&(g+=`import { renderHook, act } from '@testing-library/react-hooks';
1722
1723
  `);let h=this.generateImportStatement(c,r,e);g+=`${h}
1723
1724
  `;let b=this.detectRequiredMocks(t);if(g+=`
1724
- `,g+=this.buildMockDeclarations(b),a&&a.imports.length>0){let S=a.imports.filter(O=>!O.startsWith(".")),P=["react-native","@react-navigation/native","@react-native-async-storage/async-storage","react-native-reanimated","react-native-gesture-handler"],k=S.filter(O=>!P.some(z=>O.includes(z)));if(k.length>0){g+=`// Auto-generated mocks from Knowledge Graph dependency analysis
1725
- `;for(let O of k.slice(0,10))g+=`jest.mock('${O}', () => ({ default: jest.fn() }));
1725
+ `,g+=this.buildMockDeclarations(b),a&&a.imports.length>0){let S=a.imports.filter(O=>!O.startsWith(".")),k=["react-native","@react-navigation/native","@react-native-async-storage/async-storage","react-native-reanimated","react-native-gesture-handler"],P=S.filter(O=>!k.some(z=>O.includes(z)));if(P.length>0){g+=`// Auto-generated mocks from Knowledge Graph dependency analysis
1726
+ `;for(let O of P.slice(0,10))g+=`jest.mock('${O}', () => ({ default: jest.fn() }));
1726
1727
  `;g+=`
1727
1728
  `}}let w=s.functions.filter(S=>S.isExported),C=s.classes.filter(S=>S.isExported);for(let S of w)g+=this.generateFunctionTests(S,i);for(let S of C)g+=this.generateClassTests(S,i);return g}generateFunctionTests(t,e){if(this.isHook(t))return this.generateHookTests(t);let r=this.generateTestCasesForFunction(t),i=`describe('${t.name}', () => {
1728
1729
  `;for(let n of r){n.setup&&(i+=` ${n.setup}
@@ -2051,7 +2052,7 @@ ${t}
2051
2052
  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:
2052
2053
  \`\`\`${this.getCodeFenceLanguage(r)}
2053
2054
  ${t}
2054
- \`\`\``}],model:i,maxTokens:1024,temperature:.5});if(n.content)try{let s=n.content.match(/\[[\s\S]*\]/);if(s)return E(s[0]).map(o=>o.name)}catch{}return[]}catch{return ja.warn("LLM suggestion generation failed:"),[]}}async generateTests(t){try{let e=Vl({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,coverageTarget:a=this.config.coverageTargetDefault,patterns:o=[]}=t;if(n.length===0)return p(new Error("No source files provided"));let c=[],l=[];for(let m of n){let g=await this.generateTestsForFile(m,s,r,o,i,t);g.success&&(c.push(...g.value.tests),l.push(...g.value.patternsUsed))}if(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true")for(let m of c)vp(m.id)&&(m.holdout=!0);let d=this.estimateCoverage(c,a);return await this.storeGenerationMetadata(c,l),f({tests:c,coverageEstimate:d,patternsUsed:Array.from(new Set(l))})}catch(e){return p(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 p(y(i))}}async generateTDDTests(t){try{let e=await this.tddGenerator.generateTDDTests(t);return f(e)}catch(e){return p(y(e))}}async generatePropertyTests(t){try{let e=await this.propertyTestGenerator.generatePropertyTests(t);return f(e)}catch(e){return p(y(e))}}async generateTestData(t){try{let e=await this.testDataGenerator.generateTestData(t);return f(e)}catch(e){return p(y(e))}}async generateTestsForFile(t,e,r,i,n,s){let a=this.getTestFilePath(t,r),o=[],c=await this.findApplicablePatterns(t,i);o.push(...c.map(k=>k.name));let l=null,d="";try{d=Gl.readFileSync(t,"utf-8"),l=await this.analyzeSourceCode(d,t)}catch{}let m,g;this.memory&&d&&await this.hasKGVectors()&&(m=await this.queryKGDependencies(t,d),g=await this.queryKGSimilarCode(d));let h=this.generatorFactory.create(r),b=this.extractModuleName(t),w=this.getImportPath(t),C={moduleName:b,importPath:w,testType:e,patterns:c,analysis:l??void 0,dependencies:m,similarCode:g},S=h.generateTests(C);this.isLLMEnhancementAvailable()&&d&&(S=await this.enhanceTestWithLLM(S,d,l,C));let P={id:v(),name:`${b} tests`,sourceFile:t,testFile:a,testCode:S,type:e,assertions:this.countAssertions(S),language:n,framework:r,llmEnhanced:this.isLLMEnhancementAvailable()};if(s?.compileValidation&&n)try{let k=await zl.validate(S,n,s.projectRoot);P.compilationValidated=k.compiles,k.compiles||(P.compilationErrors=k.errors.map(O=>O.message))}catch{}return this.qualityGate&&(P.qualityGateResult=this.qualityGate.validate(S,t,d||void 0)),f({tests:[P],patternsUsed:o})}async generateTestForLines(t,e,r){if(e.length===0)return null;let i=v(),n=this.getTestFilePath(t,r),s=this.extractModuleName(t),a=this.getImportPath(t),c=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:c,type:"unit",assertions:this.countAssertions(c)}}async analyzeSourceCode(t,e){let r=ri.extname(e),i=rt(r);if(i&&i!=="typescript"&&i!=="javascript"){let c=await Or.parseFile(t,e,i);if(c)return nt.convertParsedFile(c)}let n=x.createSourceFile(ri.basename(e),t,x.ScriptTarget.Latest,!0,x.ScriptKind.TS),s=[],a=[],o=c=>{if(x.isFunctionDeclaration(c)&&c.name)s.push(this.extractFunctionInfo(c,n));else if(x.isVariableStatement(c)){for(let l of c.declarationList.declarations)if(x.isVariableDeclaration(l)&&l.initializer&&(x.isArrowFunction(l.initializer)||x.isFunctionExpression(l.initializer))){let d=l.name.getText(n);s.push(this.extractArrowFunctionInfo(d,l.initializer,n,c))}}else x.isClassDeclaration(c)&&c.name&&a.push(this.extractClassInfo(c,n));x.forEachChild(c,o)};return x.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(l=>l.kind===x.SyntaxKind.AsyncKeyword)??!1,a=t.modifiers?.some(l=>l.kind===x.SyntaxKind.ExportKeyword)??!1,{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:c}=e.getLineAndCharacterOfPosition(t.getEnd());return{name:r,parameters:i,returnType:n,isAsync:s,isExported:a,complexity:this.calculateComplexity(t),startLine:o+1,endLine:c+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===x.SyntaxKind.AsyncKeyword)??!1,o=x.isVariableStatement(i)&&(i.modifiers?.some(d=>d.kind===x.SyntaxKind.ExportKeyword)??!1),{line:c}=r.getLineAndCharacterOfPosition(e.getStart(r)),{line:l}=r.getLineAndCharacterOfPosition(e.getEnd());return{name:t,parameters:n,returnType:s,isAsync:a,isExported:o,complexity:this.calculateComplexity(e),startLine:c+1,endLine:l+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(c=>c.kind===x.SyntaxKind.ExportKeyword)??!1;for(let c of t.members)if(x.isMethodDeclaration(c)){let l=c.name.getText(e),d=this.extractParameters(c.parameters,e),m=c.type?.getText(e),g=c.modifiers?.some(w=>w.kind===x.SyntaxKind.AsyncKeyword)??!1,{line:h}=e.getLineAndCharacterOfPosition(c.getStart(e)),{line:b}=e.getLineAndCharacterOfPosition(c.getEnd());i.push({name:l,parameters:d,returnType:m,isAsync:g,isExported:!1,complexity:this.calculateComplexity(c),startLine:h+1,endLine:b+1,body:c.body?.getText(e)})}else if(x.isConstructorDeclaration(c))s=!0,a=this.extractParameters(c.parameters,e);else if(x.isPropertyDeclaration(c)){let l=c.name.getText(e),d=c.type?.getText(e),m=c.modifiers?.some(h=>h.kind===x.SyntaxKind.PrivateKeyword)??!1,g=c.modifiers?.some(h=>h.kind===x.SyntaxKind.ReadonlyKeyword)??!1;n.push({name:l,type:d,isPrivate:m,isReadonly:g})}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 x.isObjectBindingPattern(n.name)?(r++,s=r>1?`options${r}`:"options",a||(a=`{ ${n.name.elements.map(c=>`${c.name.getText(e)}: unknown`).join(", ")} }`)):x.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 x.SyntaxKind.IfStatement:case x.SyntaxKind.ForStatement:case x.SyntaxKind.ForInStatement:case x.SyntaxKind.ForOfStatement:case x.SyntaxKind.WhileStatement:case x.SyntaxKind.DoStatement:case x.SyntaxKind.CaseClause:case x.SyntaxKind.CatchClause:case x.SyntaxKind.ConditionalExpression:e++;break;case x.SyntaxKind.BinaryExpression:{let n=i;(n.operatorToken.kind===x.SyntaxKind.AmpersandAmpersandToken||n.operatorToken.kind===x.SyntaxKind.BarBarToken)&&e++;break}}x.forEachChild(i,r)};return x.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 g of m){let h=g[1]||g[2];h&&/^[a-zA-Z_][\w.]*$/.test(h)&&r.push(h)}}let l=t.replace(/\\/g,"/").split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/,"")||"",d=await this.memory.search(`code-intelligence:kg:node:*${l}*`,50);for(let m of d){if(!m.includes(l))continue;let g=m.split(":"),h=g[g.length-2],b=g[g.length-1];h==="function"&&n.push(b)}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}=(Zt(),Jt(Il)),r=e?.[t];if(r){let i=ql(r);if(i)return i.codeFenceLanguage}}catch{}return"typescript"}convertParsedToCodeAnalysis(t){return nt.convertParsedFile(t)}async findApplicablePatterns(t,e){let r=[];try{let{getUnifiedMemory:i}=await import("./unified-memory-O7GFUSD3.js"),n=i().getDatabase();for(let o of e){let c=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2055
+ \`\`\``}],model:i,maxTokens:1024,temperature:.5});if(n.content)try{let s=n.content.match(/\[[\s\S]*\]/);if(s)return E(s[0]).map(o=>o.name)}catch{}return[]}catch{return ja.warn("LLM suggestion generation failed:"),[]}}async generateTests(t){try{let e=Vl({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,coverageTarget:a=this.config.coverageTargetDefault,patterns:o=[]}=t;if(n.length===0)return p(new Error("No source files provided"));let c=[],l=[];for(let m of n){let g=await this.generateTestsForFile(m,s,r,o,i,t);g.success&&(c.push(...g.value.tests),l.push(...g.value.patternsUsed))}if(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true")for(let m of c)vp(m.id)&&(m.holdout=!0);let d=this.estimateCoverage(c,a);return await this.storeGenerationMetadata(c,l),f({tests:c,coverageEstimate:d,patternsUsed:Array.from(new Set(l))})}catch(e){return p(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 p(y(i))}}async generateTDDTests(t){try{let e=await this.tddGenerator.generateTDDTests(t);return f(e)}catch(e){return p(y(e))}}async generatePropertyTests(t){try{let e=await this.propertyTestGenerator.generatePropertyTests(t);return f(e)}catch(e){return p(y(e))}}async generateTestData(t){try{let e=await this.testDataGenerator.generateTestData(t);return f(e)}catch(e){return p(y(e))}}async generateTestsForFile(t,e,r,i,n,s){let a=this.getTestFilePath(t,r),o=[],c=await this.findApplicablePatterns(t,i);o.push(...c.map(P=>P.name));let l=null,d="";try{d=Gl.readFileSync(t,"utf-8"),l=await this.analyzeSourceCode(d,t)}catch{}let m,g;this.memory&&d&&await this.hasKGVectors()&&(m=await this.queryKGDependencies(t,d),g=await this.queryKGSimilarCode(d));let h=this.generatorFactory.create(r),b=this.extractModuleName(t),w=s?.importPathOverrides?.[t]??this.getImportPath(t),C={moduleName:b,importPath:w,testType:e,patterns:c,analysis:l??void 0,dependencies:m,similarCode:g},S=h.generateTests(C);this.isLLMEnhancementAvailable()&&d&&(S=await this.enhanceTestWithLLM(S,d,l,C));let k={id:v(),name:`${b} tests`,sourceFile:t,testFile:a,testCode:S,type:e,assertions:this.countAssertions(S),language:n,framework:r,llmEnhanced:this.isLLMEnhancementAvailable()};if(s?.compileValidation&&n)try{let P=await zl.validate(S,n,s.projectRoot);k.compilationValidated=P.compiles,P.compiles||(k.compilationErrors=P.errors.map(O=>O.message))}catch{}return this.qualityGate&&(k.qualityGateResult=this.qualityGate.validate(S,t,d||void 0)),f({tests:[k],patternsUsed:o})}async generateTestForLines(t,e,r){if(e.length===0)return null;let i=v(),n=this.getTestFilePath(t,r),s=this.extractModuleName(t),a=this.getImportPath(t),c=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:c,type:"unit",assertions:this.countAssertions(c)}}async analyzeSourceCode(t,e){let r=ri.extname(e),i=rt(r);if(i&&i!=="typescript"&&i!=="javascript"){let c=await Or.parseFile(t,e,i);if(c)return nt.convertParsedFile(c)}let n=x.createSourceFile(ri.basename(e),t,x.ScriptTarget.Latest,!0,x.ScriptKind.TS),s=[],a=[],o=c=>{if(x.isFunctionDeclaration(c)&&c.name)s.push(this.extractFunctionInfo(c,n));else if(x.isVariableStatement(c)){for(let l of c.declarationList.declarations)if(x.isVariableDeclaration(l)&&l.initializer&&(x.isArrowFunction(l.initializer)||x.isFunctionExpression(l.initializer))){let d=l.name.getText(n);s.push(this.extractArrowFunctionInfo(d,l.initializer,n,c))}}else x.isClassDeclaration(c)&&c.name&&a.push(this.extractClassInfo(c,n));x.forEachChild(c,o)};return x.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(l=>l.kind===x.SyntaxKind.AsyncKeyword)??!1,a=t.modifiers?.some(l=>l.kind===x.SyntaxKind.ExportKeyword)??!1,{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:c}=e.getLineAndCharacterOfPosition(t.getEnd());return{name:r,parameters:i,returnType:n,isAsync:s,isExported:a,complexity:this.calculateComplexity(t),startLine:o+1,endLine:c+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===x.SyntaxKind.AsyncKeyword)??!1,o=x.isVariableStatement(i)&&(i.modifiers?.some(d=>d.kind===x.SyntaxKind.ExportKeyword)??!1),{line:c}=r.getLineAndCharacterOfPosition(e.getStart(r)),{line:l}=r.getLineAndCharacterOfPosition(e.getEnd());return{name:t,parameters:n,returnType:s,isAsync:a,isExported:o,complexity:this.calculateComplexity(e),startLine:c+1,endLine:l+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(c=>c.kind===x.SyntaxKind.ExportKeyword)??!1;for(let c of t.members)if(x.isMethodDeclaration(c)){let l=c.name.getText(e),d=this.extractParameters(c.parameters,e),m=c.type?.getText(e),g=c.modifiers?.some(w=>w.kind===x.SyntaxKind.AsyncKeyword)??!1,{line:h}=e.getLineAndCharacterOfPosition(c.getStart(e)),{line:b}=e.getLineAndCharacterOfPosition(c.getEnd());i.push({name:l,parameters:d,returnType:m,isAsync:g,isExported:!1,complexity:this.calculateComplexity(c),startLine:h+1,endLine:b+1,body:c.body?.getText(e)})}else if(x.isConstructorDeclaration(c))s=!0,a=this.extractParameters(c.parameters,e);else if(x.isPropertyDeclaration(c)){let l=c.name.getText(e),d=c.type?.getText(e),m=c.modifiers?.some(h=>h.kind===x.SyntaxKind.PrivateKeyword)??!1,g=c.modifiers?.some(h=>h.kind===x.SyntaxKind.ReadonlyKeyword)??!1;n.push({name:l,type:d,isPrivate:m,isReadonly:g})}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 x.isObjectBindingPattern(n.name)?(r++,s=r>1?`options${r}`:"options",a||(a=`{ ${n.name.elements.map(c=>`${c.name.getText(e)}: unknown`).join(", ")} }`)):x.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 x.SyntaxKind.IfStatement:case x.SyntaxKind.ForStatement:case x.SyntaxKind.ForInStatement:case x.SyntaxKind.ForOfStatement:case x.SyntaxKind.WhileStatement:case x.SyntaxKind.DoStatement:case x.SyntaxKind.CaseClause:case x.SyntaxKind.CatchClause:case x.SyntaxKind.ConditionalExpression:e++;break;case x.SyntaxKind.BinaryExpression:{let n=i;(n.operatorToken.kind===x.SyntaxKind.AmpersandAmpersandToken||n.operatorToken.kind===x.SyntaxKind.BarBarToken)&&e++;break}}x.forEachChild(i,r)};return x.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 g of m){let h=g[1]||g[2];h&&/^[a-zA-Z_][\w.]*$/.test(h)&&r.push(h)}}let l=t.replace(/\\/g,"/").split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/,"")||"",d=await this.memory.search(`code-intelligence:kg:node:*${l}*`,50);for(let m of d){if(!m.includes(l))continue;let g=m.split(":"),h=g[g.length-2],b=g[g.length-1];h==="function"&&n.push(b)}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}=(Zt(),Jt(Il)),r=e?.[t];if(r){let i=ql(r);if(i)return i.codeFenceLanguage}}catch{}return"typescript"}convertParsedToCodeAnalysis(t){return nt.convertParsedFile(t)}async findApplicablePatterns(t,e){let r=[];try{let{getUnifiedMemory:i}=await import("./unified-memory-2ETCY22B.js"),n=i().getDatabase();for(let o of e){let c=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2055
2056
  FROM qe_patterns WHERE id = ? OR name = ? LIMIT 1`).get(o,o);c&&r.push({id:c.id,name:c.name,structure:c.pattern_type,examples:c.usage_count,applicability:c.quality_score})}let s=t.split(".").pop()||"",a=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2056
2057
  FROM qe_patterns
2057
2058
  WHERE qe_domain = 'test-generation'
@@ -2141,7 +2142,7 @@ Individual assessments:`),t.forEach(s=>{let a=this.countsAsAgreement(s)?"\u2713
2141
2142
  created_at TEXT DEFAULT (datetime('now')),
2142
2143
  updated_at TEXT DEFAULT (datetime('now'))
2143
2144
  );
2144
- `,Ro={loadOnInit:!0,autoSaveInterval:0,maxPatternsToLoad:1e4,enableCrossProcessSharing:!0},In=class{baseEngine;config;persistence=null;db=null;prepared=new Map;initialized=!1;initPromise=null;pendingSaves=new Map;saveTimer=null;serverClient=null;constructor(t){this.config={...Ro,...t},this.baseEngine=new gl(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=Ji(),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-264QUQ3E.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}),kn.info("Three-loop engine restored Fisher state from SQLite",{domain:this.config.domain,requestCount:e.requestCount,taskBoundaries:e.taskBoundaries}))}kn.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: ${T(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(su)),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(au))}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(`
2145
+ `,Ro={loadOnInit:!0,autoSaveInterval:0,maxPatternsToLoad:1e4,enableCrossProcessSharing:!0},In=class{baseEngine;config;persistence=null;db=null;prepared=new Map;initialized=!1;initPromise=null;pendingSaves=new Map;saveTimer=null;serverClient=null;constructor(t){this.config={...Ro,...t},this.baseEngine=new gl(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=Ji(),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-6ALWBTHS.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}),kn.info("Three-loop engine restored Fisher state from SQLite",{domain:this.config.domain,requestCount:e.requestCount,taskBoundaries:e.taskBoundaries}))}kn.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: ${T(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(su)),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(au))}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(`
2145
2146
  SELECT * FROM sona_patterns
2146
2147
  WHERE domain = ?
2147
2148
  ORDER BY confidence DESC, updated_at DESC
@@ -2283,7 +2284,7 @@ stderr: ${e.slice(0,500)}`))}}parseVitestOutput(t,e,r,i){let n=t.match(/\{[\s\S]
2283
2284
  `+e,s=n.match(/Tests\s+(\d+)\s+passed(?:\s*\|\s*(\d+)\s+failed)?(?:\s*\|\s*(\d+)\s+skipped)?/i);if(s){let o=parseInt(s[1],10)||0,c=parseInt(s[2],10)||0,l=parseInt(s[3],10)||0;return f({total:o+c+l,passed:o,failed:c,skipped:l,failedTests:c>0?this.createGenericFailures(r,c,n):[],coverage:void 0})}let a=n.match(/Tests:\s+(?:(\d+)\s+failed,\s+)?(?:(\d+)\s+skipped,\s+)?(\d+)\s+passed,\s+(\d+)\s+total/i);if(a){let o=parseInt(a[1],10)||0,c=parseInt(a[2],10)||0,l=parseInt(a[3],10)||0;return f({total:l+o+c,passed:l,failed:o,skipped:c,failedTests:o>0?this.createGenericFailures(r,o,n):[],coverage:void 0})}if(i!==0){let o=["Cannot find module","SyntaxError","Error:","FAIL","failed"];for(let c of o)if(n.includes(c))return p(new Error(`Test execution failed for ${r} (exit code ${i}):
2284
2285
  ${n.slice(0,1e3)}`))}return i===0&&(n.includes("No test")||n.includes("0 tests"))?p(new Error(`No tests found in file: ${r}`)):p(new Error(`Unable to parse test results for ${r}. Exit code: ${i}
2285
2286
  Output: ${n.slice(0,500)}`))}createGenericFailures(t,e,r){let i=[],n=/FAIL\s+(.+?)(?:\n|$)|AssertionError[:\s]+(.+?)(?:\n|$)|Error[:\s]+(.+?)(?:\n|$)/gi,s=Array.from(r.matchAll(n));for(let a of s){if(i.length>=e)break;i.push({testId:v(),testName:a[1]||a[2]||a[3]||`Test #${i.length+1}`,file:t,error:a[0].trim(),stack:"",duration:0})}for(;i.length<e;)i.push({testId:v(),testName:`Failed test #${i.length+1}`,file:t,error:"Test failed (details not available)",stack:"",duration:0});return i}simulateTestExecution(t){let e=le(0,10)+1,r=L()>1-this.config.simulatedFailureRate?1:0,i=L()>1-this.config.simulatedSkipRate?1:0,n=[];r>0&&n.push({testId:v(),testName:`test in ${t}`,file:t,error:"Assertion failed",stack:`Error: Assertion failed
2286
- at ${t}:10:5`,duration:L()*1e3});let s={line:Math.round(L()*4e3+6e3)/100,branch:Math.round(L()*5e3+4e3)/100,function:Math.round(L()*3e3+7e3)/100,statement:Math.round(L()*4e3+6e3)/100};return{total:e,passed:e-r-i,failed:r,skipped:i,failedTests:n,coverage:s,fileCoverages:[{path:t,...s}]}}shardTests(t,e,r){let i=Array.from({length:e},()=>[]);switch(r){case"file":t.forEach((n,s)=>{i[s%e].push(n)});break;case"test":t.forEach((n,s)=>{i[s%e].push(n)});break;case"time-balanced":t.forEach((n,s)=>{i[s%e].push(n)});break}return i}async executeWorker(t,e,r,i){let n=await Promise.all(t.map(s=>this.executeTestFile(s,i.framework,i.timeout??3e4)));return this.aggregateResults(n)}aggregateResults(t){let e={total:0,passed:0,failed:0,skipped:0,failedTests:[],coverage:void 0};for(let i of t)e.total+=i.total,e.passed+=i.passed,e.failed+=i.failed,e.skipped+=i.skipped,e.failedTests.push(...i.failedTests);e.coverage=this.aggregateCoverage(t.map(i=>i.coverage).filter(i=>i!==void 0));let r=t.flatMap(i=>i.fileCoverages??[]);return r.length>0&&(e.fileCoverages=r),e}aggregateCoverage(t){if(t.length===0)return;let e=t.reduce((r,i)=>({line:r.line+i.line,branch:r.branch+i.branch,function:r.function+i.function,statement:r.statement+i.statement}),{line:0,branch:0,function:0,statement:0});return{line:Math.round(e.line/t.length*100)/100,branch:Math.round(e.branch/t.length*100)/100,function:Math.round(e.function/t.length*100)/100,statement:Math.round(e.statement/t.length*100)/100}}extractCoverageFromJson(t){let e=[];try{let r=t?.coverageSummary?.total??t?.coverageMap?.total;if(r?.lines?.pct!==void 0)return{summary:{line:typeof r.lines?.pct=="number"?r.lines.pct:0,branch:typeof r.branches?.pct=="number"?r.branches.pct:0,function:typeof r.functions?.pct=="number"?r.functions.pct:0,statement:typeof r.statements?.pct=="number"?r.statements.pct:0},perFile:e};let i=t?.coverageMap;if(i&&typeof i=="object"){let n=Object.keys(i).filter(s=>s!=="total");if(n.length>0){let s=0,a=0,o=0,c=0,l=0;for(let d of n){let m=i[d],g=m?.s??{},h=m?.f??{},b=m?.b??{},w=Object.keys(g).length,C=Object.values(g).filter(z=>z>0).length,S=Object.keys(h).length,P=Object.values(h).filter(z=>z>0).length,k=Object.keys(b).length,O=Object.values(b).filter(z=>Array.isArray(z)?z.every(K=>K>0):z>0).length;if(w>0){let z=Math.round(C/w*1e4)/100,K=S>0?Math.round(P/S*1e4)/100:100,Ce=k>0?Math.round(O/k*1e4)/100:100,Y=z;e.push({path:d,line:z,branch:Ce,function:K,statement:Y}),c+=Y,s+=z,o+=K,a+=Ce,l++}}if(l>0)return{summary:{line:Math.round(s/l*100)/100,branch:Math.round(a/l*100)/100,function:Math.round(o/l*100)/100,statement:Math.round(c/l*100)/100},perFile:e}}}}catch{}return{perFile:e}}readCoverageFromDisk(){try{let t=[pu(process.cwd(),"coverage","coverage-summary.json"),pu(process.cwd(),"coverage","coverage-final.json")];for(let e of t){if(!mu(e))continue;let r=jp(e,"utf-8"),i=E(r);if(i?.total?.lines?.pct!==void 0){let n=[];for(let[s,a]of Object.entries(i)){if(s==="total")continue;let o=s.replace(process.cwd()+"/","").replace(process.cwd()+"\\","");if(o.includes(".."))continue;let c=a;c?.lines?.pct!==void 0&&n.push({path:o,line:c.lines.pct,branch:c.branches?.pct??0,function:c.functions?.pct??0,statement:c.statements?.pct??0})}return{summary:{line:i.total.lines.pct,branch:i.total.branches?.pct??0,function:i.total.functions?.pct??0,statement:i.total.statements?.pct??0},perFile:n}}if(typeof i=="object"&&!i.total){let n=this.extractCoverageFromJson({coverageMap:i});if(n.summary)return{summary:n.summary,perFile:n.perFile}}}}catch{}}async storeResults(t,e){if(await this.memory.set(`test-run:${t}`,e,{namespace:"test-execution",persist:!0}),e.coverage)try{if(await this.memory.set("coverage:latest",{line:e.coverage.line??0,branch:e.coverage.branch??0,function:e.coverage.function??0,statement:e.coverage.statement??0,files:e.fileCoverages?.length??0},{persist:!0}),e.fileCoverages)for(let r of e.fileCoverages)await this.memory.set(`coverage:file:${r.path}`,{line:r.line,branch:r.branch,function:r.function,statement:r.statement},{persist:!0})}catch{}}};M();import{spawn as Kp}from"child_process";import*as xo from"path";import*as hu from"fs";A();H();se();var Jp={simulateForTesting:!1,simulatedFlakinessRate:ar.DEFAULT_FLAKY_RATE,simulatedFlakyPassRate:ar.DEFAULT_FLAKY_PASS_RATE,simulatedTestsPerFile:2,testRunner:"npx",testRunnerArgs:["vitest","run","--reporter=json"],runTimeout:je.DEFAULT_TEST_TIMEOUT_MS},gu=R.create("test-execution/flaky-detector"),zn=class{constructor(t,e={}){this.memory=t;this.config={...Jp,...e}}memory;testHistory=new Map;analysisCache=new Map;config;MAX_TESTS_TRACKED=je.MAX_TESTS_TRACKED;ANALYSIS_CACHE_TTL_MS=je.ANALYSIS_CACHE_TTL_MS;async detectFlaky(t){let e=Date.now();try{let{testFiles:r,runs:i,threshold:n}=t;if(i<2)return p(new Error("Minimum 2 runs required for flaky detection"));if(n<0||n>1)return p(new Error("Threshold must be between 0 and 1"));let s=[];for(let o of r){let c=await this.runMultipleTimes(o,i),l=this.identifyFlakyTests(c,n);s.push(...l)}let a={flakyTests:s,totalRuns:i*r.length,analysisTime:Date.now()-e};return await this.storeReport(a),f(a)}catch(r){return p(y(r))}}async analyzePattern(t){try{let e=this.analysisCache.get(t);if(e)return f(e);let r=await this.getTestHistory(t);if(r.length<5)return p(new Error("Insufficient history for pattern analysis (minimum 5 runs)"));let i=this.performPatternAnalysis(t,r),n={...i,analyzedAt:Date.now()};return this.analysisCache.set(t,n),await this.memory.set(`flaky-analysis:${t}`,n,{namespace:"test-execution",ttl:36e5}),f(i)}catch(e){return p(y(e))}}async suggestFix(t){try{let e=await this.analyzePattern(t);if(!e.success)return p(e.error);let r=e.value,i=this.generateRecommendations(r),n={testId:t,pattern:r.pattern,recommendations:i,priority:this.determinePriority(r)};return f(n)}catch(e){return p(y(e))}}async recordExecution(t,e){let r=this.testHistory.get(t)??[];r.push(e),r.length>100&&r.shift(),this.testHistory.set(t,r),await this.memory.set(`test-history:${t}`,r,{namespace:"test-execution",persist:!0}),this.analysisCache.delete(t)}async getFlakinessScore(t){let e=await this.getTestHistory(t);if(e.length<2)return 0;let r=0;for(let o=1;o<e.length;o++)e[o].passed!==e[o-1].passed&&r++;let i=r/(e.length-1),s=e.filter(o=>!o.passed).length/e.length,a=Math.min(s,1-s)*2;return Math.min(1,i*.6+a*.4)}cleanup(){let t=Date.now(),e=0;for(let[r,i]of this.analysisCache)t-(i.analyzedAt??0)>this.ANALYSIS_CACHE_TTL_MS&&(this.analysisCache.delete(r),e++);if(this.testHistory.size>this.MAX_TESTS_TRACKED){let r=this.testHistory.size-this.MAX_TESTS_TRACKED,i=Array.from(this.testHistory.keys()).slice(0,r);for(let n of i)this.testHistory.delete(n),this.analysisCache.delete(n),e++}return e}destroy(){this.testHistory.clear(),this.analysisCache.clear()}async runMultipleTimes(t,e){if(this.config.simulateForTesting)return this.simulateMultipleRuns(e);let r=this.config.cwd?xo.resolve(this.config.cwd,t):xo.resolve(t);if(!hu.existsSync(r))throw new Error(`Test file not found: ${r}. Cannot perform flaky detection without a valid test file.`);let i=new Map;for(let n=0;n<e;n++){let s=await this.executeTestFile(t,n);for(let[a,o]of s.entries()){let c=i.get(a)??[];c.push(...o),i.set(a,c)}}if(i.size===0)throw new Error(`Test execution produced no results for ${t}. Ensure the test runner (${this.config.testRunner}) is properly configured and the test file contains valid tests.`);for(let[n,s]of i.entries())for(let a of s)await this.recordExecution(n,a);return i}async executeTestFile(t,e){let r=new Map,i=v(),n=Date.now();return new Promise((s,a)=>{let o=[...this.config.testRunnerArgs,t],c=this.config.cwd??process.cwd(),l=Kp(this.config.testRunner,o,{cwd:c,env:{...process.env,...this.config.env},stdio:["ignore","pipe","pipe"]}),d="",m="";l.stdout?.on("data",h=>{d+=h.toString()}),l.stderr?.on("data",h=>{m+=h.toString()});let g=setTimeout(()=>{l.kill("SIGTERM"),a(new Error(`Test execution timed out after ${this.config.runTimeout}ms for ${t}`))},this.config.runTimeout);l.on("error",h=>{clearTimeout(g),a(new Error(`Failed to execute test runner: ${h.message}. Ensure ${this.config.testRunner} is installed and accessible.`))}),l.on("close",h=>{clearTimeout(g);let b=Date.now()-n;try{let w=this.parseTestOutput(d,m,h??0,t,i,e,b);if(w.size===0){let C=this.generateTestId(t,"main");r.set(C,[{runId:i,passed:h===0,duration:b,error:h!==0?m||`Exit code: ${h}`:void 0,timestamp:new Date,context:{parallelRuns:1,workerIndex:e}}])}else for(let[C,S]of w.entries())r.set(C,S);s(r)}catch(w){let C=this.generateTestId(t,"main");r.set(C,[{runId:i,passed:h===0,duration:b,error:h!==0?m||`Exit code: ${h}, Parse error: ${w}`:void 0,timestamp:new Date,context:{parallelRuns:1,workerIndex:e}}]),s(r)}})})}parseTestOutput(t,e,r,i,n,s,a){let o=new Map;try{let l=this.extractJson(t);if(l){let d=E(l);return this.parseVitestJson(d,i,n,s)}}catch{gu.debug("Vitest JSON parse failed:")}try{let l=this.extractJson(t);if(l){let d=E(l);if(d.testResults)return this.parseJestJson(d,i,n,s)}}catch{gu.debug("Jest JSON parse failed:")}if(t.includes("TAP version")||t.match(/^(ok|not ok)\s+\d+/m))return this.parseTapOutput(t,i,n,s);let c=this.parseMochaOutput(t,e,r,i,n,s,a);return c.size>0?c:o}extractJson(t){let e=t.indexOf("{"),r=t.indexOf("["),i=e===-1?r:r===-1?e:Math.min(e,r);if(i===-1)return null;let n=0,s=!1,a=!1;for(let o=i;o<t.length;o++){let c=t[o];if(a){a=!1;continue}if(c==="\\"){a=!0;continue}if(c==='"'){s=!s;continue}if(!s&&((c==="{"||c==="[")&&n++,(c==="}"||c==="]")&&n--,n===0))return t.substring(i,o+1)}return null}parseVitestJson(t,e,r,i){let n=new Map;if(!t.testResults)return n;for(let s of t.testResults)for(let a of s.assertionResults||[]){let o=this.generateTestId(e,a.fullName||a.title),c={runId:r,passed:a.status==="passed",duration:a.duration||0,error:a.status==="failed"?a.failureMessages?.join(`
2287
+ at ${t}:10:5`,duration:L()*1e3});let s={line:Math.round(L()*4e3+6e3)/100,branch:Math.round(L()*5e3+4e3)/100,function:Math.round(L()*3e3+7e3)/100,statement:Math.round(L()*4e3+6e3)/100};return{total:e,passed:e-r-i,failed:r,skipped:i,failedTests:n,coverage:s,fileCoverages:[{path:t,...s}]}}shardTests(t,e,r){let i=Array.from({length:e},()=>[]);switch(r){case"file":t.forEach((n,s)=>{i[s%e].push(n)});break;case"test":t.forEach((n,s)=>{i[s%e].push(n)});break;case"time-balanced":t.forEach((n,s)=>{i[s%e].push(n)});break}return i}async executeWorker(t,e,r,i){let n=await Promise.all(t.map(s=>this.executeTestFile(s,i.framework,i.timeout??3e4)));return this.aggregateResults(n)}aggregateResults(t){let e={total:0,passed:0,failed:0,skipped:0,failedTests:[],coverage:void 0};for(let i of t)e.total+=i.total,e.passed+=i.passed,e.failed+=i.failed,e.skipped+=i.skipped,e.failedTests.push(...i.failedTests);e.coverage=this.aggregateCoverage(t.map(i=>i.coverage).filter(i=>i!==void 0));let r=t.flatMap(i=>i.fileCoverages??[]);return r.length>0&&(e.fileCoverages=r),e}aggregateCoverage(t){if(t.length===0)return;let e=t.reduce((r,i)=>({line:r.line+i.line,branch:r.branch+i.branch,function:r.function+i.function,statement:r.statement+i.statement}),{line:0,branch:0,function:0,statement:0});return{line:Math.round(e.line/t.length*100)/100,branch:Math.round(e.branch/t.length*100)/100,function:Math.round(e.function/t.length*100)/100,statement:Math.round(e.statement/t.length*100)/100}}extractCoverageFromJson(t){let e=[];try{let r=t?.coverageSummary?.total??t?.coverageMap?.total;if(r?.lines?.pct!==void 0)return{summary:{line:typeof r.lines?.pct=="number"?r.lines.pct:0,branch:typeof r.branches?.pct=="number"?r.branches.pct:0,function:typeof r.functions?.pct=="number"?r.functions.pct:0,statement:typeof r.statements?.pct=="number"?r.statements.pct:0},perFile:e};let i=t?.coverageMap;if(i&&typeof i=="object"){let n=Object.keys(i).filter(s=>s!=="total");if(n.length>0){let s=0,a=0,o=0,c=0,l=0;for(let d of n){let m=i[d],g=m?.s??{},h=m?.f??{},b=m?.b??{},w=Object.keys(g).length,C=Object.values(g).filter(z=>z>0).length,S=Object.keys(h).length,k=Object.values(h).filter(z=>z>0).length,P=Object.keys(b).length,O=Object.values(b).filter(z=>Array.isArray(z)?z.every(K=>K>0):z>0).length;if(w>0){let z=Math.round(C/w*1e4)/100,K=S>0?Math.round(k/S*1e4)/100:100,Ce=P>0?Math.round(O/P*1e4)/100:100,Y=z;e.push({path:d,line:z,branch:Ce,function:K,statement:Y}),c+=Y,s+=z,o+=K,a+=Ce,l++}}if(l>0)return{summary:{line:Math.round(s/l*100)/100,branch:Math.round(a/l*100)/100,function:Math.round(o/l*100)/100,statement:Math.round(c/l*100)/100},perFile:e}}}}catch{}return{perFile:e}}readCoverageFromDisk(){try{let t=[pu(process.cwd(),"coverage","coverage-summary.json"),pu(process.cwd(),"coverage","coverage-final.json")];for(let e of t){if(!mu(e))continue;let r=jp(e,"utf-8"),i=E(r);if(i?.total?.lines?.pct!==void 0){let n=[];for(let[s,a]of Object.entries(i)){if(s==="total")continue;let o=s.replace(process.cwd()+"/","").replace(process.cwd()+"\\","");if(o.includes(".."))continue;let c=a;c?.lines?.pct!==void 0&&n.push({path:o,line:c.lines.pct,branch:c.branches?.pct??0,function:c.functions?.pct??0,statement:c.statements?.pct??0})}return{summary:{line:i.total.lines.pct,branch:i.total.branches?.pct??0,function:i.total.functions?.pct??0,statement:i.total.statements?.pct??0},perFile:n}}if(typeof i=="object"&&!i.total){let n=this.extractCoverageFromJson({coverageMap:i});if(n.summary)return{summary:n.summary,perFile:n.perFile}}}}catch{}}async storeResults(t,e){if(await this.memory.set(`test-run:${t}`,e,{namespace:"test-execution",persist:!0}),e.coverage)try{if(await this.memory.set("coverage:latest",{line:e.coverage.line??0,branch:e.coverage.branch??0,function:e.coverage.function??0,statement:e.coverage.statement??0,files:e.fileCoverages?.length??0},{persist:!0}),e.fileCoverages)for(let r of e.fileCoverages)await this.memory.set(`coverage:file:${r.path}`,{line:r.line,branch:r.branch,function:r.function,statement:r.statement},{persist:!0})}catch{}}};M();import{spawn as Kp}from"child_process";import*as xo from"path";import*as hu from"fs";A();H();se();var Jp={simulateForTesting:!1,simulatedFlakinessRate:ar.DEFAULT_FLAKY_RATE,simulatedFlakyPassRate:ar.DEFAULT_FLAKY_PASS_RATE,simulatedTestsPerFile:2,testRunner:"npx",testRunnerArgs:["vitest","run","--reporter=json"],runTimeout:je.DEFAULT_TEST_TIMEOUT_MS},gu=R.create("test-execution/flaky-detector"),zn=class{constructor(t,e={}){this.memory=t;this.config={...Jp,...e}}memory;testHistory=new Map;analysisCache=new Map;config;MAX_TESTS_TRACKED=je.MAX_TESTS_TRACKED;ANALYSIS_CACHE_TTL_MS=je.ANALYSIS_CACHE_TTL_MS;async detectFlaky(t){let e=Date.now();try{let{testFiles:r,runs:i,threshold:n}=t;if(i<2)return p(new Error("Minimum 2 runs required for flaky detection"));if(n<0||n>1)return p(new Error("Threshold must be between 0 and 1"));let s=[];for(let o of r){let c=await this.runMultipleTimes(o,i),l=this.identifyFlakyTests(c,n);s.push(...l)}let a={flakyTests:s,totalRuns:i*r.length,analysisTime:Date.now()-e};return await this.storeReport(a),f(a)}catch(r){return p(y(r))}}async analyzePattern(t){try{let e=this.analysisCache.get(t);if(e)return f(e);let r=await this.getTestHistory(t);if(r.length<5)return p(new Error("Insufficient history for pattern analysis (minimum 5 runs)"));let i=this.performPatternAnalysis(t,r),n={...i,analyzedAt:Date.now()};return this.analysisCache.set(t,n),await this.memory.set(`flaky-analysis:${t}`,n,{namespace:"test-execution",ttl:36e5}),f(i)}catch(e){return p(y(e))}}async suggestFix(t){try{let e=await this.analyzePattern(t);if(!e.success)return p(e.error);let r=e.value,i=this.generateRecommendations(r),n={testId:t,pattern:r.pattern,recommendations:i,priority:this.determinePriority(r)};return f(n)}catch(e){return p(y(e))}}async recordExecution(t,e){let r=this.testHistory.get(t)??[];r.push(e),r.length>100&&r.shift(),this.testHistory.set(t,r),await this.memory.set(`test-history:${t}`,r,{namespace:"test-execution",persist:!0}),this.analysisCache.delete(t)}async getFlakinessScore(t){let e=await this.getTestHistory(t);if(e.length<2)return 0;let r=0;for(let o=1;o<e.length;o++)e[o].passed!==e[o-1].passed&&r++;let i=r/(e.length-1),s=e.filter(o=>!o.passed).length/e.length,a=Math.min(s,1-s)*2;return Math.min(1,i*.6+a*.4)}cleanup(){let t=Date.now(),e=0;for(let[r,i]of this.analysisCache)t-(i.analyzedAt??0)>this.ANALYSIS_CACHE_TTL_MS&&(this.analysisCache.delete(r),e++);if(this.testHistory.size>this.MAX_TESTS_TRACKED){let r=this.testHistory.size-this.MAX_TESTS_TRACKED,i=Array.from(this.testHistory.keys()).slice(0,r);for(let n of i)this.testHistory.delete(n),this.analysisCache.delete(n),e++}return e}destroy(){this.testHistory.clear(),this.analysisCache.clear()}async runMultipleTimes(t,e){if(this.config.simulateForTesting)return this.simulateMultipleRuns(e);let r=this.config.cwd?xo.resolve(this.config.cwd,t):xo.resolve(t);if(!hu.existsSync(r))throw new Error(`Test file not found: ${r}. Cannot perform flaky detection without a valid test file.`);let i=new Map;for(let n=0;n<e;n++){let s=await this.executeTestFile(t,n);for(let[a,o]of s.entries()){let c=i.get(a)??[];c.push(...o),i.set(a,c)}}if(i.size===0)throw new Error(`Test execution produced no results for ${t}. Ensure the test runner (${this.config.testRunner}) is properly configured and the test file contains valid tests.`);for(let[n,s]of i.entries())for(let a of s)await this.recordExecution(n,a);return i}async executeTestFile(t,e){let r=new Map,i=v(),n=Date.now();return new Promise((s,a)=>{let o=[...this.config.testRunnerArgs,t],c=this.config.cwd??process.cwd(),l=Kp(this.config.testRunner,o,{cwd:c,env:{...process.env,...this.config.env},stdio:["ignore","pipe","pipe"]}),d="",m="";l.stdout?.on("data",h=>{d+=h.toString()}),l.stderr?.on("data",h=>{m+=h.toString()});let g=setTimeout(()=>{l.kill("SIGTERM"),a(new Error(`Test execution timed out after ${this.config.runTimeout}ms for ${t}`))},this.config.runTimeout);l.on("error",h=>{clearTimeout(g),a(new Error(`Failed to execute test runner: ${h.message}. Ensure ${this.config.testRunner} is installed and accessible.`))}),l.on("close",h=>{clearTimeout(g);let b=Date.now()-n;try{let w=this.parseTestOutput(d,m,h??0,t,i,e,b);if(w.size===0){let C=this.generateTestId(t,"main");r.set(C,[{runId:i,passed:h===0,duration:b,error:h!==0?m||`Exit code: ${h}`:void 0,timestamp:new Date,context:{parallelRuns:1,workerIndex:e}}])}else for(let[C,S]of w.entries())r.set(C,S);s(r)}catch(w){let C=this.generateTestId(t,"main");r.set(C,[{runId:i,passed:h===0,duration:b,error:h!==0?m||`Exit code: ${h}, Parse error: ${w}`:void 0,timestamp:new Date,context:{parallelRuns:1,workerIndex:e}}]),s(r)}})})}parseTestOutput(t,e,r,i,n,s,a){let o=new Map;try{let l=this.extractJson(t);if(l){let d=E(l);return this.parseVitestJson(d,i,n,s)}}catch{gu.debug("Vitest JSON parse failed:")}try{let l=this.extractJson(t);if(l){let d=E(l);if(d.testResults)return this.parseJestJson(d,i,n,s)}}catch{gu.debug("Jest JSON parse failed:")}if(t.includes("TAP version")||t.match(/^(ok|not ok)\s+\d+/m))return this.parseTapOutput(t,i,n,s);let c=this.parseMochaOutput(t,e,r,i,n,s,a);return c.size>0?c:o}extractJson(t){let e=t.indexOf("{"),r=t.indexOf("["),i=e===-1?r:r===-1?e:Math.min(e,r);if(i===-1)return null;let n=0,s=!1,a=!1;for(let o=i;o<t.length;o++){let c=t[o];if(a){a=!1;continue}if(c==="\\"){a=!0;continue}if(c==='"'){s=!s;continue}if(!s&&((c==="{"||c==="[")&&n++,(c==="}"||c==="]")&&n--,n===0))return t.substring(i,o+1)}return null}parseVitestJson(t,e,r,i){let n=new Map;if(!t.testResults)return n;for(let s of t.testResults)for(let a of s.assertionResults||[]){let o=this.generateTestId(e,a.fullName||a.title),c={runId:r,passed:a.status==="passed",duration:a.duration||0,error:a.status==="failed"?a.failureMessages?.join(`
2287
2288
  `):void 0,timestamp:new Date,context:{parallelRuns:1,workerIndex:i}};n.set(o,[c])}return n}parseJestJson(t,e,r,i){let n=new Map;for(let s of t.testResults||[])for(let a of s.assertionResults||[]){let o=this.generateTestId(e,a.fullName||a.title),c={runId:r,passed:a.status==="passed",duration:a.duration||0,error:a.status==="failed"?a.failureMessages?.join(`
2288
2289
  `):void 0,timestamp:new Date,context:{parallelRuns:1,workerIndex:i}};n.set(o,[c])}return n}parseTapOutput(t,e,r,i){let n=new Map,s=t.split(`
2289
2290
  `);for(let a of s){let o=a.match(/^(ok|not ok)\s+(\d+)\s*-?\s*(.*)/);if(o){let[,c,,l]=o,d=this.generateTestId(e,l||`test-${o[2]}`),m={runId:r,passed:c==="ok",duration:0,error:c!=="ok"?`Test failed: ${l}`:void 0,timestamp:new Date,context:{parallelRuns:1,workerIndex:i}};n.set(d,[m])}}return n}parseMochaOutput(t,e,r,i,n,s,a){let o=new Map,c=t.match(/(\d+)\s+passing/),l=t.match(/(\d+)\s+failing/);if(c||l){let d=c?parseInt(c[1],10):0,m=l?parseInt(l[1],10):0;for(let g=0;g<d;g++){let h=this.generateTestId(i,`passing-${g+1}`);o.set(h,[{runId:n,passed:!0,duration:a/(d+m),timestamp:new Date,context:{parallelRuns:1,workerIndex:s}}])}for(let g=0;g<m;g++){let h=this.generateTestId(i,`failing-${g+1}`);o.set(h,[{runId:n,passed:!1,duration:a/(d+m),error:e||"Test failed",timestamp:new Date,context:{parallelRuns:1,workerIndex:s}}])}}return o}generateTestId(t,e){let r=t.replace(/[^a-zA-Z0-9]/g,"-"),i=e.replace(/[^a-zA-Z0-9]/g,"-");return`${r}::${i}`}async getHistoryForFile(t){let e=new Map;for(let[r,i]of this.testHistory.entries())r.includes(t.replace(/[^a-zA-Z0-9]/g,"-"))&&e.set(r,i);return e}simulateMultipleRuns(t){let e=new Map,r=this.config.simulatedTestsPerFile,i=Array.from({length:r},()=>`test-${v().slice(0,8)}`);for(let n of i){let s=[],a=L()<this.config.simulatedFlakinessRate;for(let o=0;o<t;o++){let c=a?L()<this.config.simulatedFlakyPassRate:!0;s.push({runId:v(),passed:c,duration:L()*1e3+100,error:c?void 0:"Assertion failed",timestamp:new Date,context:{parallelRuns:t}})}e.set(n,s)}return e}identifyFlakyTests(t,e){let r=[];for(let[i,n]of t){let a=n.filter(o=>!o.passed).length/n.length;if(a>0&&a<1&&a>=e){let o=this.detectPattern(n);r.push({testId:i,testName:i,file:"unknown",failureRate:a,pattern:o,recommendation:this.getQuickRecommendation(o)})}}return r}detectPattern(t){let e=t.filter(c=>!c.passed),r=t.filter(c=>c.passed);if(e.length>0&&r.length>0){let c=this.average(e.map(d=>d.duration)),l=this.average(r.map(d=>d.duration));if(Math.abs(c-l)/l>.5)return"timing"}let i=["timeout","promise","async","await","callback"];if(e.some(c=>c.error&&i.some(l=>c.error.toLowerCase().includes(l))))return"async";let s=["connection","database","network","port","file"];return e.some(c=>c.error&&s.some(l=>c.error.toLowerCase().includes(l)))?"resource":e.some(c=>c.context?.precedingTests&&c.context.precedingTests.length>0)?"ordering":"unknown"}getQuickRecommendation(t){switch(t){case"timing":return"Increase timeouts or use explicit waits instead of fixed delays";case"ordering":return"Ensure test isolation and independent setup/teardown";case"resource":return"Mock external dependencies or use connection pooling";case"async":return"Properly await async operations and handle promise rejections";case"unknown":return"Review test for potential race conditions or external dependencies"}}async getTestHistory(t){let e=this.testHistory.get(t);if(e&&e.length>0)return e;let r=await this.memory.get(`test-history:${t}`);return r?(this.testHistory.set(t,r),r):[]}performPatternAnalysis(t,e){let r=this.detectPattern(e),i=this.identifyFactors(e,r),n=this.calculateCorrelations(e),s=this.calculateConfidence(e,r);return{testId:t,pattern:r,confidence:s,factors:i,correlations:n}}identifyFactors(t,e){let r=[];switch(e){case"timing":r.push("Variable execution duration"),r.push("Possible race conditions"),this.hasDurationSpikes(t)&&r.push("Duration spikes before failures");break;case"async":r.push("Unhandled async operations"),r.push("Missing await statements");break;case"resource":r.push("External dependency instability"),r.push("Shared resource contention");break;case"ordering":r.push("Shared state between tests"),r.push("Incomplete cleanup");break;case"unknown":r.push("No clear pattern identified"),r.push("Manual investigation recommended");break}return r}calculateCorrelations(t){let e=[],r=this.correlateWithFailure(t,s=>s.duration);Math.abs(r)>.3&&e.push({factor:"duration",correlation:r,description:r>0?"Failures correlate with longer duration":"Failures correlate with shorter duration"});let i=this.correlateWithFailure(t,s=>new Date(s.timestamp).getHours());Math.abs(i)>.3&&e.push({factor:"time_of_day",correlation:i,description:"Failures correlate with specific times"});let n=this.correlateWithFailure(t,s=>s.context?.parallelRuns??1);return Math.abs(n)>.3&&e.push({factor:"parallelism",correlation:n,description:"Failures correlate with parallel execution"}),e}correlateWithFailure(t,e){if(t.length<2)return 0;let r=t.map(e),i=t.map(n=>n.passed?0:1);return this.pearsonCorrelation(r,i)}pearsonCorrelation(t,e){let r=t.length;if(r===0)return 0;let i=t.reduce((d,m)=>d+m,0),n=e.reduce((d,m)=>d+m,0),s=t.reduce((d,m,g)=>d+m*e[g],0),a=t.reduce((d,m)=>d+m*m,0),o=e.reduce((d,m)=>d+m*m,0),c=r*s-i*n,l=Math.sqrt((r*a-i*i)*(r*o-n*n));return l===0?0:c/l}calculateConfidence(t,e){let r=Math.min(1,t.length/20),i=.5;e!=="unknown"&&(i=.8);let n=t.filter(a=>!a.passed).length/t.length,s=Math.min(n,1-n)*2;return r*.4+i*.4+s*.2}generateRecommendations(t){let e=[];switch(t.pattern){case"timing":e.push({action:"Use explicit waits",description:"Replace fixed delays with condition-based waits",codeSnippet:"await waitFor(() => expect(element).toBeVisible());",effort:"low"}),e.push({action:"Increase timeout margins",description:"Add buffer time for slow environments",codeSnippet:"jest.setTimeout(10000);",effort:"low"});break;case"async":e.push({action:"Ensure proper async handling",description:"Await all promises and use async/await consistently",codeSnippet:`const result = await asyncOperation();
@@ -2411,7 +2412,7 @@ expect(result).toBeDefined();`,effort:"medium"}),e.push({action:"Add error bound
2411
2412
  });
2412
2413
  return JSON.stringify(results);
2413
2414
  })()
2414
- `,c=await a.evaluate(o);if(!c.success)throw c.error;let l=E(c.value),d=Bo(l);if(t.options?.failOnSeverity){let m={critical:0,high:1,medium:2,low:3,info:4},g=m[t.options.failOnSeverity],h=l.violations.filter(b=>m[b.impact]<=g);if(h.length>0)throw new Ue(`Accessibility violations found: ${h.length} at or above ${t.options.failOnSeverity}`,t.id,0,h.length)}return{accessibilityResult:d}}let n=await e.checkAccessibility({selector:t.target,wcagLevel:t.options?.wcagLevel??"AA",rules:t.options?.rules?{include:t.options.tags,exclude:t.options.context?.exclude}:void 0});if(!n.success)throw n.error;let s=n.value;if(t.options?.failOnSeverity){let a={critical:0,high:1,medium:2,low:3,info:4},o=a[t.options.failOnSeverity],c=s.violations.filter(l=>a[l.impact]<=o);if(c.length>0)throw new Ue(`Accessibility violations found: ${c.length} violations at or above ${t.options.failOnSeverity} severity`,t.id,0,c.length)}if(t.options?.maxViolations!==void 0&&s.violations.length>t.options.maxViolations)throw new Ue(`Too many accessibility violations: ${s.violations.length} (max: ${t.options.maxViolations})`,t.id,t.options.maxViolations,s.violations.length);return{accessibilityResult:s}}getCurrentPageUrl(t){for(let e=t.previousResults.length-1;e>=0;e--){let r=t.previousResults[e];if(r.data?.url&&typeof r.data.url=="string")return r.data.url}return t.baseUrl}resolveUrl(t,e){return t.startsWith("http://")||t.startsWith("https://")?t:new URL(t,e).toString()}delay(t){return new Promise(e=>setTimeout(e,t))}};function Wo(u,t,e){return new cs(u,t,e)}A();var ls=class{config;stepExecutors;log;constructor(t,e,r){this.config=t,this.stepExecutors=e,this.log=r}async executeStepWithRetry(t,e){let r=(t.retries??this.config.defaultRetries)+1,i=t.timeout??this.config.defaultStepTimeout,n,s=0;for(let o=1;o<=r;o++){let c=new Date;try{let l=await this.withTimeout(this.executeStepInternal(t,e),i,t.id),d=new Date,m=d.getTime()-c.getTime();return s+=m,{stepId:t.id,stepType:t.type,success:!0,durationMs:m,data:l.data,screenshot:l.screenshot,accessibilityResult:l.accessibilityResult,startedAt:c,completedAt:d,retryInfo:o>1?{attempts:o,totalDurationMs:s}:void 0}}catch(l){n=y(l),s+=Date.now()-c.getTime(),o<r&&(this.log(`Step "${t.id}" failed (attempt ${o}/${r}), retrying...`),await this.delay(this.config.retryDelay))}}let a=new Date;return{stepId:t.id,stepType:t.type,success:!1,durationMs:s,error:{message:n?.message??"Unknown error",code:n instanceof xe?n.code:"UNKNOWN",stack:n?.stack},startedAt:new Date(a.getTime()-s),completedAt:a,retryInfo:{attempts:r,totalDurationMs:s}}}async executeStepInternal(t,e){return t.condition&&!this.evaluateCondition(t.condition,e)?{data:{}}:this.stepExecutors.executeStep(t,e)}evaluateCondition(t,e){let r={...e.variables};return hl(t,r,!0)}async withTimeout(t,e,r){return new Promise((i,n)=>{let s=setTimeout(()=>{n(new Dt(r,e))},e);t.then(a=>{clearTimeout(s),i(a)}).catch(a=>{clearTimeout(s),n(a)})})}delay(t){return new Promise(e=>setTimeout(e,t))}};function jo(u,t,e){return new ls(u,t,e)}var us=class{createSkippedResult(t,e){return{testCaseId:t.id,testCaseName:t.name,success:!0,status:"skipped",stepResults:[],totalDurationMs:0,startedAt:e,completedAt:new Date}}createErrorResult(t,e,r,i=[]){return{testCaseId:t.id,testCaseName:t.name,success:!1,status:"error",stepResults:i,totalDurationMs:Date.now()-e.getTime(),startedAt:e,completedAt:new Date,errorSummary:{failedStep:i.length>0?i[i.length-1].stepId:"setup",errorMessage:r}}}createResult(t,e,r,i,n){let s=new Date,o=r.some(l=>!l.success&&t.steps.find(d=>d.id===l.stepId)?.required&&!t.steps.find(d=>d.id===l.stepId)?.continueOnFailure)?"failed":"passed",c=r.find(l=>!l.success);return{testCaseId:t.id,testCaseName:t.name,success:o==="passed",status:o,stepResults:r,totalDurationMs:s.getTime()-e.getTime(),screenshots:i.length>0?i:void 0,accessibilityResults:n.length>0?n:void 0,startedAt:e,completedAt:s,browserInfo:t.viewport?{browserType:"chromium",viewport:t.viewport,userAgent:t.browserContext?.userAgent??""}:void 0,errorSummary:c?{failedStep:c.stepId,errorMessage:c.error?.message??"Unknown error",errorCode:c.error?.code,screenshot:c.error?.failureScreenshot}:void 0}}hasFailure(t){return t.some(e=>!e.success)}calculateSummary(t){return{total:t.length,passed:t.filter(e=>e.status==="passed").length,failed:t.filter(e=>e.status==="failed"||e.status==="error").length,skipped:t.filter(e=>e.status==="skipped").length}}createSuiteResult(t,e,r,i){let n=new Date,s=this.calculateSummary(r);return{suiteId:t,suiteName:e,success:s.failed===0,testResults:r,summary:{...s,totalDurationMs:n.getTime()-i.getTime()},startedAt:i,completedAt:n}}};function Uo(){return new us}A();var _g=R.create("test-execution/e2e-coordinator"),ds=class{constructor(t,e={}){this.client=t;this.config={...Do,...e};let r=i=>this.log(i);this.orchestrator=qo(t,this.config,r),this.stepExecutors=Wo(this.config,this.orchestrator,r),this.retryHandler=jo(this.config,this.stepExecutors,r),this.resultCollector=Uo(),this.log(`E2E Runner initialized with ${this.orchestrator.isUsingAgentBrowser()?"agent-browser":"vibium"} client`)}client;config;orchestrator;stepExecutors;retryHandler;resultCollector;async runTestCase(t){let e=new Date,r=[],i=[],n=[];if(t.skip)return this.resultCollector.createSkippedResult(t,e);if(t.requiredEnvVars?.length){let s=t.requiredEnvVars.filter(a=>!process.env[a]);if(s.length>0)return this.resultCollector.createErrorResult(t,e,`Missing required environment variables: ${s.join(", ")}`)}try{let s=await this.orchestrator.ensureBrowserLaunched(t);if(s)return this.resultCollector.createErrorResult(t,e,s);let a={testCase:t,baseUrl:t.baseUrl,variables:t.testData??{},previousResults:r,useAgentBrowser:this.orchestrator.isUsingAgentBrowser()};if(this.orchestrator.isUsingAgentBrowser()&&(a.currentSnapshot=await this.orchestrator.refreshSnapshot()),t.hooks?.beforeAll){let o=await this.executeHooks(t.hooks.beforeAll,a,"beforeAll");if(r.push(...o),this.resultCollector.hasFailure(o)&&this.config.stopOnFirstFailure)return this.resultCollector.createResult(t,e,r,i,n)}for(let o of t.steps){if(t.hooks?.beforeEach){let l=await this.executeHooks(t.hooks.beforeEach,a,"beforeEach");r.push(...l)}o.delayBefore&&o.delayBefore>0&&await this.delay(o.delayBefore);let c=await this.retryHandler.executeStepWithRetry(o,a);if(r.push(c),c.screenshot&&i.push(c.screenshot),c.accessibilityResult&&n.push(c.accessibilityResult),o.delayAfter&&o.delayAfter>0&&await this.delay(o.delayAfter),t.hooks?.afterEach){let l=await this.executeHooks(t.hooks.afterEach,a,"afterEach");r.push(...l)}if(!c.success){if(t.hooks?.onFailure){let l=await this.executeHooks(t.hooks.onFailure,a,"onFailure");r.push(...l)}if(this.config.screenshotOnFailure&&!c.screenshot){let l=await this.orchestrator.captureFailureScreenshot(o.id);l&&(c.error={...c.error,failureScreenshot:l},i.push(l))}if(this.config.stopOnFirstFailure&&o.required&&!o.continueOnFailure)break}}if(t.hooks?.afterAll){let o=await this.executeHooks(t.hooks.afterAll,a,"afterAll");r.push(...o)}return this.resultCollector.createResult(t,e,r,i,n)}catch(s){let a=T(s);return this.resultCollector.createErrorResult(t,e,a,r)}}async runTestSuite(t,e=t.parallel?"parallel":"sequential"){let r=new Date,i=[],n=t.testCases.filter(a=>a.only),s=n.length>0?n:t.testCases;if(e==="parallel"){let a=await this.executeInParallel(s,t.maxWorkers);i.push(...a)}else for(let a of s){let o=await this.runTestCase(a);i.push(o)}return this.resultCollector.createSuiteResult(t.id,t.name,i,r)}async executeHooks(t,e,r){let i=[];for(let n of t){this.log(`Executing ${r} hook: ${n.id}`);let s=await this.retryHandler.executeStepWithRetry(n,e);if(i.push(s),!s.success&&n.required){this.log(`${r} hook "${n.id}" failed`);break}}return i}async executeInParallel(t,e){let r=e??this.config.maxParallelWorkers,i=[],n=[...t],s=async()=>{for(;n.length>0;){let o=n.shift();if(o){let c=await this.runTestCase(o);i.push(c)}}},a=[];for(let o=0;o<Math.min(r,t.length);o++)a.push(s());return await Promise.all(a),i}delay(t){return new Promise(e=>setTimeout(e,t))}log(t){this.config.verbose&&_g.info(`${t}`)}};function Qo(u,t){return new ds(u,t)}A();var Ko=class{calculator;constructor(t){this.calculator=t??new fl}optimize(t,e=1){if(t.length===0)return this.emptyResult();if(t.length===1)return this.singleTestResult(t[0]);let{graph:r,testIds:i,fileIds:n,edgeCount:s}=this.buildCoverageGraph(t),a=this.calculator.approxMinCut(r),o=r.getStats(),c=new Set(a.sourceSide),l=new Set,d=new Set;for(let k of i)c.has(k)?l.add(k):d.add(k);let m=this.buildFileCoverageMap(t),g=new Set(m.keys()),h=this.findUniquelyCriticalTests(t,m);for(let k of h)l.add(k),d.delete(k);let b=new Set(l),w=new Set(d);if(e<1){let k=Math.ceil(g.size*e);this.computeCoveredFiles(t,b).size<k&&this.promoteToCritical(t,b,w,k)}else this.ensureFullCoverage(t,b,w,m);let C=this.buildExecutionOrder(t,b,w),S=new Map(t.map(k=>[k.testId,k])),P=Array.from(w).reduce((k,O)=>k+(S.get(O)?.estimatedDurationMs??0),0);return{criticalTests:Array.from(b),skippableTests:Array.from(w),executionOrder:C,estimatedTimeSavingsMs:P,graphStats:{testCount:t.length,coverageEdges:s,mincutValue:a.value,connectedComponents:o.componentCount}}}buildCoverageGraph(t){let e=new yl,r=[],i=new Set,n=new Map;for(let a of t)for(let o of a.coveredFiles)n.set(o,(n.get(o)??0)+1);for(let a of t){let o={id:a.testId,type:"agent",weight:a.coveredFiles.length,createdAt:new Date,metadata:{nodeType:"test",testFile:a.testFile}};e.addVertex(o),r.push(a.testId)}for(let[a]of n){let o=`file:${a}`,c={id:o,type:"domain",weight:1,createdAt:new Date,metadata:{nodeType:"file",filePath:a}};e.addVertex(c),i.add(o)}let s=0;for(let a of t)for(let o of a.coveredFiles){let c=`file:${o}`,d=1/(n.get(o)??1),m={source:a.testId,target:c,weight:d,type:"coordination",bidirectional:!0};e.addEdge(m),s++}return{graph:e,testIds:r,fileIds:Array.from(i),edgeCount:s}}buildFileCoverageMap(t){let e=new Map;for(let r of t)for(let i of r.coveredFiles){let n=e.get(i);n||(n=new Set,e.set(i,n)),n.add(r.testId)}return e}findUniquelyCriticalTests(t,e){let r=new Set;for(let[,i]of e)if(i.size===1){let[n]=i;r.add(n)}return r}computeCoveredFiles(t,e){let r=new Set;for(let i of t)if(e.has(i.testId))for(let n of i.coveredFiles)r.add(n);return r}promoteToCritical(t,e,r,i){let n=this.computeCoveredFiles(t,e),s=new Map(t.map(o=>[o.testId,o])),a=Array.from(r);for(;n.size<i&&a.length>0;){let o=-1,c=0;for(let m=0;m<a.length;m++){let g=s.get(a[m]);if(!g)continue;let h=g.coveredFiles.filter(b=>!n.has(b)).length;h>c&&(c=h,o=m)}if(o===-1||c===0)break;let l=a[o];a.splice(o,1),e.add(l),r.delete(l);let d=s.get(l);if(d)for(let m of d.coveredFiles)n.add(m)}}ensureFullCoverage(t,e,r,i){let n=this.computeCoveredFiles(t,e);for(let[s,a]of i)if(!n.has(s)){for(let o of a)if(r.has(o)){e.add(o),r.delete(o);let c=t.find(l=>l.testId===o);if(c)for(let l of c.coveredFiles)n.add(l);break}}}buildExecutionOrder(t,e,r){let i=new Map(t.map(o=>[o.testId,o])),n=(o,c)=>{let l=i.get(o)?.coveredFiles.length??0;return(i.get(c)?.coveredFiles.length??0)-l},s=Array.from(e).sort(n),a=Array.from(r).sort(n);return[...s,...a]}emptyResult(){return{criticalTests:[],skippableTests:[],executionOrder:[],estimatedTimeSavingsMs:0,graphStats:{testCount:0,coverageEdges:0,mincutValue:0,connectedComponents:0}}}singleTestResult(t){return{criticalTests:[t.testId],skippableTests:[],executionOrder:[t.testId],estimatedTimeSavingsMs:0,graphStats:{testCount:1,coverageEdges:t.coveredFiles.length,mincutValue:0,connectedComponents:(t.coveredFiles.length>0,1)}}}};function Iu(u){return new Ko(u)}var zg={simulateForTesting:!1,enablePrioritization:!0,maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Pe=R.create("test-execution"),Jo=class extends Q{memory;executor;flakyDetector;retryHandler;prioritizer;e2eRunner;activeRuns=new Set;constructor(t,e,r={}){let i={...zg,...r};super(t,"test-execution",i,{verifyFindingTypes:["flaky-test-detection","test-failure-analysis","retry-strategy"],...i.consensusConfig}),this.memory=e,this.executor=new _n({memory:e},{simulateForTesting:i.simulateForTesting,...i.executorConfig}),this.flakyDetector=new zn(e,{simulateForTesting:i.simulateForTesting,...i.flakyDetectorConfig}),this.retryHandler=new qn(e,{simulateForTesting:i.simulateForTesting,...i.retryHandlerConfig}),this.prioritizer=new Xn(e,i.prioritizerConfig),i.vibiumClient&&(this.e2eRunner=Qo(i.vibiumClient,i.e2eRunnerConfig))}async onInitialize(){this.config.enablePrioritization&&await this.prioritizer.initialize(),this.subscribeToEvents()}async onDispose(){for(let t of this.activeRuns)await this.cancelRun(t);this.activeRuns.clear()}getActiveRuns(){return Array.from(this.activeRuns)}async cancelRun(t){return this.activeRuns.has(t)?(this.activeRuns.delete(t),await this.publishEvent("test-execution.TestRunCancelled",{runId:t}),f(void 0)):p(new Error(`Run not found or already completed: ${t}`))}async runTests(t){let{testsToRun:e}=await this.partitionHoldoutTests(t.testFiles);if(e.length===0)return f({runId:v(),status:"passed",total:0,passed:0,failed:0,skipped:0,duration:0,failedTests:[]});let r=this.detectFramework(e),i=t.workers??Math.min(4,Math.max(1,e.length)),n=t.timeout??6e4;if(t.parallel!==!1&&e.length>1){let a=await this.executeParallel({testFiles:e,framework:r,workers:i,timeout:n});if(t.retryCount&&t.retryCount>0&&a.success&&a.value.failed>0){let o=a.value.failedTests.map(c=>c.testId);await this.retry({runId:a.value.runId,failedTests:o,maxRetries:t.retryCount,backoff:"exponential"})}return a}let s=await this.execute({testFiles:e,framework:r,timeout:n});if(t.retryCount&&t.retryCount>0&&s.success&&s.value.failed>0){let a=s.value.failedTests.map(o=>o.testId);await this.retry({runId:s.value.runId,failedTests:a,maxRetries:t.retryCount,backoff:"exponential"})}return s}detectFramework(t){let e=t.some(i=>i.includes(".test.")||i.includes(".spec.")),r=t.some(i=>i.includes("_test.")||i.includes(".mocha."));return e?"vitest":r?"mocha":"vitest"}async execute(t){let e=v();this.activeRuns.add(e),this.infraRecoveryAttempts=0;try{let{testsToRun:r}=await this.partitionHoldoutTests(t.testFiles);if(r.length===0)return this.activeRuns.delete(e),f({runId:e,status:"passed",total:0,passed:0,failed:0,skipped:0,duration:0,failedTests:[]});t={...t,testFiles:r};let i=t.testFiles,n=null;if(this.config.enablePrioritization&&t.testFiles.length>1){let o=await this.prioritizeTests(t.testFiles,e,!1,1);o.success&&(i=o.value.orderedFiles,n=o.value.prioritizationInfo)}await this.publishEvent(Ee.TestRunStarted,{runId:e,testCount:i.length,parallel:!1,workers:1});let s={...t,testFiles:i},a=await this.executor.execute(s);if(this.activeRuns.delete(e),a.success){this.config.enablePrioritization&&n&&await this.recordExecutionResults(e,i,a.value,n),await this.publishEvent(Ee.TestRunCompleted,{runId:a.value.runId,passed:a.value.passed,failed:a.value.failed,skipped:a.value.skipped,duration:a.value.duration});for(let o of a.value.failedTests)await this.flakyDetector.recordExecution(o.testId,{runId:a.value.runId,passed:!1,duration:o.duration,error:o.error,timestamp:new Date});try{this.eventBus&&await this.eventBus.publish(D("AsymmetricLearningOutcome","test-execution",{runId:a.value.runId,totalPassed:a.value.passed,totalFailed:a.value.failed,failedTests:a.value.failedTests.map(o=>({testId:o.testId,error:o.error?.substring(0,200)}))},a.value.runId))}catch{}if(this.config.infraHealing&&a.value.failedTests.length>0){this.feedInfraHealingFromFailures(a.value.failedTests);let o=await this.attemptAutoRecoveryAndRerun(a.value.failedTests,t.framework,{timeout:t.timeout,env:t.env});if(o)return o}}return a}catch(r){return this.activeRuns.delete(e),p(y(r))}}async executeParallel(t){let e=v();this.activeRuns.add(e),this.infraRecoveryAttempts=0;try{let{testsToRun:r}=await this.partitionHoldoutTests(t.testFiles);if(r.length===0)return this.activeRuns.delete(e),f({runId:e,status:"passed",total:0,passed:0,failed:0,skipped:0,duration:0,failedTests:[]});if(t={...t,testFiles:r},this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&(Pe.warn("Topology degraded, reducing parallel workers"),t={...t,workers:Math.max(1,Math.floor(t.workers/2))}),this.minCutMixin.shouldPauseOperations())return this.activeRuns.delete(e),p(new Error("Parallel test execution paused: topology is in critical state"));let i=t.testFiles,n=null;if(this.config.enablePrioritization&&t.testFiles.length>1){let o=await this.prioritizeTests(t.testFiles,e,!0,t.workers);o.success&&(i=o.value.orderedFiles,n=o.value.prioritizationInfo)}await this.publishEvent(Ee.TestRunStarted,{runId:e,testCount:i.length,parallel:!0,workers:t.workers});let s={...t,testFiles:i},a=await this.executor.executeParallel(s);if(this.activeRuns.delete(e),a.success){this.config.enablePrioritization&&n&&await this.recordExecutionResults(e,i,a.value,n),await this.publishEvent(Ee.TestRunCompleted,{runId:a.value.runId,passed:a.value.passed,failed:a.value.failed,skipped:a.value.skipped,duration:a.value.duration});for(let o of a.value.failedTests){let c=await this.flakyDetector.getFlakinessScore(o.testId);c>.3&&await this.publishEvent(Ee.FlakyTestDetected,{testId:o.testId,testFile:o.file,failureRate:c,pattern:"unknown"})}try{this.eventBus&&await this.eventBus.publish(D("AsymmetricLearningOutcome","test-execution",{runId:a.value.runId,totalPassed:a.value.passed,totalFailed:a.value.failed,failedTests:a.value.failedTests.map(o=>({testId:o.testId,error:o.error?.substring(0,200)}))},a.value.runId))}catch{}if(this.config.infraHealing&&a.value.failedTests.length>0){this.feedInfraHealingFromFailures(a.value.failedTests);let o=await this.attemptAutoRecoveryAndRerun(a.value.failedTests,t.framework,{timeout:t.timeout,env:t.env});if(o)return o}}return a}catch(r){return this.activeRuns.delete(e),p(y(r))}}async detectFlaky(t){let e=await this.flakyDetector.detectFlaky(t);if(e.success){let r=[];for(let i of e.value.flakyTests){if(this.config.enableConsensus&&i.failureRate>.3&&!await this.verifyFlakyTestDetection({testId:i.testId,testFile:i.file,failureRate:i.failureRate,pattern:i.pattern},Math.min(.9,i.failureRate+.3))){Pe.info(`Flaky test '${i.testId}' not verified, skipping publication`);continue}r.push(i),await this.publishEvent(Ee.FlakyTestDetected,{testId:i.testId,testFile:i.file,failureRate:i.failureRate,pattern:i.pattern})}return f({...e.value,flakyTests:r})}return e}async retry(t){if(this.minCutMixin.shouldPauseOperations())return p(new Error("Retry operation paused: topology is in critical state"));let e=await this.executor.getResults(t.runId);if(!e.success)return p(new Error(`Original run not found: ${t.runId}`));let r=e.value.failedTests.filter(n=>t.failedTests.includes(n.testId));if(r.length===0)return f({originalFailed:0,retried:0,nowPassing:0,stillFailing:0,flakyDetected:[]});this.config.enableConsensus&&r.length>5&&(await this.verifyRetryStrategy({runId:t.runId,testCount:r.length,maxRetries:t.maxRetries,backoffType:t.backoff??"exponential"},.7+r.length/100)||(Pe.warn("Retry strategy not verified, proceeding with reduced retries"),t={...t,maxRetries:Math.max(1,Math.floor(t.maxRetries/2))})),await this.publishEvent(Ee.RetryTriggered,{runId:t.runId,testCount:r.length});let i=await this.retryHandler.executeWithRetry({runId:t.runId,failedTests:r,maxRetries:t.maxRetries,backoff:t.backoff??"exponential",onRetry:(n,s)=>{}});if(i.success)for(let n of i.value.flakyDetected){let s=r.find(a=>a.testId===n);await this.publishEvent(Ee.FlakyTestDetected,{testId:n,testFile:s?.file??"unknown",failureRate:.5,pattern:"unknown"})}return i}async getStats(t){return this.executor.getStats(t)}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestSuiteCreated",async t=>{let e=t.payload}),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",async t=>{let e=t.payload})}async publishEvent(t,e){let r=D(t,"test-execution",e);await this.eventBus.publish(r)}feedInfraHealingFromFailures(t){if(!this.config.infraHealing)return;let e=t.map(i=>i.error).join(`
2415
+ `,c=await a.evaluate(o);if(!c.success)throw c.error;let l=E(c.value),d=Bo(l);if(t.options?.failOnSeverity){let m={critical:0,high:1,medium:2,low:3,info:4},g=m[t.options.failOnSeverity],h=l.violations.filter(b=>m[b.impact]<=g);if(h.length>0)throw new Ue(`Accessibility violations found: ${h.length} at or above ${t.options.failOnSeverity}`,t.id,0,h.length)}return{accessibilityResult:d}}let n=await e.checkAccessibility({selector:t.target,wcagLevel:t.options?.wcagLevel??"AA",rules:t.options?.rules?{include:t.options.tags,exclude:t.options.context?.exclude}:void 0});if(!n.success)throw n.error;let s=n.value;if(t.options?.failOnSeverity){let a={critical:0,high:1,medium:2,low:3,info:4},o=a[t.options.failOnSeverity],c=s.violations.filter(l=>a[l.impact]<=o);if(c.length>0)throw new Ue(`Accessibility violations found: ${c.length} violations at or above ${t.options.failOnSeverity} severity`,t.id,0,c.length)}if(t.options?.maxViolations!==void 0&&s.violations.length>t.options.maxViolations)throw new Ue(`Too many accessibility violations: ${s.violations.length} (max: ${t.options.maxViolations})`,t.id,t.options.maxViolations,s.violations.length);return{accessibilityResult:s}}getCurrentPageUrl(t){for(let e=t.previousResults.length-1;e>=0;e--){let r=t.previousResults[e];if(r.data?.url&&typeof r.data.url=="string")return r.data.url}return t.baseUrl}resolveUrl(t,e){return t.startsWith("http://")||t.startsWith("https://")?t:new URL(t,e).toString()}delay(t){return new Promise(e=>setTimeout(e,t))}};function Wo(u,t,e){return new cs(u,t,e)}A();var ls=class{config;stepExecutors;log;constructor(t,e,r){this.config=t,this.stepExecutors=e,this.log=r}async executeStepWithRetry(t,e){let r=(t.retries??this.config.defaultRetries)+1,i=t.timeout??this.config.defaultStepTimeout,n,s=0;for(let o=1;o<=r;o++){let c=new Date;try{let l=await this.withTimeout(this.executeStepInternal(t,e),i,t.id),d=new Date,m=d.getTime()-c.getTime();return s+=m,{stepId:t.id,stepType:t.type,success:!0,durationMs:m,data:l.data,screenshot:l.screenshot,accessibilityResult:l.accessibilityResult,startedAt:c,completedAt:d,retryInfo:o>1?{attempts:o,totalDurationMs:s}:void 0}}catch(l){n=y(l),s+=Date.now()-c.getTime(),o<r&&(this.log(`Step "${t.id}" failed (attempt ${o}/${r}), retrying...`),await this.delay(this.config.retryDelay))}}let a=new Date;return{stepId:t.id,stepType:t.type,success:!1,durationMs:s,error:{message:n?.message??"Unknown error",code:n instanceof xe?n.code:"UNKNOWN",stack:n?.stack},startedAt:new Date(a.getTime()-s),completedAt:a,retryInfo:{attempts:r,totalDurationMs:s}}}async executeStepInternal(t,e){return t.condition&&!this.evaluateCondition(t.condition,e)?{data:{}}:this.stepExecutors.executeStep(t,e)}evaluateCondition(t,e){let r={...e.variables};return hl(t,r,!0)}async withTimeout(t,e,r){return new Promise((i,n)=>{let s=setTimeout(()=>{n(new Dt(r,e))},e);t.then(a=>{clearTimeout(s),i(a)}).catch(a=>{clearTimeout(s),n(a)})})}delay(t){return new Promise(e=>setTimeout(e,t))}};function jo(u,t,e){return new ls(u,t,e)}var us=class{createSkippedResult(t,e){return{testCaseId:t.id,testCaseName:t.name,success:!0,status:"skipped",stepResults:[],totalDurationMs:0,startedAt:e,completedAt:new Date}}createErrorResult(t,e,r,i=[]){return{testCaseId:t.id,testCaseName:t.name,success:!1,status:"error",stepResults:i,totalDurationMs:Date.now()-e.getTime(),startedAt:e,completedAt:new Date,errorSummary:{failedStep:i.length>0?i[i.length-1].stepId:"setup",errorMessage:r}}}createResult(t,e,r,i,n){let s=new Date,o=r.some(l=>!l.success&&t.steps.find(d=>d.id===l.stepId)?.required&&!t.steps.find(d=>d.id===l.stepId)?.continueOnFailure)?"failed":"passed",c=r.find(l=>!l.success);return{testCaseId:t.id,testCaseName:t.name,success:o==="passed",status:o,stepResults:r,totalDurationMs:s.getTime()-e.getTime(),screenshots:i.length>0?i:void 0,accessibilityResults:n.length>0?n:void 0,startedAt:e,completedAt:s,browserInfo:t.viewport?{browserType:"chromium",viewport:t.viewport,userAgent:t.browserContext?.userAgent??""}:void 0,errorSummary:c?{failedStep:c.stepId,errorMessage:c.error?.message??"Unknown error",errorCode:c.error?.code,screenshot:c.error?.failureScreenshot}:void 0}}hasFailure(t){return t.some(e=>!e.success)}calculateSummary(t){return{total:t.length,passed:t.filter(e=>e.status==="passed").length,failed:t.filter(e=>e.status==="failed"||e.status==="error").length,skipped:t.filter(e=>e.status==="skipped").length}}createSuiteResult(t,e,r,i){let n=new Date,s=this.calculateSummary(r);return{suiteId:t,suiteName:e,success:s.failed===0,testResults:r,summary:{...s,totalDurationMs:n.getTime()-i.getTime()},startedAt:i,completedAt:n}}};function Uo(){return new us}A();var _g=R.create("test-execution/e2e-coordinator"),ds=class{constructor(t,e={}){this.client=t;this.config={...Do,...e};let r=i=>this.log(i);this.orchestrator=qo(t,this.config,r),this.stepExecutors=Wo(this.config,this.orchestrator,r),this.retryHandler=jo(this.config,this.stepExecutors,r),this.resultCollector=Uo(),this.log(`E2E Runner initialized with ${this.orchestrator.isUsingAgentBrowser()?"agent-browser":"vibium"} client`)}client;config;orchestrator;stepExecutors;retryHandler;resultCollector;async runTestCase(t){let e=new Date,r=[],i=[],n=[];if(t.skip)return this.resultCollector.createSkippedResult(t,e);if(t.requiredEnvVars?.length){let s=t.requiredEnvVars.filter(a=>!process.env[a]);if(s.length>0)return this.resultCollector.createErrorResult(t,e,`Missing required environment variables: ${s.join(", ")}`)}try{let s=await this.orchestrator.ensureBrowserLaunched(t);if(s)return this.resultCollector.createErrorResult(t,e,s);let a={testCase:t,baseUrl:t.baseUrl,variables:t.testData??{},previousResults:r,useAgentBrowser:this.orchestrator.isUsingAgentBrowser()};if(this.orchestrator.isUsingAgentBrowser()&&(a.currentSnapshot=await this.orchestrator.refreshSnapshot()),t.hooks?.beforeAll){let o=await this.executeHooks(t.hooks.beforeAll,a,"beforeAll");if(r.push(...o),this.resultCollector.hasFailure(o)&&this.config.stopOnFirstFailure)return this.resultCollector.createResult(t,e,r,i,n)}for(let o of t.steps){if(t.hooks?.beforeEach){let l=await this.executeHooks(t.hooks.beforeEach,a,"beforeEach");r.push(...l)}o.delayBefore&&o.delayBefore>0&&await this.delay(o.delayBefore);let c=await this.retryHandler.executeStepWithRetry(o,a);if(r.push(c),c.screenshot&&i.push(c.screenshot),c.accessibilityResult&&n.push(c.accessibilityResult),o.delayAfter&&o.delayAfter>0&&await this.delay(o.delayAfter),t.hooks?.afterEach){let l=await this.executeHooks(t.hooks.afterEach,a,"afterEach");r.push(...l)}if(!c.success){if(t.hooks?.onFailure){let l=await this.executeHooks(t.hooks.onFailure,a,"onFailure");r.push(...l)}if(this.config.screenshotOnFailure&&!c.screenshot){let l=await this.orchestrator.captureFailureScreenshot(o.id);l&&(c.error={...c.error,failureScreenshot:l},i.push(l))}if(this.config.stopOnFirstFailure&&o.required&&!o.continueOnFailure)break}}if(t.hooks?.afterAll){let o=await this.executeHooks(t.hooks.afterAll,a,"afterAll");r.push(...o)}return this.resultCollector.createResult(t,e,r,i,n)}catch(s){let a=T(s);return this.resultCollector.createErrorResult(t,e,a,r)}}async runTestSuite(t,e=t.parallel?"parallel":"sequential"){let r=new Date,i=[],n=t.testCases.filter(a=>a.only),s=n.length>0?n:t.testCases;if(e==="parallel"){let a=await this.executeInParallel(s,t.maxWorkers);i.push(...a)}else for(let a of s){let o=await this.runTestCase(a);i.push(o)}return this.resultCollector.createSuiteResult(t.id,t.name,i,r)}async executeHooks(t,e,r){let i=[];for(let n of t){this.log(`Executing ${r} hook: ${n.id}`);let s=await this.retryHandler.executeStepWithRetry(n,e);if(i.push(s),!s.success&&n.required){this.log(`${r} hook "${n.id}" failed`);break}}return i}async executeInParallel(t,e){let r=e??this.config.maxParallelWorkers,i=[],n=[...t],s=async()=>{for(;n.length>0;){let o=n.shift();if(o){let c=await this.runTestCase(o);i.push(c)}}},a=[];for(let o=0;o<Math.min(r,t.length);o++)a.push(s());return await Promise.all(a),i}delay(t){return new Promise(e=>setTimeout(e,t))}log(t){this.config.verbose&&_g.info(`${t}`)}};function Qo(u,t){return new ds(u,t)}A();var Ko=class{calculator;constructor(t){this.calculator=t??new fl}optimize(t,e=1){if(t.length===0)return this.emptyResult();if(t.length===1)return this.singleTestResult(t[0]);let{graph:r,testIds:i,fileIds:n,edgeCount:s}=this.buildCoverageGraph(t),a=this.calculator.approxMinCut(r),o=r.getStats(),c=new Set(a.sourceSide),l=new Set,d=new Set;for(let P of i)c.has(P)?l.add(P):d.add(P);let m=this.buildFileCoverageMap(t),g=new Set(m.keys()),h=this.findUniquelyCriticalTests(t,m);for(let P of h)l.add(P),d.delete(P);let b=new Set(l),w=new Set(d);if(e<1){let P=Math.ceil(g.size*e);this.computeCoveredFiles(t,b).size<P&&this.promoteToCritical(t,b,w,P)}else this.ensureFullCoverage(t,b,w,m);let C=this.buildExecutionOrder(t,b,w),S=new Map(t.map(P=>[P.testId,P])),k=Array.from(w).reduce((P,O)=>P+(S.get(O)?.estimatedDurationMs??0),0);return{criticalTests:Array.from(b),skippableTests:Array.from(w),executionOrder:C,estimatedTimeSavingsMs:k,graphStats:{testCount:t.length,coverageEdges:s,mincutValue:a.value,connectedComponents:o.componentCount}}}buildCoverageGraph(t){let e=new yl,r=[],i=new Set,n=new Map;for(let a of t)for(let o of a.coveredFiles)n.set(o,(n.get(o)??0)+1);for(let a of t){let o={id:a.testId,type:"agent",weight:a.coveredFiles.length,createdAt:new Date,metadata:{nodeType:"test",testFile:a.testFile}};e.addVertex(o),r.push(a.testId)}for(let[a]of n){let o=`file:${a}`,c={id:o,type:"domain",weight:1,createdAt:new Date,metadata:{nodeType:"file",filePath:a}};e.addVertex(c),i.add(o)}let s=0;for(let a of t)for(let o of a.coveredFiles){let c=`file:${o}`,d=1/(n.get(o)??1),m={source:a.testId,target:c,weight:d,type:"coordination",bidirectional:!0};e.addEdge(m),s++}return{graph:e,testIds:r,fileIds:Array.from(i),edgeCount:s}}buildFileCoverageMap(t){let e=new Map;for(let r of t)for(let i of r.coveredFiles){let n=e.get(i);n||(n=new Set,e.set(i,n)),n.add(r.testId)}return e}findUniquelyCriticalTests(t,e){let r=new Set;for(let[,i]of e)if(i.size===1){let[n]=i;r.add(n)}return r}computeCoveredFiles(t,e){let r=new Set;for(let i of t)if(e.has(i.testId))for(let n of i.coveredFiles)r.add(n);return r}promoteToCritical(t,e,r,i){let n=this.computeCoveredFiles(t,e),s=new Map(t.map(o=>[o.testId,o])),a=Array.from(r);for(;n.size<i&&a.length>0;){let o=-1,c=0;for(let m=0;m<a.length;m++){let g=s.get(a[m]);if(!g)continue;let h=g.coveredFiles.filter(b=>!n.has(b)).length;h>c&&(c=h,o=m)}if(o===-1||c===0)break;let l=a[o];a.splice(o,1),e.add(l),r.delete(l);let d=s.get(l);if(d)for(let m of d.coveredFiles)n.add(m)}}ensureFullCoverage(t,e,r,i){let n=this.computeCoveredFiles(t,e);for(let[s,a]of i)if(!n.has(s)){for(let o of a)if(r.has(o)){e.add(o),r.delete(o);let c=t.find(l=>l.testId===o);if(c)for(let l of c.coveredFiles)n.add(l);break}}}buildExecutionOrder(t,e,r){let i=new Map(t.map(o=>[o.testId,o])),n=(o,c)=>{let l=i.get(o)?.coveredFiles.length??0;return(i.get(c)?.coveredFiles.length??0)-l},s=Array.from(e).sort(n),a=Array.from(r).sort(n);return[...s,...a]}emptyResult(){return{criticalTests:[],skippableTests:[],executionOrder:[],estimatedTimeSavingsMs:0,graphStats:{testCount:0,coverageEdges:0,mincutValue:0,connectedComponents:0}}}singleTestResult(t){return{criticalTests:[t.testId],skippableTests:[],executionOrder:[t.testId],estimatedTimeSavingsMs:0,graphStats:{testCount:1,coverageEdges:t.coveredFiles.length,mincutValue:0,connectedComponents:(t.coveredFiles.length>0,1)}}}};function Iu(u){return new Ko(u)}var zg={simulateForTesting:!1,enablePrioritization:!0,maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Pe=R.create("test-execution"),Jo=class extends Q{memory;executor;flakyDetector;retryHandler;prioritizer;e2eRunner;activeRuns=new Set;constructor(t,e,r={}){let i={...zg,...r};super(t,"test-execution",i,{verifyFindingTypes:["flaky-test-detection","test-failure-analysis","retry-strategy"],...i.consensusConfig}),this.memory=e,this.executor=new _n({memory:e},{simulateForTesting:i.simulateForTesting,...i.executorConfig}),this.flakyDetector=new zn(e,{simulateForTesting:i.simulateForTesting,...i.flakyDetectorConfig}),this.retryHandler=new qn(e,{simulateForTesting:i.simulateForTesting,...i.retryHandlerConfig}),this.prioritizer=new Xn(e,i.prioritizerConfig),i.vibiumClient&&(this.e2eRunner=Qo(i.vibiumClient,i.e2eRunnerConfig))}async onInitialize(){this.config.enablePrioritization&&await this.prioritizer.initialize(),this.subscribeToEvents()}async onDispose(){for(let t of this.activeRuns)await this.cancelRun(t);this.activeRuns.clear()}getActiveRuns(){return Array.from(this.activeRuns)}async cancelRun(t){return this.activeRuns.has(t)?(this.activeRuns.delete(t),await this.publishEvent("test-execution.TestRunCancelled",{runId:t}),f(void 0)):p(new Error(`Run not found or already completed: ${t}`))}async runTests(t){let{testsToRun:e}=await this.partitionHoldoutTests(t.testFiles);if(e.length===0)return f({runId:v(),status:"passed",total:0,passed:0,failed:0,skipped:0,duration:0,failedTests:[]});let r=this.detectFramework(e),i=t.workers??Math.min(4,Math.max(1,e.length)),n=t.timeout??6e4;if(t.parallel!==!1&&e.length>1){let a=await this.executeParallel({testFiles:e,framework:r,workers:i,timeout:n});if(t.retryCount&&t.retryCount>0&&a.success&&a.value.failed>0){let o=a.value.failedTests.map(c=>c.testId);await this.retry({runId:a.value.runId,failedTests:o,maxRetries:t.retryCount,backoff:"exponential"})}return a}let s=await this.execute({testFiles:e,framework:r,timeout:n});if(t.retryCount&&t.retryCount>0&&s.success&&s.value.failed>0){let a=s.value.failedTests.map(o=>o.testId);await this.retry({runId:s.value.runId,failedTests:a,maxRetries:t.retryCount,backoff:"exponential"})}return s}detectFramework(t){let e=t.some(i=>i.includes(".test.")||i.includes(".spec.")),r=t.some(i=>i.includes("_test.")||i.includes(".mocha."));return e?"vitest":r?"mocha":"vitest"}async execute(t){let e=v();this.activeRuns.add(e),this.infraRecoveryAttempts=0;try{let{testsToRun:r}=await this.partitionHoldoutTests(t.testFiles);if(r.length===0)return this.activeRuns.delete(e),f({runId:e,status:"passed",total:0,passed:0,failed:0,skipped:0,duration:0,failedTests:[]});t={...t,testFiles:r};let i=t.testFiles,n=null;if(this.config.enablePrioritization&&t.testFiles.length>1){let o=await this.prioritizeTests(t.testFiles,e,!1,1);o.success&&(i=o.value.orderedFiles,n=o.value.prioritizationInfo)}await this.publishEvent(Ee.TestRunStarted,{runId:e,testCount:i.length,parallel:!1,workers:1});let s={...t,testFiles:i},a=await this.executor.execute(s);if(this.activeRuns.delete(e),a.success){this.config.enablePrioritization&&n&&await this.recordExecutionResults(e,i,a.value,n),await this.publishEvent(Ee.TestRunCompleted,{runId:a.value.runId,passed:a.value.passed,failed:a.value.failed,skipped:a.value.skipped,duration:a.value.duration});for(let o of a.value.failedTests)await this.flakyDetector.recordExecution(o.testId,{runId:a.value.runId,passed:!1,duration:o.duration,error:o.error,timestamp:new Date});try{this.eventBus&&await this.eventBus.publish(D("AsymmetricLearningOutcome","test-execution",{runId:a.value.runId,totalPassed:a.value.passed,totalFailed:a.value.failed,failedTests:a.value.failedTests.map(o=>({testId:o.testId,error:o.error?.substring(0,200)}))},a.value.runId))}catch{}if(this.config.infraHealing&&a.value.failedTests.length>0){this.feedInfraHealingFromFailures(a.value.failedTests);let o=await this.attemptAutoRecoveryAndRerun(a.value.failedTests,t.framework,{timeout:t.timeout,env:t.env});if(o)return o}}return a}catch(r){return this.activeRuns.delete(e),p(y(r))}}async executeParallel(t){let e=v();this.activeRuns.add(e),this.infraRecoveryAttempts=0;try{let{testsToRun:r}=await this.partitionHoldoutTests(t.testFiles);if(r.length===0)return this.activeRuns.delete(e),f({runId:e,status:"passed",total:0,passed:0,failed:0,skipped:0,duration:0,failedTests:[]});if(t={...t,testFiles:r},this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&(Pe.warn("Topology degraded, reducing parallel workers"),t={...t,workers:Math.max(1,Math.floor(t.workers/2))}),this.minCutMixin.shouldPauseOperations())return this.activeRuns.delete(e),p(new Error("Parallel test execution paused: topology is in critical state"));let i=t.testFiles,n=null;if(this.config.enablePrioritization&&t.testFiles.length>1){let o=await this.prioritizeTests(t.testFiles,e,!0,t.workers);o.success&&(i=o.value.orderedFiles,n=o.value.prioritizationInfo)}await this.publishEvent(Ee.TestRunStarted,{runId:e,testCount:i.length,parallel:!0,workers:t.workers});let s={...t,testFiles:i},a=await this.executor.executeParallel(s);if(this.activeRuns.delete(e),a.success){this.config.enablePrioritization&&n&&await this.recordExecutionResults(e,i,a.value,n),await this.publishEvent(Ee.TestRunCompleted,{runId:a.value.runId,passed:a.value.passed,failed:a.value.failed,skipped:a.value.skipped,duration:a.value.duration});for(let o of a.value.failedTests){let c=await this.flakyDetector.getFlakinessScore(o.testId);c>.3&&await this.publishEvent(Ee.FlakyTestDetected,{testId:o.testId,testFile:o.file,failureRate:c,pattern:"unknown"})}try{this.eventBus&&await this.eventBus.publish(D("AsymmetricLearningOutcome","test-execution",{runId:a.value.runId,totalPassed:a.value.passed,totalFailed:a.value.failed,failedTests:a.value.failedTests.map(o=>({testId:o.testId,error:o.error?.substring(0,200)}))},a.value.runId))}catch{}if(this.config.infraHealing&&a.value.failedTests.length>0){this.feedInfraHealingFromFailures(a.value.failedTests);let o=await this.attemptAutoRecoveryAndRerun(a.value.failedTests,t.framework,{timeout:t.timeout,env:t.env});if(o)return o}}return a}catch(r){return this.activeRuns.delete(e),p(y(r))}}async detectFlaky(t){let e=await this.flakyDetector.detectFlaky(t);if(e.success){let r=[];for(let i of e.value.flakyTests){if(this.config.enableConsensus&&i.failureRate>.3&&!await this.verifyFlakyTestDetection({testId:i.testId,testFile:i.file,failureRate:i.failureRate,pattern:i.pattern},Math.min(.9,i.failureRate+.3))){Pe.info(`Flaky test '${i.testId}' not verified, skipping publication`);continue}r.push(i),await this.publishEvent(Ee.FlakyTestDetected,{testId:i.testId,testFile:i.file,failureRate:i.failureRate,pattern:i.pattern})}return f({...e.value,flakyTests:r})}return e}async retry(t){if(this.minCutMixin.shouldPauseOperations())return p(new Error("Retry operation paused: topology is in critical state"));let e=await this.executor.getResults(t.runId);if(!e.success)return p(new Error(`Original run not found: ${t.runId}`));let r=e.value.failedTests.filter(n=>t.failedTests.includes(n.testId));if(r.length===0)return f({originalFailed:0,retried:0,nowPassing:0,stillFailing:0,flakyDetected:[]});this.config.enableConsensus&&r.length>5&&(await this.verifyRetryStrategy({runId:t.runId,testCount:r.length,maxRetries:t.maxRetries,backoffType:t.backoff??"exponential"},.7+r.length/100)||(Pe.warn("Retry strategy not verified, proceeding with reduced retries"),t={...t,maxRetries:Math.max(1,Math.floor(t.maxRetries/2))})),await this.publishEvent(Ee.RetryTriggered,{runId:t.runId,testCount:r.length});let i=await this.retryHandler.executeWithRetry({runId:t.runId,failedTests:r,maxRetries:t.maxRetries,backoff:t.backoff??"exponential",onRetry:(n,s)=>{}});if(i.success)for(let n of i.value.flakyDetected){let s=r.find(a=>a.testId===n);await this.publishEvent(Ee.FlakyTestDetected,{testId:n,testFile:s?.file??"unknown",failureRate:.5,pattern:"unknown"})}return i}async getStats(t){return this.executor.getStats(t)}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestSuiteCreated",async t=>{let e=t.payload}),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",async t=>{let e=t.payload})}async publishEvent(t,e){let r=D(t,"test-execution",e);await this.eventBus.publish(r)}feedInfraHealingFromFailures(t){if(!this.config.infraHealing)return;let e=t.map(i=>i.error).join(`
2415
2416
  `);this.config.infraHealing.feedTestOutput(e);let r=this.config.infraHealing.getObserver().getFailingServices();if(r.size>0){let i=t.map(n=>n.testId);for(let n of r)this.config.infraHealing.recordAffectedTests(n,i)}}infraRecoveryAttempts=0;async attemptAutoRecoveryAndRerun(t,e,r){if(!this.config.infraHealing||!(this.config.infraAutoRecover??!0))return null;let n=this.config.infraMaxAutoRecoveryAttempts??1;if(this.infraRecoveryAttempts>=n||this.config.infraHealing.getObserver().getFailingServices().size===0)return null;this.infraRecoveryAttempts++;let o=(await this.config.infraHealing.runRecoveryCycle()).filter(l=>l.recovered);if(o.length===0)return null;let c=new Set;for(let l of o)for(let d of l.affectedTestIds){let m=t.find(g=>g.testId===d);m&&c.add(m.file)}return c.size===0?null:this.execute({testFiles:[...c],framework:e,timeout:r.timeout,env:r.env})}async prioritizeTests(t,e,r,i){try{let n=t.map(c=>({testId:this.generateTestId(c),filePath:c,testName:this.extractTestName(c),testType:"unit",priority:"p2",complexity:.5,domain:"test-execution",estimatedDuration:5e3,coverage:0,failureHistory:[],flakinessScore:0,executionCount:0})),s={runId:e,totalTests:t.length,availableTime:6e4,workers:i,mode:r?"parallel":"sequential",phase:"ci"},a=await this.prioritizer.prioritize(n,s);if(!a.success)return p(a.error);let o=a.value.tests.map(c=>c.filePath);return f({orderedFiles:o,prioritizationInfo:{method:a.value.method,averageConfidence:a.value.averageConfidence,learningStatus:a.value.learningStatus}})}catch(n){return p(y(n))}}async recordExecutionResults(t,e,r,i){for(let n=0;n<e.length;n++){let s=this.generateTestId(e[n]),a=i,o=r.failedTests.find(g=>g.file===e[n]),c=!o,l=o?.duration??r.duration/e.length,d=n<Math.ceil(e.length*.2)?"critical":n<Math.ceil(e.length*.5)?"high":n<Math.ceil(e.length*.8)?"standard":"low",m={runId:t,totalTests:e.length,availableTime:6e4,workers:1,mode:"sequential",phase:"ci"};await this.prioritizer.recordExecution(s,{passed:c,duration:l,priority:d,failedEarly:o!==void 0&&n<Math.ceil(e.length*.3),coverageImproved:!1,flakyDetected:!1},m)}}generateTestId(t){return`test-${t.replace(/[^a-zA-Z0-9]/g,"-")}`}extractTestName(t){let e=t.split("/");return e[e.length-1]||t}async partitionHoldoutTests(t,e){if(!(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true"))return{testsToRun:t,holdoutCount:0};try{let i=await this.memory.get("test-generation:holdout-test-files");if(!i||i.length===0)return{testsToRun:t,holdoutCount:0};let n=new Set(i),s=[],a=[];for(let c of t)n.has(c)?a.push(c):s.push(c);return e===!0||process.env.AQE_RUN_HOLDOUT_TESTS==="true"?(Pe.info(`Holdout run: executing ${a.length} holdout tests, skipping ${s.length} normal tests`),await this.memory.set(`test-execution:holdout-run:${Date.now()}`,{holdoutCount:a.length,holdoutFiles:a},{namespace:"test-execution",ttl:86400}),{testsToRun:a,holdoutCount:a.length}):(a.length>0&&(Pe.info(`Normal run: filtered out ${a.length} holdout test(s), running ${s.length} normal tests`),await this.memory.set(`test-execution:holdout-filtered:${Date.now()}`,{holdoutCount:a.length,holdoutFiles:a},{namespace:"test-execution",ttl:86400})),{testsToRun:s,holdoutCount:a.length})}catch(i){return Pe.warn("Holdout test partitioning failed (running all tests)",{error:i instanceof Error?i.message:String(i)}),{testsToRun:t,holdoutCount:0}}}async executeE2ETestCase(t){if(!this.e2eRunner)return p(new Error("E2E runner not available - Vibium client not configured"));try{await this.publishEvent("test-execution.E2ETestStarted",{testCaseId:t.id,testCaseName:t.name});let e=await this.e2eRunner.runTestCase(t);return await this.publishEvent("test-execution.E2ETestCompleted",{testCaseId:e.testCaseId,testCaseName:e.testCaseName,success:e.success,duration:e.totalDurationMs}),f(e)}catch(e){return p(y(e))}}async executeE2ETestSuite(t,e="sequential"){if(!this.e2eRunner)return p(new Error("E2E runner not available - Vibium client not configured"));try{await this.publishEvent("test-execution.E2ETestSuiteStarted",{suiteId:t.id,suiteName:t.name,testCount:t.testCases.length,strategy:e});let r=await this.e2eRunner.runTestSuite(t,e);return await this.publishEvent("test-execution.E2ETestSuiteCompleted",{suiteId:r.suiteId,suiteName:r.suiteName,success:r.success,passed:r.summary.passed,failed:r.summary.failed,total:r.summary.total,duration:r.summary.totalDurationMs}),f(r)}catch(r){return p(y(r))}}optimizeTestSuite(t,e){return Iu().optimize(t,e?.coverageThreshold)}async verifyFlakyTestDetection(t,e){let r=V({id:v(),type:"flaky-test-detection",confidence:e,description:`Verify flaky test classification: ${t.testId} (failure rate: ${(t.failureRate*100).toFixed(1)}%)`,payload:t,detectedBy:"test-execution-coordinator",severity:t.failureRate>.5?"high":"medium"});if(this.consensusMixin.requiresConsensus(r)){let i=await this.consensusMixin.verifyFinding(r);return i.success&&i.value.verdict==="verified"?(Pe.info(`Flaky test '${t.testId}' classification verified by consensus`),!0):(Pe.warn(`Flaky test '${t.testId}' classification NOT verified: ${i.success?i.value.verdict:i.error.message}`),!1)}return!0}async verifyRetryStrategy(t,e){let r=V({id:v(),type:"retry-strategy",confidence:e,description:`Verify retry strategy: ${t.testCount} tests with ${t.maxRetries} max retries (${t.backoffType})`,payload:t,detectedBy:"test-execution-coordinator",severity:t.testCount>10?"high":"medium"});if(this.consensusMixin.requiresConsensus(r)){let i=await this.consensusMixin.verifyFinding(r);return i.success&&i.value.verdict==="verified"?(Pe.info("Retry strategy verified by consensus"),!0):(Pe.warn(`Retry strategy NOT verified: ${i.success?i.value.verdict:i.error.message}`),!1)}return!0}async verifyTestFailureAnalysis(t,e){let r=V({id:v(),type:"test-failure-analysis",confidence:e,description:`Verify failure analysis for ${t.testId}: ${t.failureType} - ${t.rootCause}`,payload:t,detectedBy:"test-execution-coordinator",severity:"high"});if(this.consensusMixin.requiresConsensus(r)){let i=await this.consensusMixin.verifyFinding(r);return i.success&&i.value.verdict==="verified"?(Pe.info(`Failure analysis for '${t.testId}' verified by consensus`),!0):(Pe.warn(`Failure analysis NOT verified: ${i.success?i.value.verdict:i.error.message}`),!1)}return!0}};function Du(u,t,e){return new Jo(u,t,e)}var Bg=null;function Mu(){return Bg}var Yo=class extends W{coordinator=null;constructor(t,e){super(t,e)}get name(){return"test-execution"}get version(){return"1.0.0"}get dependencies(){return["test-generation"]}getAPI(){if(!this.coordinator)throw new Error("Plugin not initialized");return{runTests:this.coordinator.runTests.bind(this.coordinator),execute:this.coordinator.execute.bind(this.coordinator),executeParallel:this.coordinator.executeParallel.bind(this.coordinator),detectFlaky:this.coordinator.detectFlaky.bind(this.coordinator),retry:this.coordinator.retry.bind(this.coordinator),getStats:this.coordinator.getStats.bind(this.coordinator),executeE2ETestCase:this.coordinator.executeE2ETestCase?.bind(this.coordinator),executeE2ETestSuite:this.coordinator.executeE2ETestSuite?.bind(this.coordinator)}}getTaskHandlers(){return new Map([["execute-tests",async t=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));if(t.testFiles&&Array.isArray(t.testFiles)){let e={testFiles:t.testFiles,parallel:t.parallel,retryCount:t.retryCount,timeout:t.timeout,workers:t.workers};return this.coordinator.runTests(e)}else if(t.framework){let e={testFiles:t.testFiles||[],framework:t.framework,timeout:t.timeout,env:t.env,reporters:t.reporters};return this.coordinator.execute(e)}return p(new Error("Invalid execute-tests payload: missing testFiles or framework"))}],["detect-flaky",async t=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let e=t.testFiles,r=t.runs,i=t.threshold;return e?this.coordinator.detectFlaky({testFiles:e,runs:r??5,threshold:i??.1}):p(new Error("Invalid detect-flaky payload: missing testFiles"))}],["retry-tests",async t=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let e=t.runId,r=t.failedTests,i=t.maxRetries;return!e||!r?p(new Error("Invalid retry-tests payload: missing runId or failedTests")):this.coordinator.retry({runId:e,failedTests:r,maxRetries:i??3,backoff:t.backoff})}]])}async onInitialize(){let t=Mu()??void 0;this.coordinator=Du(this.eventBus,this.memory,{infraHealing:t}),await this.coordinator.initialize(),this.updateHealth({status:"idle",lastActivity:new Date})}async onDispose(){this.coordinator&&(await this.coordinator.dispose(),this.coordinator=null),this.updateHealth({status:"unhealthy"})}async onEvent(t){switch(t.type){case"test-generation.TestSuiteCreated":await this.handleTestSuiteCreated(t);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(t);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGapDetected(t);break}}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestSuiteCreated",t=>this.handleEvent(t)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",t=>this.handleEvent(t)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",t=>this.handleEvent(t))}async handleTestSuiteCreated(t){let e=t.payload;this.updateHealth({lastActivity:new Date}),await this.memory.set(`suite-event:${e.suiteId}`,{eventId:t.id,timestamp:t.timestamp,sourceFiles:e.sourceFiles},{namespace:"test-execution",ttl:864e5})}async handleQualityGateEvaluated(t){let e=t.payload;e.passed||await this.memory.set(`quality-context:${e.gateId}`,{requiresRetry:!0,failedChecks:e.checks.filter(r=>!r.passed).map(r=>r.name)},{namespace:"test-execution",ttl:36e5}),this.updateHealth({lastActivity:new Date})}async handleCoverageGapDetected(t){let e=t.payload;e.riskScore>.7&&await this.memory.set(`coverage-gap:${e.gapId}`,{file:e.file,uncoveredLines:e.uncoveredLines,priority:"high"},{namespace:"test-execution",persist:!0}),this.updateHealth({lastActivity:new Date})}};function Fu(u,t){return new Yo(u,t)}M();A();M();A();H();var qg={defaultThreshold:80,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},Lu=R.create("coverage-analysis/coverage-analyzer"),mt=class u{static DEFAULT_THRESHOLD=80;static VECTOR_DIMENSION=384;memory;config;llmRouter;constructor(t,e={}){this.config={...qg,...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)}async analyze(t){try{let{coverageData:e,threshold:r=this.config.defaultThreshold}=t,i=this.calculateMetrics(e),s=this.calculateOverallCoverage(i)>=r,a=await this.calculateDelta(i),o=this.generateRecommendations(e,i,r);return await this.storeCoverageSnapshot(i),t.includeFileDetails&&(await this.indexFileCoverageVectors(e.files),await this.storeFileCoverageKV(e.files)),f({summary:i,meetsThreshold:s,delta:a,recommendations:o})}catch(e){return p(y(e))}}async findGaps(t,e=this.config.defaultThreshold){try{let r=[],i=0;for(let s of t.files)if(this.calculateFileCoveragePercentage(s)<e){let o=this.calculateFileRiskScore(s),c=this.riskScoreToSeverity(o),l=await this.findSimilarGapPatterns(s);r.push({id:this.generateGapId(s.path),file:s.path,lines:s.uncoveredLines,branches:s.uncoveredBranches,riskScore:o,severity:c,recommendation:this.generateGapRecommendation(s,l)}),i+=s.uncoveredLines.length}r.sort((s,a)=>a.riskScore-s.riskScore);let n=this.estimateEffort(i);return f({gaps:r,totalUncoveredLines:i,estimatedEffort:n})}catch(r){return p(y(r))}}calculateMetrics(t){let e=t.files;if(e.length===0)return{line:0,branch:0,function:0,statement:0,files:0};let r=0,i=0,n=0,s=0,a=0,o=0,c=0,l=0;for(let d of e)r+=d.lines.total,i+=d.lines.covered,n+=d.branches.total,s+=d.branches.covered,a+=d.functions.total,o+=d.functions.covered,c+=d.statements.total,l+=d.statements.covered;return{line:r>0?i/r*100:0,branch:n>0?s/n*100:0,function:a>0?o/a*100:0,statement:c>0?l/c*100:0,files:e.length}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(t){switch(t){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async analyzeCoverageWithLLM(t,e){if(!this.llmRouter)return this.getDefaultInsights();try{let r=this.buildCoverageAnalysisPrompt(t,e),i=this.getModelForTier(this.config.llmModelTier??2),n=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert code coverage analyst and test engineer. Analyze coverage gaps and provide actionable insights.
2416
2417
 
2417
2418
  Your response MUST be valid JSON with this exact structure:
@@ -2606,14 +2607,14 @@ describe('${e} Integration', () => {
2606
2607
  });
2607
2608
  });
2608
2609
  });`}};A();var Hg=[{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}],lr=class u{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=Hg}=t,n=this.normalizeFactorWeights(i),s=await this.calculateFactorScores(e,r,n),a=s.reduce((l,d)=>l+d.score*d.contribution,0),o=this.riskScoreToSeverity(a),c=this.generateRiskRecommendations(e,a,o,s);return await this.storeRiskSnapshot(e,a,s),f({file:e,overallRisk:a,riskLevel:o,factors:s,recommendations:c})}catch(e){return p(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 l=a.value;l.trend==="increasing"?o=.15:l.trend==="decreasing"&&(o=-.1)}let c=e+i+s+o;return Math.min(1,Math.max(0,c))}catch{return e}}async getRiskTrend(t){try{let e=`${u.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(-u.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 p(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,c)=>c.score*c.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=`${u.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(-u.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 c=o,l=t[o].riskScore;r+=c,i+=l,n+=c*l,s+=c*c}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 Xo={dimensions:384,includePathFeatures:!0,includeTemporalFeatures:!0,normalization:"l2"},yi=class{config;constructor(t={}){this.config={...Xo,...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((l,d)=>l-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 c=this.countContiguousRegions(s);t[r++]=Math.min(1,c/10),t[r++]=c>0?i.length/c: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 vi(u){return new yi(u)}M();A();var RP=R.create("coverage-analysis/sublinear-analyzer");Ki();A();var bi=["missing-error-handler","absent-boundary-validation","unprotected-state-transition","missing-integration-contract","absent-edge-case","missing-security-check"],Wg={dimensions:384,minConfidence:.3,maxGaps:50,riskWeight:.6,distanceWeight:.4,namespace:"ghost-surface",idealSurfaceDecay:.95},wi=class u{config;hnswIndex;embedder;idealSurfacePatterns=[];cachedIdealSurface=null;cachedPhantomRatio=1;initialized=!1;constructor(t,e={}){this.config={...Wg,...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 p(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 c=this.embedder.embedFileCoverage(o).vector;n.push(c),i.set(o.path,this.computeGhostVector(c,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 p(y(r))}}async detectPhantomGaps(t,e){try{this.ensureInitialized();let r=e??this.config.minConfidence,i=[];for(let[n,s]of t.ghostVectors){if(Qi(s)<.01)continue;let a=await this.hnswIndex.search(s,5),o=this.getApplicableCategories(n);for(let c of this.classifyGhost(s,a)){if(c.confidence<r||!o.has(c.category))continue;let l=this.gapRiskScore(s,c.category),d=Math.min(1,Qi(s));i.push({id:this.gapId(n,c.category),file:n,category:c.category,ghostDistance:d,riskScore:l,severity:this.toSeverity(d,l),confidence:c.confidence,description:this.gapDescription(n,c.category,d),suggestedLines:c.suggestedLines})}}return i.sort((n,s)=>s.ghostDistance*s.riskScore-n.ghostDistance*n.riskScore),f(i.slice(0,this.config.maxGaps))}catch(r){return p(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 p(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 vt(i)}buildBaselinePatterns(){let t=this.config.dimensions,e=Math.floor(t/bi.length);return bi.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:vt(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 vt(e)}aggregateIdealSurface(){let t=this.config.dimensions;if(this.idealSurfacePatterns.length===0)return vt(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 vt(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 vt(r)}classifyGhost(t,e){let r=this.config.dimensions,i=Math.floor(r/bi.length),n=[],s=0;for(let a of e)a.score>.7&&(s+=a.score*.1);for(let a=0;a<bi.length;a++){let o=a*i,c=Math.min(o+i,r),l=0;for(let m=o;m<c&&m<t.length;m++)l+=t[m]**2;l=Math.sqrt(l/(c-o));let d=Math.min(1,l+s);d>.05&&n.push({category:bi[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,Qi(t)*(u.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-et(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]}};se();var _=class{forward(t){return Math.max(0,t)}backward(t){return t>0?1:0}};var B=class{forward(t){return t}backward(t){return 1}},pe=class u{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=u.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 ms=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]=(L()*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)}},q=class u{layers=[];learningRate;constructor(t){this.learningRate=t.learningRate||.001;for(let e=0;e<t.layerSizes.length-1;e++){let r=new ms({inputSize:t.layerSizes[e],outputSize:t.layerSizes[e+1],activation:t.activations[e]||new _});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),c=r.forward(o,a);i+=c;let l=r.backward(o,a);this.backward(l)}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 u({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]}}};se();var Ke=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(le(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=L()*e.reduce((o,c)=>o+c,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 Yg={stateSize:10,actionSize:4,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0,maxGradNorm:1},ps=class extends ae{qNetwork;targetNetwork;replayBufferClass;qConfig;updateCount=0;actions=[];constructor(t={},e=ou){super("q-learning","value-based",{},e),this.qConfig={...Yg,...t},this.qNetwork=new q({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new Ke(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),c=this.actionToIndex(i.action);if(this.qConfig.doubleDQN&&!i.done){let m=this.qNetwork.forward(s),g=this.argmax(m),b=this.targetNetwork.forward(s)[g];a=i.reward+this.config.discountFactor*b}else{let m=this.targetNetwork.forward(s),g=Math.max(...m);a=i.reward+this.config.discountFactor*g*(i.done?0:1)}let l=new Float32Array(o.length);for(let m=0;m<l.length;m++)l[m]=m===c?a:o[m];let d=this.qNetwork.train(n,l,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 q({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new _).concat([new B]),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 q({layerSizes:[this.qConfig.stateSize,...this.qConfig.hiddenLayers,this.qConfig.actionSize],activations:Array(this.qConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var Xg={maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Fe=R.create("coverage-analysis"),Ci=class extends Q{constructor(e,r,i={}){let n={...Xg,...i};super(e,"coverage-analysis",n,{verifyFindingTypes:["coverage-gap","risk-zone","quality-regression"],...n.consensusConfig});this.memory=r;this.coverageAnalyzer=new mt(r),this.gapDetector=new cr(r),this.riskScorer=new lr(r),this.qLearning=new ps(this.qlConfig,cu)}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),c=this.actionToTestType(o.action),l=this.estimateCoverageGain(a,o.action),d=this.estimateTestDuration(a,c);i.push({filePath:a.file,testType:c,priority:o.value,estimatedCoverageGain:l,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 p(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){Fe.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()&&Fe.warn("Topology degraded, using conservative analysis mode"),this.minCutMixin.shouldPauseOperations())return p(new Error("Coverage analysis paused: topology is in critical state"));let r=await this.coverageAnalyzer.analyze(e);return r.success&&await this.publishCoverageReport(r.value),r}catch(r){return p(y(r))}}async detectGaps(e){try{if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Fe.warn("Topology degraded, using conservative gap detection"),this.minCutMixin.shouldPauseOperations())return p(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)){Fe.info(`Coverage gap in '${n.file}' not verified, skipping publication`);continue}}i.push(n)}return await this.publishGapEvents(i),f({...r.value,gaps:i})}return r}catch(r){return p(y(r))}}async calculateRisk(e){try{if(this.minCutMixin.shouldPauseOperations())return p(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 Fe.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 p(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 l of n){let d=parseInt(l.split(":").pop()||"0",10),m=new Date(d);if(m>=r.start&&m<=r.end){let g=await this.memory.get(l);g&&s.push({date:m,coverage:g})}}s.sort((l,d)=>l.date.getTime()-d.date.getTime());let a=this.aggregateByGranularity(s,i),o=this.analyzeCoverageTrend(a),c=this.forecastCoverage(a);return f({dataPoints:a,trend:o,forecast:c})}catch(r){return p(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 l of a){let d=l.metadata;d&&o.push({gap:{id:l.key,file:d.file||"unknown",lines:[],branches:[],riskScore:d.riskScore||0,severity:d.severity||"low",recommendation:"Similar pattern found in codebase"},similarity:l.score})}let c=Date.now()-n;return f({patterns:o,searchTime:c})}catch(r){return p(y(r))}}async analyzeGhostCoverage(e,r){try{if(!this.ghostAnalyzer){let d={hnswIndex:_r(this.memory),embedder:vi()};this.ghostAnalyzer=new wi(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 p(s.error);let a=s.value,o=await this.ghostAnalyzer.detectPhantomGaps(a),l={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(l)}catch(i){return p(y(i))}}async publishCoverageReport(e){let r={reportId:crypto.randomUUID(),line:e.summary.line,branch:e.summary.branch,function:e.summary.function,statement:e.summary.statement,files:e.summary.files},i=D(Yi.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},s=D(Yi.CoverageGapDetected,"coverage-analysis",n);await this.eventBus.publish(s)}}async publishRiskZoneEvent(e){let r=D(Yi.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,c)=>o+c.coverage.line,0)/s.length,branch:s.reduce((o,c)=>o+c.coverage.branch,0)/s.length,function:s.reduce((o,c)=>o+c.coverage.function,0)/s.length,statement:s.reduce((o,c)=>o+c.coverage.statement,0)/s.length,files:Math.round(s.reduce((o,c)=>o+c.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(l=>{let d=l.coverage;return(d.line+d.branch+d.function+d.statement)/4}),i=r.length,n=0,s=0,a=0,o=0;for(let l=0;l<i;l++)n+=l,s+=r[l],a+=l*r[l],o+=l*l;let c=(i*a-n*s)/(i*o-n*n);return c>.5?"improving":c<-.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=V({id:v(),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"?(Fe.info(`Coverage gap in '${e.file}' verified by consensus`),!0):(Fe.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=V({id:v(),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"?(Fe.info(`Risk zone '${e.file}' classification verified by consensus`),!0):(Fe.warn(`Risk zone '${e.file}' classification NOT verified`),!1)}return!0}async verifyQualityRegression(e,r){let i=V({id:v(),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"?(Fe.info("Quality regression verified by consensus"),!0):(Fe.warn(`Quality regression NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};var gs=class u extends W{static VERSION="1.0.0";coordinator;_activeAnalyses=0;constructor(t,e){super(t,e),this.coordinator=new Ci(t,e)}get name(){return"coverage-analysis"}get version(){return u.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 p(new Error("Invalid analyze-coverage payload: missing coverageData"));this._activeAnalyses++,this.updateAgentMetrics();try{return await this.coordinator.analyze({coverageData:e,threshold:t.threshold,includeFileDetails:t.includeFileDetails})}finally{this._activeAnalyses--,this.updateAgentMetrics()}}],["detect-gaps",async t=>{let e=t.coverageData;if(!e)return p(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 p(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 p(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(Ee.TestRunCompleted,this.handleTestRunCompleted.bind(this))}async onEvent(t){t.type===Ee.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 Zo(u,t){return new gs(u,t)}M();A();A();var Zg={strictMode:!1,enableWarnings:!0,defaultSeverities:{coverage:"high",testsPassing:"critical",criticalBugs:"critical",codeSmells:"medium",securityVulnerabilities:"critical",technicalDebt:"medium",duplications:"low"}},eh={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}}},pt=class{constructor(t,e={}){this.memory=t;this.config={...Zg,...e};for(let[r,i]of Object.entries(eh))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 p(new Error("No metrics provided for gate evaluation"));let n=[],s=[];n.push(...this.evaluateMinThresholds(r,i)),n.push(...this.evaluateMaxThresholds(r,i));for(let l of n)l.passed||s.push(l.name);let a=this.calculateOverallScore(n),o=this.determineGateStatus(n),c={gateName:e,passed:o,checks:n,overallScore:a,failedChecks:s};return await this.storeEvaluationResult(c),f(c)}catch(e){return p(y(e))}}async createGatePreset(t,e){try{let r=`preset-${t}-${v().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 p(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=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})}};M();Zt();var hs=class{parser;fileReader;constructor(){this.parser=new zr,this.fileReader=new De}async analyzeFile(t){let e=await this.fileReader.readFile(t);if(!e.success)return null;let r=e.value,i=r.split(`
2609
- `),{codeLines:n,commentLines:s,blankLines:a}=this.countLines(i),o=t.split("/").pop()||t,c=o.split(".").pop()||"",l=1,d=0,m=0,g=0,h=0;if(["ts","tsx","js","jsx"].includes(c))try{let C=this.parser.parseFile(o,r),S=this.parser.extractFunctions(C);g=S.length;for(let k of S){let O=this.analyzeFunctionComplexity(r,k);l+=O.cyclomaticComplexity-1,d+=O.cognitiveComplexity,m=Math.max(m,this.calculateNestingDepth(r,k))}let P=this.parser.extractClasses(C);h=P.length;for(let k of P)for(let O of k.methods){let z=this.analyzeFunctionComplexity(r,O);l+=z.cyclomaticComplexity-1,d+=z.cognitiveComplexity}}catch{l=this.estimateCyclomaticComplexity(r),d=this.estimateCognitiveComplexity(r)}else{l=this.estimateCyclomaticComplexity(r),d=this.estimateCognitiveComplexity(r);let C=rt(c);if(C&&C!=="typescript"&&C!=="javascript"&&Or.supportsLanguage(C))try{let S=await Or.parseFile(r,t,C);S&&(g=S.functions.length,h=S.classes.length)}catch{g=(r.match(/function\s|def\s|func\s|fn\s/g)||[]).length,h=(r.match(/class\s|struct\s|interface\s/g)||[]).length}else g=(r.match(/function\s|def\s|func\s|fn\s/g)||[]).length,h=(r.match(/class\s|struct\s|interface\s/g)||[]).length}let b=this.calculateHalsteadMetrics(r),w=this.calculateMaintainabilityIndex(b.volume,l,n);return{path:t,linesOfCode:n,linesOfComments:s,blankLines:a,cyclomaticComplexity:l,cognitiveComplexity:d,maintainabilityIndex:w,halsteadMetrics:b,functionCount:g,classCount:h,maxNestingDepth:m}}analyzeFunctionComplexity(t,e){let r=t.split(`
2610
+ `),{codeLines:n,commentLines:s,blankLines:a}=this.countLines(i),o=t.split("/").pop()||t,c=o.split(".").pop()||"",l=1,d=0,m=0,g=0,h=0;if(["ts","tsx","js","jsx"].includes(c))try{let C=this.parser.parseFile(o,r),S=this.parser.extractFunctions(C);g=S.length;for(let P of S){let O=this.analyzeFunctionComplexity(r,P);l+=O.cyclomaticComplexity-1,d+=O.cognitiveComplexity,m=Math.max(m,this.calculateNestingDepth(r,P))}let k=this.parser.extractClasses(C);h=k.length;for(let P of k)for(let O of P.methods){let z=this.analyzeFunctionComplexity(r,O);l+=z.cyclomaticComplexity-1,d+=z.cognitiveComplexity}}catch{l=this.estimateCyclomaticComplexity(r),d=this.estimateCognitiveComplexity(r)}else{l=this.estimateCyclomaticComplexity(r),d=this.estimateCognitiveComplexity(r);let C=rt(c);if(C&&C!=="typescript"&&C!=="javascript"&&Or.supportsLanguage(C))try{let S=await Or.parseFile(r,t,C);S&&(g=S.functions.length,h=S.classes.length)}catch{g=(r.match(/function\s|def\s|func\s|fn\s/g)||[]).length,h=(r.match(/class\s|struct\s|interface\s/g)||[]).length}else g=(r.match(/function\s|def\s|func\s|fn\s/g)||[]).length,h=(r.match(/class\s|struct\s|interface\s/g)||[]).length}let b=this.calculateHalsteadMetrics(r),w=this.calculateMaintainabilityIndex(b.volume,l,n);return{path:t,linesOfCode:n,linesOfComments:s,blankLines:a,cyclomaticComplexity:l,cognitiveComplexity:d,maintainabilityIndex:w,halsteadMetrics:b,functionCount:g,classCount:h,maxNestingDepth:m}}analyzeFunctionComplexity(t,e){let r=t.split(`
2610
2611
  `),i=e.startLine,n=e.endLine,s=r.slice(i-1,n).join(`
2611
2612
  `);return{name:e.name,startLine:i,endLine:n,cyclomaticComplexity:this.calculateCyclomaticComplexity(s),cognitiveComplexity:this.calculateCognitiveComplexity(s),parameterCount:"parameters"in e?e.parameters.length:0,linesOfCode:n-i+1}}async detectDuplication(t,e=5){let r=new Map,i=0,n=0;for(let c of t){let l=await this.fileReader.readFile(c);if(l.success){let d=l.value.split(`
2612
2613
  `).map(m=>m.trim());r.set(c,d),i+=d.length}}let s=new Map,a=[];for(let[c,l]of r.entries())for(let d=0;d<l.length-e+1;d++){let m=l.slice(d,d+e).join(`
2613
2614
  `);if(m.length<20)continue;let g=this.hashString(m),h=s.get(g)||[];h.push({file:c,line:d+1}),s.set(g,h)}for(let[,c]of s.entries())c.length>1&&(n+=e*(c.length-1),a.push({lines:e,occurrences:c.length,locations:c.map(l=>({file:l.file,startLine:l.line,endLine:l.line+e-1}))}));let o=a.sort((c,l)=>l.occurrences-c.occurrences).slice(0,20);return{percentage:i>0?Math.round(n/i*100*10)/10:0,duplicates:o}}countLines(t){let e=0,r=0,i=0,n=!1;for(let s of t){let a=s.trim();if(a===""){i++;continue}if(n){r++,a.includes("*/")&&(n=!1);continue}a.startsWith("//")?r++:a.startsWith("/*")?(r++,a.includes("*/")||(n=!0)):(e++,(a.includes("//")||a.includes("/*"))&&r++)}return{codeLines:e,commentLines:r,blankLines:i}}calculateCyclomaticComplexity(t){let e=[/\bif\s*\(/g,/\belse\s+if\s*\(/g,/\bfor\s*\(/g,/\bwhile\s*\(/g,/\bcase\s+/g,/\bcatch\s*\(/g,/\?\s*[^:]/g,/&&/g,/\|\|/g,/\?\?/g],r=1;for(let i of e){let n=t.match(i);n&&(r+=n.length)}return r}calculateCognitiveComplexity(t){let e=0,r=0,i=t.split(`
2614
2615
  `);for(let n of i){let s=n.trim();/\bif\s*\(/.test(s)&&(e+=1+r,r++),/\belse\s+if\s*\(/.test(s)&&(e+=1+r),/\belse\s*{/.test(s)&&(e+=1),/\bfor\s*\(/.test(s)&&(e+=1+r,r++),/\bwhile\s*\(/.test(s)&&(e+=1+r,r++),/\bswitch\s*\(/.test(s)&&(e+=1+r,r++),/\bcatch\s*\(/.test(s)&&(e+=1+r,r++),/\?\s*[^:]/.test(s)&&(e+=1+r),/&&|\|\|/.test(s)&&(e+=1);let a=(s.match(/{/g)||[]).length,o=(s.match(/}/g)||[]).length;r=Math.max(0,r+a-o)}return e}estimateCyclomaticComplexity(t){return this.calculateCyclomaticComplexity(t)}estimateCognitiveComplexity(t){return this.calculateCognitiveComplexity(t)}calculateNestingDepth(t,e){let i=t.split(`
2615
2616
  `).slice(e.startLine-1,e.endLine).join(`
2616
- `),n=0,s=0;for(let a of i)a==="{"?(s++,n=Math.max(n,s)):a==="}"&&(s=Math.max(0,s-1));return n}calculateHalsteadMetrics(t){let e=new Set,r=new Set,i=0,n=0,s=[/[+\-*/%]=?/g,/[<>]=?/g,/[!=]=?=?/g,/&&|\|\|/g,/\+\+|--/g,/\./g,/,/g,/:/g,/\?/g,/=>/g];for(let P of s){let k=t.match(P);if(k)for(let O of k)e.add(O),i++}let a=/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,o=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","this","true","false","null","undefined","typeof","import","export","default","from","async","await","try","catch","finally","throw","interface","type","extends"]),c=t.match(a);if(c)for(let P of c)o.has(P)||(r.add(P),n++);let l=e.size,d=r.size,m=i,g=n,h=l+d,b=m+g,w=b>0&&h>0?b*Math.log2(h):0,C=d>0?l/2*(g/d):0,S=w*C;return{vocabulary:h,length:b,volume:Math.round(w*100)/100,difficulty:Math.round(C*100)/100,effort:Math.round(S*100)/100}}calculateMaintainabilityIndex(t,e,r){if(r<=0||t<=0)return 100;let i=Math.log(t),n=Math.log(r),s=171-5.2*i-.23*e-16.2*n,a=Math.max(0,Math.min(100,s*100/171));return Math.round(a*100)/100}hashString(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)}},ec=null;function tc(){return ec||(ec=new hs),ec}import*as Je from"os";var fs=class{lastCpuUsage=null;lastCpuTime=0;metricHistory=new Map;maxHistorySize;constructor(t=1e3){this.maxHistorySize=t}collectSystemMetrics(){let t=this.collectCpuMetrics(),e=this.collectMemoryMetrics(),r=this.collectProcessMetrics(),i={timestamp:new Date,cpu:t,memory:e,process:r};return this.recordMetric("cpu_usage",t.usage),this.recordMetric("memory_usage",e.usage),this.recordMetric("process_cpu_usage",r.cpuUsage),this.recordMetric("process_memory_usage",r.memoryUsage),i}collectCpuMetrics(){let t=Je.cpus(),e=Je.loadavg(),r=0,i=0;for(let s of t){for(let a of Object.keys(s.times))i+=s.times[a];r+=s.times.idle}let n=i>0?(i-r)/i*100:0;return{usage:Math.round(n*100)/100,loadAverage:e,cores:t.length}}collectMemoryMetrics(){let t=Je.totalmem(),e=Je.freemem(),r=t-e,i=r/t*100;return{usage:Math.round(i*100)/100,total:t,free:e,used:r}}collectProcessMetrics(){let t=process.memoryUsage(),e=process.cpuUsage(this.lastCpuUsage??void 0),r=Date.now(),n=(this.lastCpuTime>0?r-this.lastCpuTime:1e3)*1e3,a=(e.user+e.system)/n*100;this.lastCpuUsage=e,this.lastCpuTime=r;let o=Je.totalmem(),c=t.rss/o*100;return{cpuUsage:Math.min(100,Math.round(a*100)/100),memoryUsage:Math.round(c*100)/100,heapUsed:t.heapUsed,heapTotal:t.heapTotal,rss:t.rss,uptime:process.uptime()}}getMetricValue(t){let e=this.collectSystemMetrics();switch(t){case"cpu_usage":return e.cpu.usage;case"memory_usage":return e.memory.usage;case"process_cpu_usage":return e.process.cpuUsage;case"process_memory_usage":return e.process.memoryUsage;case"heap_used":return e.process.heapUsed;case"heap_total":return e.process.heapTotal;case"rss":return e.process.rss;case"load_average_1m":return e.cpu.loadAverage[0];case"load_average_5m":return e.cpu.loadAverage[1];case"load_average_15m":return e.cpu.loadAverage[2];default:let r=this.metricHistory.get(t);return r&&r.length>0?r[r.length-1].value:0}}getChaosMetricValue(t){let r={response_time_ms:()=>this.getResponseTimeEstimate(),error_rate:()=>this.getErrorRateEstimate(),throughput:()=>this.getThroughputEstimate(),cpu_usage:()=>this.collectSystemMetrics().cpu.usage,memory_usage:()=>this.collectSystemMetrics().memory.usage,latency_p50:()=>this.getLatencyPercentile(50),latency_p95:()=>this.getLatencyPercentile(95),latency_p99:()=>this.getLatencyPercentile(99)}[t];return r?r():this.getMetricValue(t)}recordMetric(t,e,r){let i={name:t,value:e,timestamp:new Date,labels:r},n=this.metricHistory.get(t)||[];n.push(i),n.length>this.maxHistorySize&&n.shift(),this.metricHistory.set(t,n)}recordHttpMetrics(t){this.recordMetric("response_time_ms",t.responseTimeMs),this.recordMetric("http_status",t.statusCode),this.recordMetric("http_success",t.success?1:0)}getMetricHistory(t,e){let r=this.metricHistory.get(t)||[];return e&&r.length>e?r.slice(-e):[...r]}getMetricAverage(t,e=10){let r=this.getMetricHistory(t,e);return r.length===0?0:r.reduce((n,s)=>n+s.value,0)/r.length}getResponseTimeEstimate(){let t=this.collectSystemMetrics().cpu,e=50,r=1+t.usage/100;return Math.round(e*r)}getErrorRateEstimate(){let t=this.getMetricHistory("http_success",100);return t.length===0?0:t.filter(r=>r.value===0).length/t.length}getThroughputEstimate(){let t=this.getMetricHistory("response_time_ms",100);if(t.length<2)return 1e3;let e=t[0].timestamp.getTime(),i=(t[t.length-1].timestamp.getTime()-e)/1e3;return i<=0?1e3:Math.round(t.length/i)}getLatencyPercentile(t){let e=this.getMetricHistory("response_time_ms",1e3);if(e.length===0)return 50;let r=e.map(n=>n.value).sort((n,s)=>n-s),i=Math.floor(t/100*r.length);return r[Math.min(i,r.length-1)]}clearHistory(){this.metricHistory.clear()}},rc=null;function ic(){return rc||(rc=new fs),rc}A();H();var th={enableTrendAnalysis:!0,trendDataPointsMin:3,complexityThresholds:{cyclomatic:{warning:10,critical:20},cognitive:{warning:15,critical:30},maintainability:{warning:50,critical:30}},enableLLMInsights:!0,llmModelTier:2,llmMaxTokens:2048},ys={A:90,B:80,C:70,D:50,E:0},Ou=R.create("quality-assessment/quality-analyzer"),Ye=class{config;metricsAnalyzer;memory;llmRouter;constructor(t,e={}){this.config={...th,...e},this.metricsAnalyzer=tc(),"memory"in t?(this.memory=t.memory,this.llmRouter=t.llmRouter):(this.memory=t,this.llmRouter=void 0)}isLLMInsightsAvailable(){return this.config.enableLLMInsights===!0&&this.llmRouter!==void 0}getModelForTier(t){switch(t){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async generateQualityInsightsWithLLM(t,e,r){if(!this.llmRouter)return null;try{let i=this.buildQualityInsightsPrompt(t,e,r),n=this.getModelForTier(this.config.llmModelTier??2),s=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software quality engineer. Analyze quality metrics and provide actionable insights.
2617
+ `),n=0,s=0;for(let a of i)a==="{"?(s++,n=Math.max(n,s)):a==="}"&&(s=Math.max(0,s-1));return n}calculateHalsteadMetrics(t){let e=new Set,r=new Set,i=0,n=0,s=[/[+\-*/%]=?/g,/[<>]=?/g,/[!=]=?=?/g,/&&|\|\|/g,/\+\+|--/g,/\./g,/,/g,/:/g,/\?/g,/=>/g];for(let k of s){let P=t.match(k);if(P)for(let O of P)e.add(O),i++}let a=/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g,o=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","class","const","let","var","new","this","true","false","null","undefined","typeof","import","export","default","from","async","await","try","catch","finally","throw","interface","type","extends"]),c=t.match(a);if(c)for(let k of c)o.has(k)||(r.add(k),n++);let l=e.size,d=r.size,m=i,g=n,h=l+d,b=m+g,w=b>0&&h>0?b*Math.log2(h):0,C=d>0?l/2*(g/d):0,S=w*C;return{vocabulary:h,length:b,volume:Math.round(w*100)/100,difficulty:Math.round(C*100)/100,effort:Math.round(S*100)/100}}calculateMaintainabilityIndex(t,e,r){if(r<=0||t<=0)return 100;let i=Math.log(t),n=Math.log(r),s=171-5.2*i-.23*e-16.2*n,a=Math.max(0,Math.min(100,s*100/171));return Math.round(a*100)/100}hashString(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)}},ec=null;function tc(){return ec||(ec=new hs),ec}import*as Je from"os";var fs=class{lastCpuUsage=null;lastCpuTime=0;metricHistory=new Map;maxHistorySize;constructor(t=1e3){this.maxHistorySize=t}collectSystemMetrics(){let t=this.collectCpuMetrics(),e=this.collectMemoryMetrics(),r=this.collectProcessMetrics(),i={timestamp:new Date,cpu:t,memory:e,process:r};return this.recordMetric("cpu_usage",t.usage),this.recordMetric("memory_usage",e.usage),this.recordMetric("process_cpu_usage",r.cpuUsage),this.recordMetric("process_memory_usage",r.memoryUsage),i}collectCpuMetrics(){let t=Je.cpus(),e=Je.loadavg(),r=0,i=0;for(let s of t){for(let a of Object.keys(s.times))i+=s.times[a];r+=s.times.idle}let n=i>0?(i-r)/i*100:0;return{usage:Math.round(n*100)/100,loadAverage:e,cores:t.length}}collectMemoryMetrics(){let t=Je.totalmem(),e=Je.freemem(),r=t-e,i=r/t*100;return{usage:Math.round(i*100)/100,total:t,free:e,used:r}}collectProcessMetrics(){let t=process.memoryUsage(),e=process.cpuUsage(this.lastCpuUsage??void 0),r=Date.now(),n=(this.lastCpuTime>0?r-this.lastCpuTime:1e3)*1e3,a=(e.user+e.system)/n*100;this.lastCpuUsage=e,this.lastCpuTime=r;let o=Je.totalmem(),c=t.rss/o*100;return{cpuUsage:Math.min(100,Math.round(a*100)/100),memoryUsage:Math.round(c*100)/100,heapUsed:t.heapUsed,heapTotal:t.heapTotal,rss:t.rss,uptime:process.uptime()}}getMetricValue(t){let e=this.collectSystemMetrics();switch(t){case"cpu_usage":return e.cpu.usage;case"memory_usage":return e.memory.usage;case"process_cpu_usage":return e.process.cpuUsage;case"process_memory_usage":return e.process.memoryUsage;case"heap_used":return e.process.heapUsed;case"heap_total":return e.process.heapTotal;case"rss":return e.process.rss;case"load_average_1m":return e.cpu.loadAverage[0];case"load_average_5m":return e.cpu.loadAverage[1];case"load_average_15m":return e.cpu.loadAverage[2];default:let r=this.metricHistory.get(t);return r&&r.length>0?r[r.length-1].value:0}}getChaosMetricValue(t){let r={response_time_ms:()=>this.getResponseTimeEstimate(),error_rate:()=>this.getErrorRateEstimate(),throughput:()=>this.getThroughputEstimate(),cpu_usage:()=>this.collectSystemMetrics().cpu.usage,memory_usage:()=>this.collectSystemMetrics().memory.usage,latency_p50:()=>this.getLatencyPercentile(50),latency_p95:()=>this.getLatencyPercentile(95),latency_p99:()=>this.getLatencyPercentile(99)}[t];return r?r():this.getMetricValue(t)}recordMetric(t,e,r){let i={name:t,value:e,timestamp:new Date,labels:r},n=this.metricHistory.get(t)||[];n.push(i),n.length>this.maxHistorySize&&n.shift(),this.metricHistory.set(t,n)}recordHttpMetrics(t){this.recordMetric("response_time_ms",t.responseTimeMs),this.recordMetric("http_status",t.statusCode),this.recordMetric("http_success",t.success?1:0)}getMetricHistory(t,e){let r=this.metricHistory.get(t)||[];return e&&r.length>e?r.slice(-e):[...r]}getMetricAverage(t,e=10){let r=this.getMetricHistory(t,e);return r.length===0?0:r.reduce((n,s)=>n+s.value,0)/r.length}getResponseTimeEstimate(){let t=this.collectSystemMetrics().cpu,e=50,r=1+t.usage/100;return Math.round(e*r)}getErrorRateEstimate(){let t=this.getMetricHistory("http_success",100);return t.length===0?0:t.filter(r=>r.value===0).length/t.length}getThroughputEstimate(){let t=this.getMetricHistory("response_time_ms",100);if(t.length<2)return 1e3;let e=t[0].timestamp.getTime(),i=(t[t.length-1].timestamp.getTime()-e)/1e3;return i<=0?1e3:Math.round(t.length/i)}getLatencyPercentile(t){let e=this.getMetricHistory("response_time_ms",1e3);if(e.length===0)return 50;let r=e.map(n=>n.value).sort((n,s)=>n-s),i=Math.floor(t/100*r.length);return r[Math.min(i,r.length-1)]}clearHistory(){this.metricHistory.clear()}},rc=null;function ic(){return rc||(rc=new fs),rc}A();H();var th={enableTrendAnalysis:!0,trendDataPointsMin:3,complexityThresholds:{cyclomatic:{warning:10,critical:20},cognitive:{warning:15,critical:30},maintainability:{warning:50,critical:30}},enableLLMInsights:!0,llmModelTier:2,llmMaxTokens:2048},ys={A:90,B:80,C:70,D:50,E:0},Ou=R.create("quality-assessment/quality-analyzer"),Ye=class{config;metricsAnalyzer;memory;llmRouter;constructor(t,e={}){this.config={...th,...e},this.metricsAnalyzer=tc(),"memory"in t?(this.memory=t.memory,this.llmRouter=t.llmRouter):(this.memory=t,this.llmRouter=void 0)}isLLMInsightsAvailable(){return this.config.enableLLMInsights===!0&&this.llmRouter!==void 0}getModelForTier(t){switch(t){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async generateQualityInsightsWithLLM(t,e,r){if(!this.llmRouter)return null;try{let i=this.buildQualityInsightsPrompt(t,e,r),n=this.getModelForTier(this.config.llmModelTier??2),s=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software quality engineer. Analyze quality metrics and provide actionable insights.
2617
2618
 
2618
2619
  Your response MUST be valid JSON with this exact structure:
2619
2620
  {
@@ -2709,7 +2710,7 @@ Estimated Rollback Time: ${t.rollbackPlan.estimatedTime}`),a.length>0&&(s=a.join
2709
2710
 
2710
2711
  \`\`\`json
2711
2712
  ${JSON.stringify(u,null,2)}
2712
- \`\`\``}M();A();se();var ch={stateSize:10,actionSize:4,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],actorLR:1e-4,criticLR:.001,entropyCoeff:.01},vs=class extends ae{actor;critic;acConfig;actions=[];constructor(t={}){super("actor-critic","policy-based"),this.acConfig={...ch,...t},this.initializeActions(),this.actor=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.actorHiddenLayers,this.acConfig.actionSize],activations:Array(this.acConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.actorLR}),this.critic=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.criticHiddenLayers,1],activations:Array(this.acConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.criticLR})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=pe.forward(this.actor.forward(e)),i=this.sampleAction(r),n=this.actions[i],s=this.critic.forward(e)[0],a=Math.max(.3,Math.min(1,r[i]+.3));return{action:n,confidence:a,value:s,reasoning:this.generateReasoning(t,n,s,r[i])}}async trainCore(t){let e=0,r=0;for(let i of t){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a=this.actionToIndex(i.action),o=this.actor.forward(n),c=pe.forward(o),l=Math.log(c[a]+1e-10),d=this.critic.forward(n)[0],m=i.done?0:this.critic.forward(s)[0],g=i.reward+this.config.discountFactor*m-d,h=new Float32Array([i.reward+this.config.discountFactor*m]),b=this.critic.train(n,h,new fe),w=-l*g,C=this.calculateEntropy(c),S=this.acConfig.entropyCoeff*C,P=w-S,k=new Float32Array(c.length);for(let O=0;O<k.length;O++){let z=Math.log(c[O]+1e-10),K=O===a?-g:0;k[O]=K-this.acConfig.entropyCoeff*(c[O]*Math.log(c[O]+1e-10))}this.actor.backward(k);for(let O of this.actor.layers)O.update(this.acConfig.actorLR);e+=Math.abs(P),r+=Math.abs(b)}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:(e+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 Actor-Critic for Quality Gate Threshold Tuning",capabilities:["Neural Actor learns optimal threshold policy","Neural Critic provides value estimates","Lower variance than REINFORCE","Online learning with bootstrapping"],hyperparameters:{stateSize:this.acConfig.stateSize,actionSize:this.acConfig.actionSize,actorLR:this.acConfig.actorLR,criticLR:this.acConfig.criticLR,entropyCoeff:this.acConfig.entropyCoeff},stats:this.stats}}sampleAction(t){if(L()<this.config.explorationRate)return le(0,this.actions.length);let e=L(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}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}prepareState(t){let e=t.features.slice(0,this.acConfig.stateSize);for(;e.length<this.acConfig.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:"adjust-threshold",value:.1},{type:"adjust-threshold",value:-.1},{type:"approve",value:1},{type:"reject",value:0}],this.acConfig.actionSize=this.actions.length,this.actor=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.actorHiddenLayers,this.acConfig.actionSize],activations:Array(this.acConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.actorLR})}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)}`}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}generateReasoning(t,e,r,i){return this.episodeCount<10?`Neural Actor-Critic learning (episode ${this.episodeCount}): exploring actions`:`Neural Actor-Critic: ${e.type} (prob: ${i.toFixed(3)}, state value: ${r.toFixed(3)})`}async exportCustomData(){return{actor:this.actor.getParameters(),critic:this.critic.getParameters(),acConfig:this.acConfig}}async importCustomData(t){t.actor&&this.actor.setParameters(t.actor),t.critic&&this.critic.setParameters(t.critic),t.acConfig&&(this.acConfig={...this.acConfig,...t.acConfig}),this.initialized=!0}async resetAlgorithm(){this.actor=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.actorHiddenLayers,this.acConfig.actionSize],activations:Array(this.acConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.actorLR}),this.critic=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.criticHiddenLayers,1],activations:Array(this.acConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.criticLR})}};var gt=R.create("quality-assessment/rl-integration");async function Hu(){try{return new vs({stateSize:10,actionSize:4,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],actorLR:1e-4,criticLR:.001,entropyCoeff:.01})}catch(u){throw new Error(`Failed to initialize Actor-Critic RL: ${T(u)}`)}}async function Wu(){try{let u=await me({domain:"quality-assessment",loadOnInit:!0,autoSaveInterval:6e4,hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,minConfidence:.5,maxPatterns:5e3});return gt.info("PersistentSONAEngine initialized successfully"),u}catch(u){gt.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),gt.warn("Continuing without SONA pattern persistence");return}}async function ju(){try{return await Ie("pattern-adaptation",{dim:384,strategy:"flash",blockSize:32})}catch(u){throw new Error(`Failed to initialize QEFlashAttention: ${T(u)}`)}}async function Uu(u,t){try{let e={id:`quality-state-${Date.now()}`,features:[t.coverage/100,t.testsPassing/100,t.criticalBugs/10,t.codeSmells/50,t.securityVulnerabilities/10,t.technicalDebt/20,t.duplications/20]},r=await u.predict(e);return{thresholds:lh({coverage:{min:80},testsPassing:{min:95},criticalBugs:{max:0},codeSmells:{max:20},securityVulnerabilities:{max:0},technicalDebt:{max:5},duplications:{max:5}},r.action),confidence:r.confidence,reasoning:r.reasoning??""}}catch(e){return gt.error("RL threshold tuning failed:",e instanceof Error?e:void 0),null}}function lh(u,t){let e={...u};if(t.type==="adjust-threshold"&&typeof t.value=="number"){let r=t.value*5;e.coverage?.min!==void 0&&(e.coverage.min=Math.max(50,Math.min(100,e.coverage.min+r))),e.codeSmells?.max!==void 0&&(e.codeSmells.max=Math.max(0,Math.min(100,e.codeSmells.max-r)))}return e}async function Qu(u,t,e){try{let r={id:`quality-state-${Date.now()}`,features:[t.metrics.coverage/100,t.metrics.testsPassing/100,t.metrics.criticalBugs/10,t.metrics.codeSmells/50,t.metrics.securityVulnerabilities/10,t.metrics.technicalDebt/20,t.metrics.duplications/20]},i={type:"evaluate-gate",value:e.overallScore},n={...r},s=0;if(e.passed)s+=e.overallScore/100,e.overallScore>=90&&(s+=.5),e.overallScore>=95&&(s+=.5);else{s-=.5;let o=e.checks.filter(c=>!c.passed&&c.severity==="critical").length;s-=o*.2}let a={state:r,action:i,nextState:n,reward:Math.max(-1,Math.min(1,s)),done:!0};await u.train(a)}catch(r){gt.error("Actor-Critic training failed:",r instanceof Error?r:void 0)}}async function Ku(u,t,e,r){try{let i={id:`quality-state-${Date.now()}`,features:[t.metrics.coverage,t.metrics.testsPassing,t.metrics.criticalBugs,t.metrics.codeSmells,t.metrics.securityVulnerabilities,t.metrics.technicalDebt,t.metrics.duplications]},n={type:"quality-gate-evaluation",value:e.passed?1:0};u.createPattern(i,n,{reward:e.passed?e.overallScore/100:-.5,success:e.passed,quality:e.overallScore/100},"quality-assessment",r,{gateName:t.gateName,overallScore:e.overallScore,failedChecks:e.failedChecks})}catch(i){gt.error("Failed to store quality pattern in SONA:",i instanceof Error?i:void 0)}}async function Ju(u,t,e,r){try{let i={id:`quality-analysis-${Date.now()}`,features:[e.score.overall,e.score.coverage,e.score.complexity,e.score.maintainability,e.metrics.length,t.sourceFiles.length]},n={type:"quality-analysis",value:e.score.overall};u.createPattern(i,n,{reward:e.score.overall/100,success:e.score.overall>=70,quality:e.score.overall/100},"quality-assessment",r,{sourceFileCount:t.sourceFiles.length,recommendationCount:e.recommendations.length})}catch(i){gt.error("Failed to store quality analysis pattern in SONA:",i instanceof Error?i:void 0)}}async function Yu(u,t,e,r){try{let i={id:`similarity-search-${Date.now()}`,features:[u.score.overall,u.score.coverage,u.score.complexity,u.score.maintainability]},n=await e.adaptPattern(i,"quality-assessment",r);if(!n.success||!n.pattern)return null;let s=[];if(n.pattern.metadata){let a=n.pattern.metadata;a.similarIssues&&a.similarIssues.length>0&&s.push({type:"improvement",title:"Similar Quality Patterns Found",description:`Found ${n.similarity.toFixed(0)}% similar historical patterns: ${a.similarIssues.slice(0,3).join(", ")}`,impact:"medium",effort:"low"})}return{...u,recommendations:[...u.recommendations,...s]}}catch(i){return gt.error("Failed to enhance with similarity patterns:",i instanceof Error?i:void 0),null}}function Xu(u){let t=[],e={pattern_merge:.2,novel_association:.4,optimization:.6,gap_detection:.8};for(t.push(e[u.type]||.5),t.push(u.confidenceScore),t.push(u.noveltyScore),t.push(u.actionable?1:0),t.push(Math.min(1,u.sourceConcepts.length/10));t.length<384;)t.push(0);return t.slice(0,384)}M();A();function bs(u,t,e){let r=new Error(t);return r.code=u,r.claimId=e?.claimId,r.details=e?.details,r.retryable=e?.retryable??!1,r}var nc={defaultConfidenceThreshold:.8,defaultTimeout:3e4,reportQualityThreshold:.85,enableMultiModel:!0,maxParallelVerifications:5,enableStatistics:!0,statisticsPersistInterval:6e4},ws={"security-implementation":"code-trace","security-vulnerability":"code-trace","metric-count":"execution","pattern-implementation":"cross-file","coverage-claim":"execution"},Cs=["security-implementation","security-vulnerability"];import{readFile as dh,stat as sc}from"node:fs/promises";import{join as Zu}from"node:path";import mh from"fast-glob";var Ri=class{config;constructor(t){this.config={rootDir:t.rootDir,maxFileSize:t.maxFileSize??10*1024*1024,encoding:t.encoding??"utf-8",excludePatterns:t.excludePatterns??["node_modules/**",".git/**","dist/**"]}}async verify(t,e){let r=Date.now(),i=e?.checkAllInstances??!0;try{let n=this.extractFilePatterns(t),s=this.extractSearchPatterns(t),a=[],o=!1,c="",l=0,d=0;if(n.length>0){let h=await this.verifyFileExistence(n);a.push(...h.evidence),l+=h.total,d+=h.passed,h.passed===h.total?(o=!0,c=`All ${h.total} referenced files exist`):(o=!1,c=`${h.total-h.passed} of ${h.total} files not found`)}if(s.length>0){let h=await this.verifyContentPatterns(s,i,e?.maxInstances);a.push(...h.evidence),l+=h.total,d+=h.passed,h.passed>0?(o=!0,c=i?`Pattern found in all ${h.passed} instances`:`Pattern found in ${h.passed} of ${h.total} checked files`):(o=!1,c=`Pattern not found in any of ${h.total} checked files`)}if(n.length===0&&s.length===0){let h=await this.verifyExistingEvidence(t.evidence);a=h.evidence,o=h.verified,c=h.reasoning,l=h.total,d=h.passed}let m=Date.now()-r,g=this.calculateConfidence(d,l,o);return{claimId:t.id,verified:o,confidence:g,method:"cross-file",reasoning:c,allInstancesChecked:i,instancesChecked:l,instancesPassed:d,verificationTimeMs:m,verifiedAt:new Date,requiresHumanReview:g<.7,counterEvidence:o?void 0:a.filter(h=>!h.verified)}}catch(n){let s=Date.now()-r,a=n instanceof Error?n.message:"Unknown error";return{claimId:t.id,verified:!1,confidence:0,method:"cross-file",reasoning:`Verification failed: ${a}`,allInstancesChecked:!1,instancesChecked:0,instancesPassed:0,verificationTimeMs:s,verifiedAt:new Date,requiresHumanReview:!0}}}extractFilePatterns(t){let e=[];for(let n of t.evidence)if(n.type==="file-reference"||n.type==="code-snippet"){let s=n.location.split(":")[0];s&&!e.includes(s)&&e.push(s)}let r=/(?:src\/|tests\/|lib\/|app\/)[\w\-/.]+\.[\w]+/g,i=t.statement.match(r);return i&&e.push(...i.filter(n=>!e.includes(n))),e}extractSearchPatterns(t){let e=[],r=["parameterized queries","prepared statements","input validation","sanitization","csrf token","xss prevention"];for(let i of r)t.statement.toLowerCase().includes(i)&&e.push({pattern:i});return e}async verifyFileExistence(t){let e=[],r=0;for(let i of t){let n=Zu(this.config.rootDir,i);try{let s=await sc(n),a=s.isFile();e.push({type:"file-reference",location:i,content:a?`File exists (${s.size} bytes)`:"File not found",verified:a,timestamp:new Date}),a&&r++}catch(s){e.push({type:"file-reference",location:i,content:`File not accessible: ${s instanceof Error?s.message:"Unknown error"}`,verified:!1,timestamp:new Date})}}return{evidence:e,total:t.length,passed:r}}async verifyContentPatterns(t,e,r){let i=[],n=0,s=0;for(let{pattern:a,fileGlob:o}of t){let l=await mh(o??"**/*.{ts,js,tsx,jsx}",{cwd:this.config.rootDir,ignore:this.config.excludePatterns,absolute:!0}),d=r&&!e?l.slice(0,r):l;n+=d.length;for(let m of d){let g=await this.searchFileForPattern(m,a);if(g.matches.length>0){s++;for(let h of g.matches)i.push({type:"code-snippet",location:`${g.filePath}:${h.line}`,content:h.content,verified:!0,timestamp:new Date,contentHash:Ti(h.content)})}}}return{evidence:i,total:n,passed:s}}async searchFileForPattern(t,e){try{if((await sc(t)).size>this.config.maxFileSize)return{filePath:t,matches:[]};let n=(await dh(t,this.config.encoding)).split(`
2713
+ \`\`\``}M();A();se();var ch={stateSize:10,actionSize:4,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],actorLR:1e-4,criticLR:.001,entropyCoeff:.01},vs=class extends ae{actor;critic;acConfig;actions=[];constructor(t={}){super("actor-critic","policy-based"),this.acConfig={...ch,...t},this.initializeActions(),this.actor=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.actorHiddenLayers,this.acConfig.actionSize],activations:Array(this.acConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.actorLR}),this.critic=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.criticHiddenLayers,1],activations:Array(this.acConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.criticLR})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=pe.forward(this.actor.forward(e)),i=this.sampleAction(r),n=this.actions[i],s=this.critic.forward(e)[0],a=Math.max(.3,Math.min(1,r[i]+.3));return{action:n,confidence:a,value:s,reasoning:this.generateReasoning(t,n,s,r[i])}}async trainCore(t){let e=0,r=0;for(let i of t){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a=this.actionToIndex(i.action),o=this.actor.forward(n),c=pe.forward(o),l=Math.log(c[a]+1e-10),d=this.critic.forward(n)[0],m=i.done?0:this.critic.forward(s)[0],g=i.reward+this.config.discountFactor*m-d,h=new Float32Array([i.reward+this.config.discountFactor*m]),b=this.critic.train(n,h,new fe),w=-l*g,C=this.calculateEntropy(c),S=this.acConfig.entropyCoeff*C,k=w-S,P=new Float32Array(c.length);for(let O=0;O<P.length;O++){let z=Math.log(c[O]+1e-10),K=O===a?-g:0;P[O]=K-this.acConfig.entropyCoeff*(c[O]*Math.log(c[O]+1e-10))}this.actor.backward(P);for(let O of this.actor.layers)O.update(this.acConfig.actorLR);e+=Math.abs(k),r+=Math.abs(b)}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:(e+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 Actor-Critic for Quality Gate Threshold Tuning",capabilities:["Neural Actor learns optimal threshold policy","Neural Critic provides value estimates","Lower variance than REINFORCE","Online learning with bootstrapping"],hyperparameters:{stateSize:this.acConfig.stateSize,actionSize:this.acConfig.actionSize,actorLR:this.acConfig.actorLR,criticLR:this.acConfig.criticLR,entropyCoeff:this.acConfig.entropyCoeff},stats:this.stats}}sampleAction(t){if(L()<this.config.explorationRate)return le(0,this.actions.length);let e=L(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}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}prepareState(t){let e=t.features.slice(0,this.acConfig.stateSize);for(;e.length<this.acConfig.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:"adjust-threshold",value:.1},{type:"adjust-threshold",value:-.1},{type:"approve",value:1},{type:"reject",value:0}],this.acConfig.actionSize=this.actions.length,this.actor=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.actorHiddenLayers,this.acConfig.actionSize],activations:Array(this.acConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.actorLR})}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)}`}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}generateReasoning(t,e,r,i){return this.episodeCount<10?`Neural Actor-Critic learning (episode ${this.episodeCount}): exploring actions`:`Neural Actor-Critic: ${e.type} (prob: ${i.toFixed(3)}, state value: ${r.toFixed(3)})`}async exportCustomData(){return{actor:this.actor.getParameters(),critic:this.critic.getParameters(),acConfig:this.acConfig}}async importCustomData(t){t.actor&&this.actor.setParameters(t.actor),t.critic&&this.critic.setParameters(t.critic),t.acConfig&&(this.acConfig={...this.acConfig,...t.acConfig}),this.initialized=!0}async resetAlgorithm(){this.actor=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.actorHiddenLayers,this.acConfig.actionSize],activations:Array(this.acConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.actorLR}),this.critic=new q({layerSizes:[this.acConfig.stateSize,...this.acConfig.criticHiddenLayers,1],activations:Array(this.acConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.acConfig.criticLR})}};var gt=R.create("quality-assessment/rl-integration");async function Hu(){try{return new vs({stateSize:10,actionSize:4,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],actorLR:1e-4,criticLR:.001,entropyCoeff:.01})}catch(u){throw new Error(`Failed to initialize Actor-Critic RL: ${T(u)}`)}}async function Wu(){try{let u=await me({domain:"quality-assessment",loadOnInit:!0,autoSaveInterval:6e4,hiddenDim:256,embeddingDim:384,microLoraRank:1,baseLoraRank:8,minConfidence:.5,maxPatterns:5e3});return gt.info("PersistentSONAEngine initialized successfully"),u}catch(u){gt.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),gt.warn("Continuing without SONA pattern persistence");return}}async function ju(){try{return await Ie("pattern-adaptation",{dim:384,strategy:"flash",blockSize:32})}catch(u){throw new Error(`Failed to initialize QEFlashAttention: ${T(u)}`)}}async function Uu(u,t){try{let e={id:`quality-state-${Date.now()}`,features:[t.coverage/100,t.testsPassing/100,t.criticalBugs/10,t.codeSmells/50,t.securityVulnerabilities/10,t.technicalDebt/20,t.duplications/20]},r=await u.predict(e);return{thresholds:lh({coverage:{min:80},testsPassing:{min:95},criticalBugs:{max:0},codeSmells:{max:20},securityVulnerabilities:{max:0},technicalDebt:{max:5},duplications:{max:5}},r.action),confidence:r.confidence,reasoning:r.reasoning??""}}catch(e){return gt.error("RL threshold tuning failed:",e instanceof Error?e:void 0),null}}function lh(u,t){let e={...u};if(t.type==="adjust-threshold"&&typeof t.value=="number"){let r=t.value*5;e.coverage?.min!==void 0&&(e.coverage.min=Math.max(50,Math.min(100,e.coverage.min+r))),e.codeSmells?.max!==void 0&&(e.codeSmells.max=Math.max(0,Math.min(100,e.codeSmells.max-r)))}return e}async function Qu(u,t,e){try{let r={id:`quality-state-${Date.now()}`,features:[t.metrics.coverage/100,t.metrics.testsPassing/100,t.metrics.criticalBugs/10,t.metrics.codeSmells/50,t.metrics.securityVulnerabilities/10,t.metrics.technicalDebt/20,t.metrics.duplications/20]},i={type:"evaluate-gate",value:e.overallScore},n={...r},s=0;if(e.passed)s+=e.overallScore/100,e.overallScore>=90&&(s+=.5),e.overallScore>=95&&(s+=.5);else{s-=.5;let o=e.checks.filter(c=>!c.passed&&c.severity==="critical").length;s-=o*.2}let a={state:r,action:i,nextState:n,reward:Math.max(-1,Math.min(1,s)),done:!0};await u.train(a)}catch(r){gt.error("Actor-Critic training failed:",r instanceof Error?r:void 0)}}async function Ku(u,t,e,r){try{let i={id:`quality-state-${Date.now()}`,features:[t.metrics.coverage,t.metrics.testsPassing,t.metrics.criticalBugs,t.metrics.codeSmells,t.metrics.securityVulnerabilities,t.metrics.technicalDebt,t.metrics.duplications]},n={type:"quality-gate-evaluation",value:e.passed?1:0};u.createPattern(i,n,{reward:e.passed?e.overallScore/100:-.5,success:e.passed,quality:e.overallScore/100},"quality-assessment",r,{gateName:t.gateName,overallScore:e.overallScore,failedChecks:e.failedChecks})}catch(i){gt.error("Failed to store quality pattern in SONA:",i instanceof Error?i:void 0)}}async function Ju(u,t,e,r){try{let i={id:`quality-analysis-${Date.now()}`,features:[e.score.overall,e.score.coverage,e.score.complexity,e.score.maintainability,e.metrics.length,t.sourceFiles.length]},n={type:"quality-analysis",value:e.score.overall};u.createPattern(i,n,{reward:e.score.overall/100,success:e.score.overall>=70,quality:e.score.overall/100},"quality-assessment",r,{sourceFileCount:t.sourceFiles.length,recommendationCount:e.recommendations.length})}catch(i){gt.error("Failed to store quality analysis pattern in SONA:",i instanceof Error?i:void 0)}}async function Yu(u,t,e,r){try{let i={id:`similarity-search-${Date.now()}`,features:[u.score.overall,u.score.coverage,u.score.complexity,u.score.maintainability]},n=await e.adaptPattern(i,"quality-assessment",r);if(!n.success||!n.pattern)return null;let s=[];if(n.pattern.metadata){let a=n.pattern.metadata;a.similarIssues&&a.similarIssues.length>0&&s.push({type:"improvement",title:"Similar Quality Patterns Found",description:`Found ${n.similarity.toFixed(0)}% similar historical patterns: ${a.similarIssues.slice(0,3).join(", ")}`,impact:"medium",effort:"low"})}return{...u,recommendations:[...u.recommendations,...s]}}catch(i){return gt.error("Failed to enhance with similarity patterns:",i instanceof Error?i:void 0),null}}function Xu(u){let t=[],e={pattern_merge:.2,novel_association:.4,optimization:.6,gap_detection:.8};for(t.push(e[u.type]||.5),t.push(u.confidenceScore),t.push(u.noveltyScore),t.push(u.actionable?1:0),t.push(Math.min(1,u.sourceConcepts.length/10));t.length<384;)t.push(0);return t.slice(0,384)}M();A();function bs(u,t,e){let r=new Error(t);return r.code=u,r.claimId=e?.claimId,r.details=e?.details,r.retryable=e?.retryable??!1,r}var nc={defaultConfidenceThreshold:.8,defaultTimeout:3e4,reportQualityThreshold:.85,enableMultiModel:!0,maxParallelVerifications:5,enableStatistics:!0,statisticsPersistInterval:6e4},ws={"security-implementation":"code-trace","security-vulnerability":"code-trace","metric-count":"execution","pattern-implementation":"cross-file","coverage-claim":"execution"},Cs=["security-implementation","security-vulnerability"];import{readFile as dh,stat as sc}from"node:fs/promises";import{join as Zu}from"node:path";import mh from"fast-glob";var Ri=class{config;constructor(t){this.config={rootDir:t.rootDir,maxFileSize:t.maxFileSize??10*1024*1024,encoding:t.encoding??"utf-8",excludePatterns:t.excludePatterns??["node_modules/**",".git/**","dist/**"]}}async verify(t,e){let r=Date.now(),i=e?.checkAllInstances??!0;try{let n=this.extractFilePatterns(t),s=this.extractSearchPatterns(t),a=[],o=!1,c="",l=0,d=0;if(n.length>0){let h=await this.verifyFileExistence(n);a.push(...h.evidence),l+=h.total,d+=h.passed,h.passed===h.total?(o=!0,c=`All ${h.total} referenced files exist`):(o=!1,c=`${h.total-h.passed} of ${h.total} files not found`)}if(s.length>0){let h=await this.verifyContentPatterns(s,i,e?.maxInstances);a.push(...h.evidence),l+=h.total,d+=h.passed,h.passed>0?(o=!0,c=i?`Pattern found in all ${h.passed} instances`:`Pattern found in ${h.passed} of ${h.total} checked files`):(o=!1,c=`Pattern not found in any of ${h.total} checked files`)}if(n.length===0&&s.length===0){let h=await this.verifyExistingEvidence(t.evidence);a=h.evidence,o=h.verified,c=h.reasoning,l=h.total,d=h.passed}let m=Date.now()-r,g=this.calculateConfidence(d,l,o);return{claimId:t.id,verified:o,confidence:g,method:"cross-file",reasoning:c,allInstancesChecked:i,instancesChecked:l,instancesPassed:d,verificationTimeMs:m,verifiedAt:new Date,requiresHumanReview:g<.7,counterEvidence:o?void 0:a.filter(h=>!h.verified)}}catch(n){let s=Date.now()-r,a=n instanceof Error?n.message:"Unknown error";return{claimId:t.id,verified:!1,confidence:0,method:"cross-file",reasoning:`Verification failed: ${a}`,allInstancesChecked:!1,instancesChecked:0,instancesPassed:0,verificationTimeMs:s,verifiedAt:new Date,requiresHumanReview:!0}}}extractFilePatterns(t){let e=[];for(let n of t.evidence)if(n.type==="file-reference"||n.type==="code-snippet"){let s=n.location.split(":")[0];s&&!e.includes(s)&&e.push(s)}let r=/(?:src\/|tests\/|lib\/|app\/)[\w\-/.]+\.[\w]+/g,i=t.statement.match(r);return i&&e.push(...i.filter(n=>!e.includes(n))),e}extractSearchPatterns(t){let e=[],r=["parameterized queries","prepared statements","input validation","sanitization","csrf token","xss prevention"];for(let i of r)t.statement.toLowerCase().includes(i)&&e.push({pattern:i});return e}async verifyFileExistence(t){let e=[],r=0;for(let i of t){let n=Zu(this.config.rootDir,i);try{let s=await sc(n),a=s.isFile();e.push({type:"file-reference",location:i,content:a?`File exists (${s.size} bytes)`:"File not found",verified:a,timestamp:new Date}),a&&r++}catch(s){e.push({type:"file-reference",location:i,content:`File not accessible: ${s instanceof Error?s.message:"Unknown error"}`,verified:!1,timestamp:new Date})}}return{evidence:e,total:t.length,passed:r}}async verifyContentPatterns(t,e,r){let i=[],n=0,s=0;for(let{pattern:a,fileGlob:o}of t){let l=await mh(o??"**/*.{ts,js,tsx,jsx}",{cwd:this.config.rootDir,ignore:this.config.excludePatterns,absolute:!0}),d=r&&!e?l.slice(0,r):l;n+=d.length;for(let m of d){let g=await this.searchFileForPattern(m,a);if(g.matches.length>0){s++;for(let h of g.matches)i.push({type:"code-snippet",location:`${g.filePath}:${h.line}`,content:h.content,verified:!0,timestamp:new Date,contentHash:Ti(h.content)})}}}return{evidence:i,total:n,passed:s}}async searchFileForPattern(t,e){try{if((await sc(t)).size>this.config.maxFileSize)return{filePath:t,matches:[]};let n=(await dh(t,this.config.encoding)).split(`
2713
2714
  `),s=[],a=e.toLowerCase();for(let o=0;o<n.length;o++)n[o].toLowerCase().includes(a)&&s.push({line:o+1,content:n[o].trim()});return{filePath:t,matches:s}}catch{return{filePath:t,matches:[]}}}async verifyExistingEvidence(t){let e=[],r=0;for(let s of t)if(s.type==="file-reference"||s.type==="code-snippet"){let a=s.location.split(":")[0],o=Zu(this.config.rootDir,a);try{let l=(await sc(o)).isFile();e.push({...s,verified:l,timestamp:new Date}),l&&r++}catch{e.push({...s,verified:!1,timestamp:new Date})}}else e.push(s);let i=r===t.length&&r>0,n=i?`All ${r} evidence items verified`:`${r} of ${t.length} evidence items verified`;return{evidence:e,verified:i,reasoning:n,total:t.length,passed:r}}calculateConfidence(t,e,r){if(e===0)return 0;let i=t/e;return r&&i===1?1:i>=.9?.9:i>=.75?.75:i>=.5?.6:.3}};H();import{execFile as ph}from"node:child_process";import{promisify as gh}from"node:util";import{readFile as hh}from"node:fs/promises";import{join as fh}from"node:path";var yh=gh(ph),ed=new Map([["npm test",{bin:"npm",args:["test"]}],["npm run test",{bin:"npm",args:["run","test"]}],["npm run test:unit",{bin:"npm",args:["run","test:unit"]}],["npm run test:unit:fast",{bin:"npm",args:["run","test:unit:fast"]}],["npm run test:ci",{bin:"npm",args:["run","test:ci"]}],["npm run test:coverage",{bin:"npm",args:["run","test:coverage"]}],["npm run test:e2e",{bin:"npm",args:["run","test:e2e"]}],["npm run test:safe",{bin:"npm",args:["run","test:safe"]}]]),Ai=class{config;constructor(t){this.config={rootDir:t.rootDir,testCommand:t.testCommand??"npm test",coverageCommand:t.coverageCommand??"npm run test:coverage",coverageReportPath:t.coverageReportPath??"coverage/coverage-summary.json",timeout:t.timeout??6e4}}async verify(t,e){let r=Date.now();try{let i=this.classifyTestClaim(t),n=[],s=!1,a="",o=0;switch(i){case"test-count":let l=await this.verifyTestCount(t);n=l.evidence,s=l.verified,a=l.reasoning,o=l.confidence;break;case"test-results":let d=await this.verifyTestExecution(t);n=d.evidence,s=d.verified,a=d.reasoning,o=d.confidence;break;case"coverage":let m=await this.verifyCoverage(t);n=m.evidence,s=m.verified,a=m.reasoning,o=m.confidence;break;default:let g=await this.verifyExistingEvidence(t.evidence);n=g.evidence,s=g.verified,a=g.reasoning,o=g.confidence}let c=Date.now()-r;return{claimId:t.id,verified:s,confidence:o,method:"execution",reasoning:a,allInstancesChecked:!0,instancesChecked:1,instancesPassed:s?1:0,verificationTimeMs:c,verifiedAt:new Date,requiresHumanReview:o<.8}}catch(i){let n=Date.now()-r,s=i instanceof Error?i.message:"Unknown error";return{claimId:t.id,verified:!1,confidence:0,method:"execution",reasoning:`Verification failed: ${s}`,allInstancesChecked:!1,instancesChecked:0,instancesPassed:0,verificationTimeMs:n,verifiedAt:new Date,requiresHumanReview:!0}}}classifyTestClaim(t){let e=t.statement.toLowerCase();return e.includes("coverage")||e.includes("%")||e.includes("percent")?"coverage":e.includes("test")&&(e.includes("pass")||e.includes("fail"))?"test-results":e.includes("test")&&/\d+/.test(e)?"test-count":"unknown"}async verifyTestCount(t){try{let e=await this.runTests(),r=this.extractNumber(t.statement),i=[{type:"test-result",location:"test-execution",content:`Total tests: ${e.total}, Passed: ${e.passed}, Failed: ${e.failed}`,verified:!0,timestamp:new Date,context:{total:e.total,passed:e.passed,failed:e.failed,skipped:e.skipped}},{type:"command-output",location:this.config.testCommand,content:e.rawOutput,verified:!0,timestamp:new Date}],n=r!==null&&e.total>=r,s=n?`Claimed ${r} tests, found ${e.total} tests`:r===null?"Could not extract test count from claim":`Claimed ${r} tests, but only ${e.total} exist`;return{evidence:i,verified:n,reasoning:s,confidence:n?.95:.3}}catch(e){let r=e instanceof Error?e.message:"Unknown error";return{evidence:[{type:"command-output",location:this.config.testCommand,content:`Test execution failed: ${r}`,verified:!1,timestamp:new Date}],verified:!1,reasoning:`Failed to run tests: ${r}`,confidence:0}}}async verifyTestExecution(t){try{let e=await this.runTests(),r=[{type:"test-result",location:"test-execution",content:`Tests passed: ${e.passed}/${e.total}`,verified:e.failed===0,timestamp:new Date,context:{total:e.total,passed:e.passed,failed:e.failed}},{type:"command-output",location:this.config.testCommand,content:e.rawOutput,verified:!0,timestamp:new Date}],i=e.failed===0&&e.total>0,n=t.statement.toLowerCase().includes("pass")?i:!i,s=i?`All ${e.total} tests passed`:`${e.failed} of ${e.total} tests failed`,a=e.total>0?.95:.3;return{evidence:r,verified:n,reasoning:s,confidence:a}}catch(e){let r=e instanceof Error?e.message:"Unknown error";return{evidence:[{type:"command-output",location:this.config.testCommand,content:`Test execution failed: ${r}`,verified:!1,timestamp:new Date}],verified:!1,reasoning:`Failed to run tests: ${r}`,confidence:0}}}async verifyCoverage(t){try{let e=await this.getCoverageData(),r=this.extractPercentage(t.statement),i=[{type:"coverage-data",location:this.config.coverageReportPath,content:`Lines: ${e.lines}%, Statements: ${e.statements}%, Functions: ${e.functions}%, Branches: ${e.branches}%`,verified:!0,timestamp:new Date,context:e.rawData}],n=e.lines,s=r!==null&&n>=r,a=s?`Claimed ${r}% coverage, actual coverage is ${n}%`:r===null?"Could not extract coverage percentage from claim":`Claimed ${r}% coverage, but actual is only ${n}%`;return{evidence:i,verified:s,reasoning:a,confidence:s?.95:.3}}catch(e){let r=e instanceof Error?e.message:"Unknown error";return{evidence:[{type:"coverage-data",location:this.config.coverageReportPath,content:`Coverage data unavailable: ${r}`,verified:!1,timestamp:new Date}],verified:!1,reasoning:`Failed to get coverage data: ${r}`,confidence:0}}}async runTests(){let t=ed.get(this.config.testCommand);if(!t)throw new Error(`Test command not in allowlist: "${this.config.testCommand}". Allowed: ${[...ed.keys()].join(", ")}`);let{stdout:e,stderr:r}=await yh(t.bin,[...t.args],{cwd:this.config.rootDir,timeout:this.config.timeout}),i=e+r;return{...this.parseTestOutput(i),rawOutput:i}}parseTestOutput(t){let e=t.match(/(\d+) passed(?:\s+\|\s+(\d+) failed)?/);if(e){let r=parseInt(e[1],10),i=e[2]?parseInt(e[2],10):0;return{total:r+i,passed:r,failed:i}}return e=t.match(/Tests:\s+(\d+) failed.*?(\d+) passed.*?(\d+) total/),e?{total:parseInt(e[3],10),passed:parseInt(e[2],10),failed:parseInt(e[1],10)}:{total:0,passed:0,failed:0}}async getCoverageData(){let t=fh(this.config.rootDir,this.config.coverageReportPath),e=await hh(t,"utf-8"),r=E(e),i=r.total||r;return{lines:i.lines?.pct??0,statements:i.statements?.pct??0,functions:i.functions?.pct??0,branches:i.branches?.pct??0,rawData:r}}async verifyExistingEvidence(t){let e=t.filter(i=>i.type==="test-result"||i.type==="coverage-data");if(e.length===0)return{evidence:[],verified:!1,reasoning:"No test or coverage evidence provided",confidence:0};let r=e.every(i=>i.verified);return{evidence:e,verified:r,reasoning:r?`All ${e.length} evidence items verified`:"Some evidence items failed verification",confidence:r?.8:.3}}extractNumber(t){let e=t.match(/\d+/);return e?parseInt(e[0],10):null}extractPercentage(t){let e=t.match(/(\d+)%/);return e?parseInt(e[1],10):null}};import{execFile as vh}from"node:child_process";import{promisify as bh}from"node:util";var wh=bh(vh),td=new Map([["npm run build",{bin:"npm",args:["run","build"]}],["npm run lint",{bin:"npm",args:["run","lint"]}],["npm test",{bin:"npm",args:["test"]}],["npm run typecheck",{bin:"npm",args:["run","typecheck"]}],["npm run test:unit",{bin:"npm",args:["run","test:unit"]}],["npm run test:ci",{bin:"npm",args:["run","test:ci"]}]]),Ei=class{config;patterns={build:[{pattern:/build successful/i,type:"success",location:"stdout"},{pattern:/compiled successfully/i,type:"success",location:"stdout"},{pattern:/done in/i,type:"success",location:"stdout"},{pattern:/error/i,type:"error",location:"stderr"},{pattern:/failed/i,type:"error",location:"both"},{pattern:/warning/i,type:"warning",location:"both"}],lint:[{pattern:/no problems found/i,type:"success",location:"stdout"},{pattern:/✔.*\d+ problems?/i,type:"success",location:"stdout"},{pattern:/✖.*\d+ problems?/i,type:"error",location:"stdout"},{pattern:/error/i,type:"error",location:"both"}]};constructor(t){this.config={rootDir:t.rootDir,timeout:t.timeout??6e4,maxOutputSize:t.maxOutputSize??1024*1024,env:t.env??{}}}async verify(t,e){let r=Date.now();try{let i=this.extractCommand(t);if(!i){let c=await this.verifyExistingEvidence(t.evidence),l=Date.now()-r;return{claimId:t.id,verified:c.verified,confidence:c.confidence,method:"execution",reasoning:c.reasoning,allInstancesChecked:!0,instancesChecked:c.evidence.length,instancesPassed:c.verified?c.evidence.length:0,verificationTimeMs:l,verifiedAt:new Date,requiresHumanReview:c.confidence<.7}}let n=await this.executeCommand(i),s=this.createEvidence(i,n),a=this.analyzeOutput(t,n),o=Date.now()-r;return{claimId:t.id,verified:a.verified,confidence:a.confidence,method:"execution",reasoning:a.reasoning,allInstancesChecked:!0,instancesChecked:1,instancesPassed:a.verified?1:0,verificationTimeMs:o,verifiedAt:new Date,requiresHumanReview:a.confidence<.8,counterEvidence:a.verified?void 0:s}}catch(i){let n=Date.now()-r,s=i instanceof Error?i.message:"Unknown error";return{claimId:t.id,verified:!1,confidence:0,method:"execution",reasoning:`Verification failed: ${s}`,allInstancesChecked:!1,instancesChecked:0,instancesPassed:0,verificationTimeMs:n,verifiedAt:new Date,requiresHumanReview:!0}}}extractCommand(t){for(let i of t.evidence)if(i.type==="command-output"&&i.location)return i.location;let e=t.statement.toLowerCase();if(e.includes("build"))return"npm run build";if(e.includes("lint"))return"npm run lint";if(e.includes("test"))return"npm test";if(e.includes("typecheck")||e.includes("type check"))return"npm run typecheck";let r=e.match(/`([^`]+)`|"([^"]+)"/);return r?r[1]||r[2]:null}async executeCommand(t){let e=Date.now(),r=td.get(t);if(!r)throw new Error(`Command not in allowlist: "${t}". Allowed: ${[...td.keys()].join(", ")}`);try{let{stdout:i,stderr:n}=await wh(r.bin,[...r.args],{cwd:this.config.rootDir,timeout:this.config.timeout,maxBuffer:this.config.maxOutputSize,env:{...process.env,...this.config.env}}),s=Date.now()-e;return{stdout:this.truncateOutput(i),stderr:this.truncateOutput(n),exitCode:0,duration:s,success:!0}}catch(i){let n=Date.now()-e;if(i&&typeof i=="object"&&"stdout"in i&&"stderr"in i){let s=i;return{stdout:this.truncateOutput(s.stdout||""),stderr:this.truncateOutput(s.stderr||""),exitCode:s.code??1,duration:n,success:!1}}throw i}}createEvidence(t,e){let r=[];return e.stdout&&r.push({type:"command-output",location:t,content:e.stdout,verified:e.success,timestamp:new Date,contentHash:Ti(e.stdout),context:{stream:"stdout",exitCode:e.exitCode,duration:e.duration}}),e.stderr&&r.push({type:"command-output",location:t,content:e.stderr,verified:e.success,timestamp:new Date,contentHash:Ti(e.stderr),context:{stream:"stderr",exitCode:e.exitCode,duration:e.duration}}),r}analyzeOutput(t,e){let r=t.statement.toLowerCase(),i=this.inferCommandType(r),n=i?this.patterns[i]:[],s=!1,a=!1,o=!1;for(let h of n){let b=h.location==="both"?e.stdout+e.stderr:h.location==="stdout"?e.stdout:e.stderr;(typeof h.pattern=="string"?new RegExp(h.pattern,"i"):h.pattern).test(b)&&(h.type==="success"&&(s=!0),h.type==="error"&&(a=!0),h.type==="warning"&&(o=!0))}let c=r.includes("success")||r.includes("pass")||r.includes("complete"),l=r.includes("fail")||r.includes("error"),d,m,g;return c?(d=e.success&&s&&!a,m=d?.95:o?.7:.3,g=d?"Command executed successfully with expected output":e.success?"Command succeeded but output patterns do not match":"Command failed with exit code "+e.exitCode):l?(d=!e.success||a,m=d?.95:.3,g=d?"Command failed as claimed":"Command succeeded, contradicting the claim"):(d=e.exitCode===0,m=.8,g=d?"Command completed successfully":"Command exited with error code "+e.exitCode),{verified:d,confidence:m,reasoning:g}}inferCommandType(t){return t.includes("build")?"build":t.includes("lint")?"lint":null}async verifyExistingEvidence(t){let e=t.filter(o=>o.type==="command-output");if(e.length===0)return{evidence:[],verified:!1,reasoning:"No command output evidence provided",confidence:0};let r=e.some(o=>/error|failed/i.test(o.content)),n=e.some(o=>/success|passed|done/i.test(o.content))&&!r,s=n?.8:.3,a=n?`Found ${e.length} evidence items indicating success`:r?"Evidence contains error indicators":"Evidence does not indicate success";return{evidence:e,verified:n,reasoning:a,confidence:s}}truncateOutput(t){return t.length<=this.config.maxOutputSize?t:t.substring(0,this.config.maxOutputSize)+`
2714
2715
 
2715
2716
  ... [output truncated]`}};var Ss=class{config;fileVerifier;testVerifier;outputVerifier;history=[];constructor(t){this.config={...nc,...t.verifier},this.fileVerifier=new Ri({rootDir:t.rootDir,...t.fileVerifier}),this.testVerifier=new Ai({rootDir:t.rootDir,...t.testVerifier}),this.outputVerifier=new Ei({rootDir:t.rootDir,...t.outputVerifier})}async verify(t,e){try{let r={confidenceThreshold:this.config.defaultConfidenceThreshold,timeout:this.config.defaultTimeout,checkAllInstances:this.requiresStrictVerification(t.type),collectCounterEvidence:!0,useMultiModel:this.config.enableMultiModel&&this.isSecurityClaim(t.type),...e},i=this.selectVerificationMethod(t,r),n=await this.executeVerification(t,i,r);return this.config.enableStatistics&&this.recordVerification(t,n),{success:!0,value:n}}catch(r){return{success:!1,error:this.handleError(r,t.id)}}}async verifyReport(t,e){try{let r={confidenceThreshold:this.config.defaultConfidenceThreshold,qualityThreshold:this.config.reportQualityThreshold,timeout:this.config.defaultTimeout,parallelLimit:this.config.maxParallelVerifications,failFast:!1,verificationOrder:"severity",...e},i=this.sortClaimsByPriority(t.claims,r.verificationOrder),n=[],s=[];for(let d=0;d<i.length;d+=r.parallelLimit){let m=i.slice(d,d+r.parallelLimit),g=await Promise.all(m.map(h=>this.verify(h,r)));for(let h of g){if(!h.success){if(r.failFast)throw h.error;continue}n.push(h.value);let b=this.checkIfFlagged(m.find(w=>w.id===h.value.claimId),h.value,r);b&&s.push(b)}}let a=this.calculateSummary(n),o=a.averageConfidence,c=o>=r.qualityThreshold&&s.filter(d=>d.priority==="urgent").length===0;return{success:!0,value:{reportId:t.id,report:t,claims:t.claims,results:n,overallConfidence:o,flaggedClaims:s,summary:a,verifiedAt:new Date,passed:c,qualityThreshold:r.qualityThreshold}}}catch(r){return{success:!1,error:this.handleError(r,t.id)}}}async verifyBatch(t,e){try{let r=await Promise.all(t.map(s=>this.verify(s,e))),i=r.filter(s=>s.success).map(s=>s.value),n=r.filter(s=>!s.success);return n.length>0?{success:!1,error:n[0].error}:{success:!0,value:i}}catch(r){return{success:!1,error:this.handleError(r)}}}getStats(){let t=new Date;return{totalClaims:this.history.length,verified:this.history.filter(r=>r.result.verified).length,rejected:this.history.filter(r=>!r.result.verified).length,disputed:this.history.filter(r=>r.result.confidence<.5).length,avgConfidence:this.calculateAverageConfidence(this.history),byType:this.calculateTypeStats(),byMethod:this.calculateMethodStats(),bySourceAgent:this.calculateAgentStats(),lastUpdated:t,timeWindow:{start:this.history[0]?.timestamp??t,end:t}}}resetStats(){this.history.length=0}requiresStrictVerification(t){return Cs.includes(t)}getRecommendedMethod(t){return ws[t]}selectVerificationMethod(t,e){return e.preferredMethods&&e.preferredMethods.length>0?e.preferredMethods[0]:this.getRecommendedMethod(t.type)}async executeVerification(t,e,r){switch(e){case"cross-file":return this.fileVerifier.verify(t,r);case"execution":return t.type==="coverage-claim"||t.statement.toLowerCase().includes("test")?this.testVerifier.verify(t,r):this.outputVerifier.verify(t,r);case"code-trace":return this.fileVerifier.verify(t,r);case"static-analysis":return this.fileVerifier.verify(t,r);case"multi-model":let i=this.getRecommendedMethod(t.type);return this.executeVerification(t,i,r);default:throw bs("METHOD_NOT_AVAILABLE",`Verification method '${e}' is not available`,{retryable:!1})}}isSecurityClaim(t){return t==="security-implementation"||t==="security-vulnerability"}sortClaimsByPriority(t,e="severity"){return e==="sequential"?[...t]:[...t].sort((r,i)=>{if(e==="severity"){let s=["critical","high","medium","low"];return s.indexOf(r.severity)-s.indexOf(i.severity)}let n=["security-vulnerability","security-implementation","coverage-claim","pattern-implementation","metric-count"];return n.indexOf(r.type)-n.indexOf(i.type)})}checkIfFlagged(t,e,r){if(e.verified&&e.confidence>=r.confidenceThreshold)return null;let i;e.verified?e.confidence<r.confidenceThreshold?i="low-confidence":!e.allInstancesChecked&&this.requiresStrictVerification(t.type)?i="partial-verification":i="verification-failed":i="verification-failed";let n;e.verified?e.confidence<.5?n="human-review-required":e.confidence<r.confidenceThreshold?n="add-disclaimer":n="re-verify":n="remove-from-report";let s;return this.isSecurityClaim(t.type)&&!e.verified?s="urgent":t.severity==="critical"?s="high":t.severity==="high"?s="medium":s="low",{claim:t,result:e,reason:i,recommendedAction:n,priority:s}}calculateSummary(t){let e={"security-implementation":{total:0,verified:0,rejected:0,avgConfidence:0},"security-vulnerability":{total:0,verified:0,rejected:0,avgConfidence:0},"metric-count":{total:0,verified:0,rejected:0,avgConfidence:0},"pattern-implementation":{total:0,verified:0,rejected:0,avgConfidence:0},"coverage-claim":{total:0,verified:0,rejected:0,avgConfidence:0}},r={"code-trace":0,execution:0,"cross-file":0,"multi-model":0,"static-analysis":0},i=0,n=0;for(let s of t)r[s.method]++,i+=s.verificationTimeMs??0,n+=s.confidence;return{totalClaims:t.length,verified:t.filter(s=>s.verified).length,rejected:t.filter(s=>!s.verified).length,disputed:t.filter(s=>s.confidence<.5).length,requiresReview:t.filter(s=>s.requiresHumanReview).length,averageConfidence:t.length>0?n/t.length:0,totalTimeMs:i,byType:e,byMethod:r}}recordVerification(t,e){this.history.push({claimId:t.id,claimType:t.type,method:e.method,result:e,timestamp:new Date})}calculateAverageConfidence(t){return t.length===0?0:t.reduce((r,i)=>r+i.result.confidence,0)/t.length}calculateTypeStats(){let t={"security-implementation":this.createEmptyTypeStats(),"security-vulnerability":this.createEmptyTypeStats(),"metric-count":this.createEmptyTypeStats(),"pattern-implementation":this.createEmptyTypeStats(),"coverage-claim":this.createEmptyTypeStats()};for(let e of this.history){let r=t[e.claimType];r.total++,e.result.verified?r.verified++:r.rejected++}for(let e of Object.keys(t)){let r=this.history.filter(i=>i.claimType===e);t[e].avgConfidence=this.calculateAverageConfidence(r),t[e].avgVerificationTimeMs=r.length>0?r.reduce((i,n)=>i+(n.result.verificationTimeMs??0),0)/r.length:0}return t}calculateMethodStats(){let t={"code-trace":this.createEmptyMethodStats(),execution:this.createEmptyMethodStats(),"cross-file":this.createEmptyMethodStats(),"multi-model":this.createEmptyMethodStats(),"static-analysis":this.createEmptyMethodStats()};for(let e of this.history){let r=t[e.method];r.timesUsed++}for(let e of Object.keys(t)){let r=this.history.filter(i=>i.method===e);r.length>0&&(t[e].successRate=r.filter(i=>i.result.verified).length/r.length,t[e].avgConfidence=this.calculateAverageConfidence(r),t[e].avgTimeMs=r.reduce((i,n)=>i+(n.result.verificationTimeMs??0),0)/r.length)}return t}calculateAgentStats(){let t={};for(let e of this.history){let r=e.claimId.split("-")[0];t[r]||(t[r]={claimsSubmitted:0,claimsVerified:0,claimsRejected:0,verificationRate:0,avgConfidence:0}),t[r].claimsSubmitted++,e.result.verified?t[r].claimsVerified++:t[r].claimsRejected++}for(let e of Object.keys(t)){let r=this.history.filter(i=>i.claimId.startsWith(e));t[e].verificationRate=t[e].claimsVerified/t[e].claimsSubmitted,t[e].avgConfidence=this.calculateAverageConfidence(r)}return t}createEmptyTypeStats(){return{total:0,verified:0,rejected:0,disputed:0,avgConfidence:0,avgVerificationTimeMs:0}}createEmptyMethodStats(){return{timesUsed:0,successRate:0,avgConfidence:0,avgTimeMs:0}}handleError(t,e){if(t&&typeof t=="object"&&"code"in t)return t;let r=t instanceof Error?t.message:"Unknown verification error";return bs("INTERNAL_ERROR",r,{claimId:e,retryable:!1})}};function ac(u){return new Ss(u)}function Ti(u){let t=0;for(let e=0;e<u.length;e++){let r=u.charCodeAt(e);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(16).padStart(8,"0")}var Rs=R.create("quality-assessment/claim-verifier");async function rd(u){try{let t=u||process.cwd();return ac({rootDir:t,verifier:{enableStatistics:!0,enableMultiModel:!1,defaultConfidenceThreshold:.7}})}catch(t){throw new Error(`Failed to initialize ClaimVerifier: ${T(t)}`)}}async function id(u,t){try{let e=Ch(u,"quality-analysis");if(e.claims.length===0)return u;let r=await t.verifyReport(e);return r.success?{...u,claimVerification:{verified:r.value.passed,confidence:r.value.overallConfidence,unverifiedClaims:r.value.flaggedClaims.length}}:(Rs.warn("Claim verification failed:"),u)}catch(e){return Rs.error("Failed to verify report claims:",e instanceof Error?e:void 0),u}}async function nd(u,t){try{let e=Sh(u);if(e.claims.length===0)return u;let r=await t.verifyReport(e);return r.success?{...u,claimVerification:{verified:r.value.passed,confidence:r.value.overallConfidence,unverifiedClaims:r.value.flaggedClaims.length}}:(Rs.warn("Gate claim verification failed:"),u)}catch(e){return Rs.error("Failed to verify gate claims:",e instanceof Error?e:void 0),u}}function Ch(u,t){let e=[];for(let r of u.metrics)e.push({id:`metric-${r.name}-${Date.now()}`,type:"metric-count",statement:`Metric ${r.name} = ${r.value}`,evidence:[],sourceAgent:"quality-analyzer",sourceAgentType:"analyzer",severity:r.value<50?"high":r.value<70?"medium":"low",timestamp:new Date,metadata:{name:r.name,value:r.value}});return u.score.coverage<80&&e.push({id:`coverage-${Date.now()}`,type:"coverage-claim",statement:`Code coverage is ${u.score.coverage}%`,evidence:[],sourceAgent:"quality-analyzer",sourceAgentType:"analyzer",severity:u.score.coverage<50?"critical":"high",timestamp:new Date,metadata:{coverage:u.score.coverage}}),{id:`quality-report-${Date.now()}`,type:t,claims:e,generatedAt:new Date,sourceAgent:"quality-assessment-coordinator"}}function Sh(u){let t=[];for(let e of u.checks)t.push({id:`gate-check-${e.name}-${Date.now()}`,type:"metric-count",statement:`Gate check '${e.name}': ${e.value} (threshold: ${e.threshold})`,evidence:[],sourceAgent:"quality-gate",sourceAgentType:"validator",severity:e.passed?"low":e.severity||"medium",timestamp:new Date,metadata:{checkName:e.name,value:e.value,threshold:e.threshold,passed:e.passed}});return{id:`gate-result-${Date.now()}`,type:"gate-evaluation",claims:t,generatedAt:new Date,sourceAgent:"quality-assessment-coordinator"}}M();var Lt=R.create("quality-assessment/gate-evaluation");function sd(u,t,e,r){let i=r,n=[{metricKey:"coverage",thresholdKey:"coverage",isMin:!0},{metricKey:"testsPassing",thresholdKey:"testsPassing",isMin:!0},{metricKey:"criticalBugs",thresholdKey:"criticalBugs",isMin:!1},{metricKey:"codeSmells",thresholdKey:"codeSmells",isMin:!1},{metricKey:"securityVulnerabilities",thresholdKey:"securityVulnerabilities",isMin:!1},{metricKey:"technicalDebt",thresholdKey:"technicalDebt",isMin:!1},{metricKey:"duplications",thresholdKey:"duplications",isMin:!1}];for(let{metricKey:s,thresholdKey:a,isMin:o}of n){let c=u[s],l=t[a];if(l===void 0)continue;let d=o?l.min:l.max;if(d===void 0||d===0)continue;let m=Math.abs(c-d)/d;if(m<i)return Lt.info(`Borderline detected: ${s}=${c} (threshold=${d}, distance=${(m*100).toFixed(1)}%)`),!0}return!1}async function ad(u,t,e){let r=V({id:`gate-verdict-${v()}`,type:"gate-verdict",confidence:t.overallScore/100,description:`Quality gate '${u.gateName}' verdict: ${t.passed?"PASSED":"FAILED"} (borderline case)`,payload:{metrics:u.metrics,thresholds:u.thresholds,initialResult:t},detectedBy:"quality-assessment-coordinator",severity:t.passed?"medium":"high"});if(!e.requiresConsensus(r))return null;try{let i=await e.verifyFinding(r);if(!i.success)return Lt.warn("Consensus verification failed:"),null;let n=i.value;return Lt.info(`[quality-assessment] Consensus for gate '${u.gateName}': verdict=${n.verdict}, confidence=${(n.confidence*100).toFixed(1)}%`),{...t,consensusVerified:!0,consensusConfidence:n.confidence,consensusVerdict:n.verdict}}catch(i){return Lt.error("Consensus verification error:",i instanceof Error?i:void 0),null}}function od(u,t){return t.decision==="blocked"||t.decision==="warning"&&u.riskTolerance==="low"||t.riskScore>.7}async function cd(u,t,e){let r=V({id:`release-readiness-${v()}`,type:"release-readiness",confidence:t.confidence,description:`Release readiness for '${u.releaseCandidate}': ${t.decision} (risk: ${(t.riskScore*100).toFixed(0)}%)`,payload:{request:u,initialAdvice:t},detectedBy:"quality-assessment-coordinator",severity:t.decision==="blocked"?"critical":"high"});if(!e.requiresConsensus(r))return null;try{let i=await e.verifyFinding(r);if(!i.success)return Lt.warn("Consensus verification for deployment failed:"),null;let n=i.value;return Lt.info(`[quality-assessment] Consensus for deployment '${u.releaseCandidate}': verdict=${n.verdict}, confidence=${(n.confidence*100).toFixed(1)}%`),{...t,consensusVerified:!0,consensusConfidence:n.confidence,consensusVerdict:n.verdict}}catch(i){return Lt.error("Consensus verification error:",i instanceof Error?i:void 0),null}}var oc={enabled:!1,consecutivePassesRequired:5,ratchetIncrementPercent:2,maxThreshold:95,monotonic:!0,cooldownMs:10080*60*1e3};function cc(u,t,e,r=Date.now()){if(process.env.AQE_GATE_RATCHETING_ENABLED!=="true"||!t.enabled)return e;let i={currentThreshold:e.currentThreshold,consecutivePasses:e.consecutivePasses,lastRatchetTime:e.lastRatchetTime,history:[...e.history]};if(!u)return i.consecutivePasses=0,i;i.consecutivePasses=i.consecutivePasses+1;let n=i.consecutivePasses>=t.consecutivePassesRequired,s=r-i.lastRatchetTime>=t.cooldownMs;if(n&&s){let a=i.currentThreshold+t.ratchetIncrementPercent,o=Math.min(a,t.maxThreshold),c=Math.max(o,i.currentThreshold);c>i.currentThreshold&&(i.currentThreshold=c,i.lastRatchetTime=r,i.history.push({threshold:c,ratchetedAt:r})),i.consecutivePasses=0}return i}qe();var Ah={maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableAutoGating:!1,enableRLThresholdTuning:!0,enableSONAPatternLearning:!0,enableFlashAttention:!0,enableClaimVerification:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2,borderlineMargin:.05},ue=R.create("quality-assessment"),xi=class extends Q{constructor(e,r,i,n={}){let s={...Ah,...n};super(e,"quality-assessment",s,{verifyFindingTypes:["gate-verdict","tech-debt-classification","release-readiness","risk-scoring"]});this.memory=r;this.agentCoordinator=i;this.qualityGate=new pt(r),this.qualityAnalyzer=new Ye(r),this.deploymentAdvisor=new Ft(r)}memory;agentCoordinator;qualityGate;qualityAnalyzer;deploymentAdvisor;actorCritic;qesona;flashAttention;claimVerifier;domain="quality-assessment";recentDreamInsights=[];ratchetState={currentThreshold:70,consecutivePasses:0,lastRatchetTime:0,history:[]};async onInitialize(){try{this.subscribeToEvents(),await this.loadWorkflowState(),await this.loadRatchetState(),this.config.enableRLThresholdTuning&&await this.initializeActorCritic(),this.config.enableSONAPatternLearning&&await this.initializeQESONA(),this.config.enableFlashAttention&&await this.initializeFlashAttention(),this.config.enableClaimVerification&&await this.initializeClaimVerifier()}catch(e){let r=`Failed to initialize quality-assessment coordinator: ${T(e)}`;throw new Error(r)}}async onDispose(){await this.saveWorkflowState(),this.flashAttention?.dispose(),this.qesona&&(await this.qesona.close(),this.qesona=void 0)}getActiveWorkflows(){return super.getActiveWorkflows()}getHealthyRoutingDomains(){return this.minCutMixin.getHealthyRoutingDomains()}async evaluateGate(e){let r=v();try{if(this.startWorkflow(r,"gate-evaluation"),this.minCutMixin.shouldPauseOperations())return ue.warn("Quality gate evaluation paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Quality gate evaluation paused: topology is in critical state"));this.isTopologyHealthy()||ue.warn("Topology degraded - applying stricter thresholds for quality gate");let i=await this.spawnQualityGateAgent(r,e);i.success&&this.addAgentToWorkflow(r,i.value);let n=e;if(this.config.enableRLThresholdTuning&&this.actorCritic){let c=await this.tuneThresholdsWithRL(e.metrics);c&&(n={...e,thresholds:c.thresholds})}let s=await this.qualityGate.evaluateGate(n);if(i.success&&await this.agentCoordinator.stop(i.value),!s.success)return this.failWorkflow(r,"Evaluation failed"),s;let a=s.value;if(this.config.enableConsensus&&this.isBorderlineGateResult(e.metrics,e.thresholds,s.value)){let c=await this.verifyGateVerdictWithConsensus(n,s.value);c&&(a=c)}if(this.completeWorkflow(r),wt()&&this.qesona?.isThreeLoopEnabled()){let c=n.metrics;this.qesona.instantAdapt([c.coverage/100,c.testsPassing/100,c.criticalBugs/10,c.codeSmells/100,c.securityVulnerabilities/10,c.technicalDebt/100,c.duplications/100,a.overallScore/100]);try{if(this.qesona.recordOutcome(a.overallScore/100),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableSONAPatternLearning&&this.qesona&&await this.storeQualityPattern(n,a),this.config.enableRLThresholdTuning&&this.actorCritic&&await this.trainActorCritic(n,a);try{(await vl()).append(a.passed?"QUALITY_GATE_PASS":"QUALITY_GATE_FAIL",{gateName:e.gateName,passed:a.passed,score:a.overallScore,failedChecks:a.failedChecks},"quality-gate")}catch{}if(process.env.AQE_GATE_RATCHETING_ENABLED==="true")try{let c=this.ratchetState.currentThreshold;this.ratchetState=cc(a.passed,oc,this.ratchetState),this.ratchetState.currentThreshold>c&&(ue.info(`Gate threshold ratcheted: ${c} -> ${this.ratchetState.currentThreshold}`),await this.saveRatchetState())}catch(c){ue.warn("Gate ratcheting failed (non-critical)",{error:c instanceof Error?c.message:String(c)})}this.config.publishEvents&&await this.publishQualityGateEvaluated(a);let o=await this.verifyGateResultClaims(a);return f(o)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}isBorderlineGateResult(e,r,i){return sd(e,r,i,this.config.borderlineMargin)}async verifyGateVerdictWithConsensus(e,r){return ad(e,r,this.consensusMixin)}async analyzeQuality(e){let r=v();try{if(this.startWorkflow(r,"quality-analysis"),this.minCutMixin.shouldPauseOperations())return ue.warn("Quality analysis paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Quality analysis paused: topology is in critical state"));this.isTopologyHealthy()||ue.warn("Topology degraded during quality analysis");let n=await this.spawnQualityAnalyzerAgent(r,e);n.success&&this.addAgentToWorkflow(r,n.value);let s=await this.qualityAnalyzer.analyzeQuality(e);if(n.success&&await this.agentCoordinator.stop(n.value),!s.success)return this.failWorkflow(r,"Evaluation failed"),s;if(this.completeWorkflow(r),this.config.enableFlashAttention&&this.flashAttention&&s.value.metrics.length>0){let o=await this.enhanceWithSimilarityPatterns(s.value);o&&(s.value=o)}if(wt()&&this.qesona?.isThreeLoopEnabled()){let o=s.value.score;this.qesona.instantAdapt([o.overall/100,s.value.metrics.length/20,s.value.trends.length/10,s.value.recommendations.length/10]);try{if(this.qesona.recordOutcome(o.overall/100),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableSONAPatternLearning&&this.qesona&&await this.storeQualityAnalysisPattern(e,s.value),this.config.enableAutoGating&&s.value.score.overall<70&&await this.memory.set(`quality-assessment:auto-gate:${r}`,{score:s.value.score,recommendations:s.value.recommendations},{namespace:"quality-assessment",ttl:3600});let a=await this.verifyQualityReportClaims(s.value);return f(a)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async getDeploymentAdvice(e){let r=v();try{if(this.startWorkflow(r,"deployment-advice"),this.minCutMixin.shouldPauseOperations())return ue.warn("Deployment advice paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Deployment advice paused: topology is in critical state"));this.isTopologyHealthy()||ue.warn("Topology degraded during deployment advice generation");let i=await this.spawnDeploymentAdvisorAgent(r,e);i.success&&this.addAgentToWorkflow(r,i.value);let n=await this.deploymentAdvisor.getDeploymentAdvice(e);if(i.success&&await this.agentCoordinator.stop(i.value),!n.success)return this.failWorkflow(r,"Evaluation failed"),n;let s=n.value;if(this.config.enableConsensus&&this.isHighRiskDeployment(e,n.value)){let a=await this.verifyDeploymentAdviceWithConsensus(e,n.value);a&&(s=a)}return this.completeWorkflow(r),this.config.publishEvents&&await this.publishDeploymentDecision(s,e.releaseCandidate),f(s)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}isHighRiskDeployment(e,r){return od(e,r)}async verifyDeploymentAdviceWithConsensus(e,r){return cd(e,r,this.consensusMixin)}async analyzeComplexity(e){let r=v();try{if(this.startWorkflow(r,"complexity-analysis"),this.minCutMixin.shouldPauseOperations())return ue.warn("Complexity analysis paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Complexity analysis paused: topology is in critical state"));this.isTopologyHealthy()||ue.warn("Topology degraded during complexity analysis");let i=await this.spawnComplexityAnalyzerAgent(r,e);i.success&&this.addAgentToWorkflow(r,i.value);let n=await this.qualityAnalyzer.analyzeComplexity(e);return i.success&&await this.agentCoordinator.stop(i.value),n.success?(this.completeWorkflow(r),n):(this.failWorkflow(r,"Evaluation failed"),n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generateReport(e){return Vu(this.memory,e)}async getQualityDashboard(){return _u(this.memory)}async analyzeRisks(e){return zu(this.memory,e)}async evaluateQualityGate(e){let r=Bu(e),i=await this.evaluateGate(r);return i.success?f({passed:i.value.passed,score:i.value.overallScore,violations:i.value.failedChecks}):p(i.error)}async assessDeploymentReadiness(e){return qu(this.memory,e)}async analyzeTechnicalDebt(e){return Gu(this.memory,e)}async spawnQualityGateAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`quality-gate-${e.slice(0,8)}`,domain:"quality-assessment",type:"validator",capabilities:["quality-gate","threshold-evaluation"],config:{workflowId:e,gateName:r.gateName}};return this.agentCoordinator.spawn(i)}async spawnQualityAnalyzerAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`quality-analyzer-${e.slice(0,8)}`,domain:"quality-assessment",type:"analyzer",capabilities:["quality-analysis","metrics-collection","trend-analysis"],config:{workflowId:e,sourceFiles:r.sourceFiles,includeMetrics:r.includeMetrics}};return this.agentCoordinator.spawn(i)}async spawnDeploymentAdvisorAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`deployment-advisor-${e.slice(0,8)}`,domain:"quality-assessment",type:"analyzer",capabilities:["deployment-advice","risk-scoring","ml-prediction"],config:{workflowId:e,releaseCandidate:r.releaseCandidate,riskTolerance:r.riskTolerance}};return this.agentCoordinator.spawn(i)}async spawnComplexityAnalyzerAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`complexity-analyzer-${e.slice(0,8)}`,domain:"quality-assessment",type:"analyzer",capabilities:["complexity-analysis","cyclomatic","cognitive","maintainability"],config:{workflowId:e,sourceFiles:r.sourceFiles,metrics:r.metrics}};return this.agentCoordinator.spawn(i)}async publishQualityGateEvaluated(e){let r=D(Xi.QualityGateEvaluated,"quality-assessment",{gateId:v(),passed:e.passed,checks:e.checks.map(i=>({name:i.name,passed:i.passed,value:i.value,threshold:i.threshold}))});await this.eventBus.publish(r)}async publishDeploymentDecision(e,r){let i=e.decision==="approved"?Xi.DeploymentApproved:Xi.DeploymentBlocked,n=D(i,"quality-assessment",{decision:e.decision,reason:e.reasons.join("; "),riskScore:e.riskScore,recommendations:e.conditions||[],releaseCandidate:r});await this.eventBus.publish(n)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageReportCreated",this.handleCoverageReportCreated.bind(this)),this.eventBus.subscribe("security-compliance.SecurityAuditCompleted",this.handleSecurityAuditCompleted.bind(this)),this.subscribeToDreamEvents()}subscribeToDreamEvents(){this.eventBus.subscribe(Ge.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.domain)||s.suggestedAction?.toLowerCase().includes("quality")||s.suggestedAction?.toLowerCase().includes("gate")||s.suggestedAction?.toLowerCase().includes("threshold"),o=s.sourceConcepts.some(l=>l.toLowerCase().includes("quality")||l.toLowerCase().includes(this.domain)||l.toLowerCase().includes("metric")||l.toLowerCase().includes("gate")),c=s.type==="optimization"||s.type==="pattern_merge";return a||o||c&&s.actionable});if(n.length!==0){ue.info(`[${this.domain}] 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(ue.info(`[${this.domain}] 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};this.qesona.createPattern(i,n,{reward:e.confidenceScore,success:!0,quality:e.noveltyScore},"quality-assessment",this.domain,{insightId:e.id,cycleId:r,description:e.description,suggestedAction:e.suggestedAction,dreamDerived:!0}),ue.info(`[${this.domain}] Created SONA pattern from dream insight ${e.id}`)}catch(i){ue.error(`[${this.domain}] Failed to store dream insight pattern`,i instanceof Error?i:void 0)}await this.memory.set(`${this.domain}:dream-insight:${e.id}`,{insight:e,cycleId:r,appliedAt:new Date().toISOString()},{namespace:this.domain,ttl:86400*7})}encodeInsightAsFeatures(e){return Xu(e)}async handleTestRunCompleted(e){if(!this.config.enableAutoGating)return;let r=e.payload;await this.memory.set(`quality-assessment:test-results:${r.runId}`,r,{namespace:"quality-assessment",ttl:3600})}async handleCoverageReportCreated(e){let r=e.payload;await this.memory.set("coverage:latest",{line:r.line,branch:r.branch,function:0,statement:0,files:0},{persist:!0})}async handleSecurityAuditCompleted(e){let r=e.payload;await this.memory.set(`quality-assessment:security:${r.auditId}`,r,{namespace:"quality-assessment",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("quality-assessment: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("quality-assessment:coordinator:workflows",e,{namespace:"quality-assessment",persist:!0})}async loadRatchetState(){try{let e=await this.memory.get("quality-assessment:ratchet-state");e&&(this.ratchetState=e,ue.info(`Restored ratchet state (threshold=${e.currentThreshold}, passes=${e.consecutivePasses})`))}catch(e){ue.warn("Failed to load ratchet state (using default)",{error:e instanceof Error?e.message:String(e)})}}async saveRatchetState(){try{await this.memory.set("quality-assessment:ratchet-state",this.ratchetState,{namespace:"quality-assessment",persist:!0})}catch(e){ue.warn("Failed to persist ratchet state",{error:e instanceof Error?e.message:String(e)})}}async initializeActorCritic(){this.actorCritic=await Hu()}async initializeQESONA(){this.qesona=await Wu()}async initializeFlashAttention(){this.flashAttention=await ju()}async tuneThresholdsWithRL(e){return!this.actorCritic||!e?null:Uu(this.actorCritic,e)}async trainActorCritic(e,r){this.actorCritic&&await Qu(this.actorCritic,e,r)}async storeQualityPattern(e,r){this.qesona&&await Ku(this.qesona,e,r,this.domain)}async storeQualityAnalysisPattern(e,r){this.qesona&&await Ju(this.qesona,e,r,this.domain)}async enhanceWithSimilarityPatterns(e){return!this.flashAttention||!this.qesona?null:Yu(e,this.flashAttention,this.qesona,this.domain)}async initializeClaimVerifier(){this.claimVerifier=await rd(this.config.claimVerifierRootDir)}async verifyQualityReportClaims(e){return!this.config.enableClaimVerification||!this.claimVerifier?e:id(e,this.claimVerifier)}async verifyGateResultClaims(e){return!this.config.enableClaimVerification||!this.claimVerifier?e:nd(e,this.claimVerifier)}getClaimVerifierStats(){return this.claimVerifier?.getStats()??null}};A();var As=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;qualityGate=null;qualityAnalyzer=null;deploymentAdvisor=null;pluginConfig;get name(){return"quality-assessment"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{evaluateGate:this.evaluateGate.bind(this),analyzeQuality:this.analyzeQuality.bind(this),getDeploymentAdvice:this.getDeploymentAdvice.bind(this),analyzeComplexity:this.analyzeComplexity.bind(this),getCoordinator:()=>this.coordinator,getQualityGate:()=>this.qualityGate,getQualityAnalyzer:()=>this.qualityAnalyzer,getDeploymentAdvisor:()=>this.deploymentAdvisor}}getTaskHandlers(){return new Map([["evaluate-gate",async e=>{let r=e.gateName,i=e.metrics,n=e.thresholds;if(!r||!i||!n)return p(new Error("Invalid evaluate-gate payload: missing gateName, metrics, or thresholds"));let s={gateName:r,metrics:i,thresholds:n};return this.evaluateGate(s)}],["analyze-quality",async e=>{let r=e.sourceFiles;if(!r||r.length===0)return p(new Error("Invalid analyze-quality payload: missing sourceFiles"));let i={sourceFiles:r,includeMetrics:e.includeMetrics??["coverage","complexity","maintainability"],compareBaseline:e.compareBaseline};return this.analyzeQuality(i)}],["deployment-advice",async e=>{let r=e.releaseCandidate,i=e.metrics,n=e.riskTolerance;if(!r||!i)return p(new Error("Invalid deployment-advice payload: missing releaseCandidate or metrics"));let s={releaseCandidate:r,metrics:i,riskTolerance:n??"medium"};return this.getDeploymentAdvice(s)}],["analyze-complexity",async e=>{let r=e.sourceFiles;if(!r||r.length===0)return p(new Error("Invalid analyze-complexity payload: missing sourceFiles"));let i={sourceFiles:r,metrics:e.metrics??["cyclomatic","cognitive"]};return this.analyzeComplexity(i)}]])}async onInitialize(){this.qualityGate=new pt(this.memory,this.pluginConfig.qualityGate),this.qualityAnalyzer=new Ye(this.memory,this.pluginConfig.qualityAnalyzer),this.deploymentAdvisor=new Ft(this.memory,this.pluginConfig.deploymentAdvisor),this.coordinator=new xi(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,this.qualityGate=null,this.qualityAnalyzer=null,this.deploymentAdvisor=null}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageReportCreated",this.handleCoverageReport.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPrediction.bind(this)),this.eventBus.subscribe("security-compliance.VulnerabilityDetected",this.handleVulnerabilityDetected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"coverage-analysis.CoverageReportCreated":await this.handleCoverageReport(e);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPrediction(e);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(e);break;default:break}}async evaluateGate(e){this.ensureInitialized();try{let r=await this.coordinator.evaluateGate(e);return r.success?this.trackSuccessfulOperation("gate-evaluation"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async analyzeQuality(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeQuality(e);return r.success?this.trackSuccessfulOperation("quality-analysis"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async getDeploymentAdvice(e){this.ensureInitialized();try{let r=await this.coordinator.getDeploymentAdvice(e);return r.success?this.trackSuccessfulOperation("deployment-advice"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async analyzeComplexity(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeComplexity(e);return r.success?this.trackSuccessfulOperation("complexity-analysis"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async handleTestRunCompleted(e){let r=e.payload;if(await this.memory.set(`quality-assessment:test-results:${r.runId}`,{...r,receivedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400}),r.failed>0){let i=r.passed+r.failed+r.skipped,n=r.passed/i*100;n<95&&await this.memory.set(`quality-assessment:concerns:test-failures:${r.runId}`,{type:"test-failures",passingRate:n,failedCount:r.failed,severity:n<80?"high":"medium"},{namespace:"quality-assessment",ttl:86400*7})}}async handleCoverageReport(e){let r=e.payload;await this.memory.set("coverage:latest",{line:r.line,branch:r.branch,function:r.function,statement:r.statement,files:0},{persist:!0})}async handleDefectPrediction(e){let r=e.payload;r.probability>=.7&&await this.memory.set(`quality-assessment:defect-risks:${r.predictionId}`,{...r,severity:r.probability>=.9?"critical":"high"},{namespace:"quality-assessment",ttl:86400*7})}async handleVulnerabilityDetected(e){let r=e.payload;await this.memory.set(`quality-assessment:vulnerabilities:${r.vulnId}`,{...r,receivedAt:new Date().toISOString()},{namespace:"quality-assessment",persist:!0})}ensureInitialized(){if(!this._initialized)throw new Error("QualityAssessmentPlugin is not initialized");if(!this.coordinator||!this.qualityGate||!this.qualityAnalyzer||!this.deploymentAdvisor)throw new Error("QualityAssessmentPlugin 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(`quality-assessment:metrics:${e}:${Date.now()}`,{type:e,success:!0,timestamp:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400}).catch(()=>{})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function lc(u,t,e,r){return new As(u,t,e,r)}M();A();M();import{execFileSync as ye}from"child_process";import*as Es from"path";function ht(u){return u.replace(/[;&|`$(){}[\]<>\\'"!\n\r]/g,"")}var Eh={repoRoot:process.cwd(),maxCommits:100,bugKeywords:["fix","bug","patch","issue","error","defect","problem"],enableCache:!0,cacheTtl:300*1e3},ur=class{config;cache=new Map;isGitRepo=null;constructor(t={}){this.config={...Eh,...t}}async isGitRepository(){if(this.isGitRepo!==null)return this.isGitRepo;try{ye("git",["rev-parse","--is-inside-work-tree"],{cwd:this.config.repoRoot,stdio:["pipe","pipe","pipe"]}),this.isGitRepo=!0}catch{this.isGitRepo=!1}return this.isGitRepo}async getChangeFrequency(t){let e=`freq:${t}`,r=this.getFromCache(e);if(r!==void 0)return r;if(!await this.isGitRepository())return .4;try{let i=ht(this.getRelativePath(t)),n=ye("git",["log","--oneline","--since=90 days ago","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim(),s=n?n.split(`
@@ -2720,7 +2721,7 @@ ${JSON.stringify(u,null,2)}
2720
2721
  `).length:0}catch{}let s=0;try{let h=ye("git",["log","--format=%ae","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();h&&(s=new Set(h.split(`
2721
2722
  `).filter(Boolean)).size)}catch{}let a=null;try{let h=ye("git",["log","--format=%at","--follow","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(h){let b=h.split(`
2722
2723
  `).filter(Boolean);if(b.length>0){let w=parseInt(b[b.length-1],10);isNaN(w)||(a=new Date(w*1e3))}}}catch{}let o=null;try{let h=ye("git",["log","-1","--format=%at","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(h){let b=parseInt(h,10);isNaN(b)||(o=new Date(b*1e3))}}catch{}let c=0;if(a&&o&&n>0){let h=Math.max(1,(o.getTime()-a.getTime())/2592e6);c=n/h}let l=o?Date.now()-o.getTime()<10080*60*1e3:!1,d=0,m=new Set;for(let h of this.config.bugKeywords){let b=ht(h);try{let w=ye("git",["log","--oneline","--grep",b,"-i","--",i],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(w){let C=w.split(`
2723
- `);for(let S of C){let P=S.split(" ")[0];P&&!m.has(P)&&(m.add(P),d++)}}}catch{}}let g={filePath:i,totalCommits:n,uniqueAuthors:s,firstCommit:a,lastCommit:o,changeFrequency:c,isRecentlyModified:l,bugFixCommits:d};return this.setCache(e,g),g}catch{return this.getDefaultFileHistory(t)}}async getChangedFiles(t){if(!await this.isGitRepository())return[];try{let r=(t||new Date(Date.now()-864e5)).toISOString().split("T")[0],i=ye("git",["log",`--since=${r}`,"--name-only","--pretty=format:"],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!i)return[];let n=i.split(`
2724
+ `);for(let S of C){let k=S.split(" ")[0];k&&!m.has(k)&&(m.add(k),d++)}}}catch{}}let g={filePath:i,totalCommits:n,uniqueAuthors:s,firstCommit:a,lastCommit:o,changeFrequency:c,isRecentlyModified:l,bugFixCommits:d};return this.setCache(e,g),g}catch{return this.getDefaultFileHistory(t)}}async getChangedFiles(t){if(!await this.isGitRepository())return[];try{let r=(t||new Date(Date.now()-864e5)).toISOString().split("T")[0],i=ye("git",["log",`--since=${r}`,"--name-only","--pretty=format:"],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();if(!i)return[];let n=i.split(`
2724
2725
  `).filter(Boolean);return Array.from(new Set(n))}catch{return[]}}async getCommitFiles(t="HEAD"){if(!await this.isGitRepository())return[];try{let e=ht(t),r=ye("git",["diff-tree","--no-commit-id","--name-only","-r",e],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return r?r.split(`
2725
2726
  `).filter(Boolean):[]}catch{return[]}}async getUncommittedFiles(){if(!await this.isGitRepository())return[];try{let t=[];try{let e=ye("git",["diff","--name-only","HEAD"],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();e&&t.push(...e.split(`
2726
2727
  `).filter(Boolean))}catch{}try{let e=ye("git",["diff","--name-only","--cached"],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();e&&t.push(...e.split(`
@@ -2757,7 +2758,7 @@ ${t.slice(0,4e3)}
2757
2758
  // File: ${l}
2758
2759
  ${m.value.slice(0,2e3)}
2759
2760
  `)}}let o=this.calculateModelConfidence(n),c=null;if(this.isLLMPredictionAvailable()&&a.length>0){let l=await this.getHistoricalDefectPatterns(e);if(c=await this.analyzeDefectRiskWithLLM(a,n,l),c){for(let d of n)d.recommendations=this.mergeRecommendationsWithLLM(d.recommendations,c);c.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:c??void 0})}catch(e){return p(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 analyzeRegressionRisk(t){try{let{changeset:e,baseline:r,depth:i="shallow"}=t;if(e.length===0)return p(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),c=this.generateTestRecommendations(n);return f({overallRisk:a,riskLevel:o,impactedAreas:n,recommendedTests:c,confidence:i==="deep"?.85:.7})}catch(e){return p(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),f(void 0)}catch(e){return p(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 i=await this.extractFileMetrics(t),n=[],s=0;for(let c of e){let d=(i[c.name]??0)*c.weight;s+=d,n.push({name:c.name,contribution:Math.round(d*100)/100})}s=Math.max(0,Math.min(1,s));let a=this.probabilityToRisk(s,r),o=this.generateRecommendations(n,s);return{file:t,probability:s,riskLevel:a,factors:n.filter(c=>c.contribution>.05),recommendations:o}}async extractFileMetrics(t){let e=await this.memory.get(`${this.config.modelNamespace}:file-metrics:${t}`);if(e)return e;let r={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)};return await this.memory.set(`${this.config.modelNamespace}:file-metrics:${t}`,r,{namespace:"defect-intelligence",ttl:3600}),r}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(`
2760
- `).length,c=s.length,l=a.length,d=a.reduce((Y,G)=>Y+G.methods.length,0),m=s.filter(Y=>Y.isAsync).length,g=r.value,h=(g.match(/\bif\s*\(/g)||[]).length,b=(g.match(/\b(for|while|do)\s*[\(\{]/g)||[]).length,w=(g.match(/\bswitch\s*\(/g)||[]).length,C=(g.match(/\bcatch\s*\(/g)||[]).length,S=(g.match(/\?[^?:]+:/g)||[]).length,P=h+b*2+w*2+C+S,k=Math.min(1,o/500),O=Math.min(1,(c+d)/30),z=Math.min(1,P/50),K=m>0?.1:0,Ce=k*.2+O*.25+z*.4+K+(l>3?.05:0);return Math.max(0,Math.min(1,Ce))}catch(i){uc.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{let e=await this.memory.get(`coverage:file:${t}`);if(e&&typeof e.line=="number")return 1-e.line/100;let r=await this.memory.get("coverage:latest");if(r&&typeof r.line=="number")return 1-r.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)).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 c=(await this.extractFileMetrics(o)).codeComplexity*.5;r.push({area:this.categorizeFile(o),files:[o],risk:c,reason:`Dependency of ${t}`}),i+=c}}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 c of o)if(c.module.startsWith(".")){let l=this.resolveRelativeImport(t,c.module);i.push(l)}else c.module.startsWith("node:")||i.push(c.module);i.length>0&&await this.memory.set(e,i,{namespace:"code-intelligence",ttl:3600})}catch(n){uc.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=v();await this.memory.set(`${this.config.modelNamespace}:prediction:${e}`,{id:e,predictions:t,timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}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})}};M();A();var kh={minPatternFrequency:2,maxPatterns:50,clusterThreshold:.7,embeddingDimension:Ct.DIMENSIONS,patternNamespace:"defect-intelligence:patterns",enableSemanticClustering:!0,enableFlashAttention:!0},xs={"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"}},Ih=R.create("defect-intelligence/pattern-learner"),mr=class{constructor(t,e={}){this.memory=t;this.config={...kh,...e},this.embedder=e.embedder??new St({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-5K6UGI3T.js");this.flashAttention=await t("defect-matching",this.config.flashAttentionConfig),this.flashAttentionAvailable=!0,Ih.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 p(new Error("No defects provided for learning"));let i=[],n=!1,s=await this.extractPatterns(e),a=this.mergeWithKnownPatterns(s);for(let c of a)c.frequency>=this.config.minPatternFrequency&&(i.push(c),await this.storePattern(c),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 p(y(e))}}async clusterDefects(t){try{let{defects:e,method:r,minClusterSize:i=2}=t;if(e.length===0)return p(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 p(new Error(`Unknown clustering method: ${r}`))}let s=new Set(n.flatMap(c=>c.defects)),a=e.filter(c=>!s.has(c.id)).map(c=>c.id),o=this.calculateClusteringMetrics(n,e.length);return f({clusters:n,outliers:a,clusteringMetrics:o})}catch(e){return p(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 p(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(xs)){let o=a.indicators.filter(c=>n.includes(c.toLowerCase()));if(o.length>0){let c=e.get(s);c?(c.defects.push(i.id),c.indicators.push(...o.filter(l=>!c.indicators.includes(l)))):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=xs[i];r.push({id:v(),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(xs))e.some(s=>s.name.toLowerCase().includes(r.replace("-"," ")))||e.push({id:v(),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 c of i){if(c.defect.id===s.id||n.has(c.defect.id))continue;await this.computeSimilarity(a,c.embedding)>=this.config.clusterThreshold&&(o.push(c.defect.id),n.add(c.defect.id))}if(o.length>=e){let c=v(),l=this.findCommonFactors(t.filter(d=>o.includes(d.id)));r.set(c,{id:c,label:this.generateClusterLabel(t.filter(d=>o.includes(d.id))),defects:o,commonFactors:l,suggestedFix:this.suggestFix(l)})}}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 c=0;c<r;c++)i[c]=t[c],n[c]=e[c],s[c]=e[c];let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=0;for(let c=0;c<r;c++)o+=a[c]*t[c];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=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Behavioral: ${n.replace(/\|/g,", ")}`,defects:s.map(c=>c.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=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Temporal: ${n}`,defects:s.map(c=>c.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(xs))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((c,l)=>c+l.defects.length,0),i=r/t.length,n=r/e,s=t.map(c=>c.defects.length),a=s.reduce((c,l)=>c+Math.pow(l-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(`
2761
+ `).length,c=s.length,l=a.length,d=a.reduce((Y,G)=>Y+G.methods.length,0),m=s.filter(Y=>Y.isAsync).length,g=r.value,h=(g.match(/\bif\s*\(/g)||[]).length,b=(g.match(/\b(for|while|do)\s*[\(\{]/g)||[]).length,w=(g.match(/\bswitch\s*\(/g)||[]).length,C=(g.match(/\bcatch\s*\(/g)||[]).length,S=(g.match(/\?[^?:]+:/g)||[]).length,k=h+b*2+w*2+C+S,P=Math.min(1,o/500),O=Math.min(1,(c+d)/30),z=Math.min(1,k/50),K=m>0?.1:0,Ce=P*.2+O*.25+z*.4+K+(l>3?.05:0);return Math.max(0,Math.min(1,Ce))}catch(i){uc.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{let e=await this.memory.get(`coverage:file:${t}`);if(e&&typeof e.line=="number")return 1-e.line/100;let r=await this.memory.get("coverage:latest");if(r&&typeof r.line=="number")return 1-r.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)).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 c=(await this.extractFileMetrics(o)).codeComplexity*.5;r.push({area:this.categorizeFile(o),files:[o],risk:c,reason:`Dependency of ${t}`}),i+=c}}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 c of o)if(c.module.startsWith(".")){let l=this.resolveRelativeImport(t,c.module);i.push(l)}else c.module.startsWith("node:")||i.push(c.module);i.length>0&&await this.memory.set(e,i,{namespace:"code-intelligence",ttl:3600})}catch(n){uc.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=v();await this.memory.set(`${this.config.modelNamespace}:prediction:${e}`,{id:e,predictions:t,timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}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})}};M();A();var kh={minPatternFrequency:2,maxPatterns:50,clusterThreshold:.7,embeddingDimension:Ct.DIMENSIONS,patternNamespace:"defect-intelligence:patterns",enableSemanticClustering:!0,enableFlashAttention:!0},xs={"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"}},Ih=R.create("defect-intelligence/pattern-learner"),mr=class{constructor(t,e={}){this.memory=t;this.config={...kh,...e},this.embedder=e.embedder??new St({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-VGKEBQLW.js");this.flashAttention=await t("defect-matching",this.config.flashAttentionConfig),this.flashAttentionAvailable=!0,Ih.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 p(new Error("No defects provided for learning"));let i=[],n=!1,s=await this.extractPatterns(e),a=this.mergeWithKnownPatterns(s);for(let c of a)c.frequency>=this.config.minPatternFrequency&&(i.push(c),await this.storePattern(c),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 p(y(e))}}async clusterDefects(t){try{let{defects:e,method:r,minClusterSize:i=2}=t;if(e.length===0)return p(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 p(new Error(`Unknown clustering method: ${r}`))}let s=new Set(n.flatMap(c=>c.defects)),a=e.filter(c=>!s.has(c.id)).map(c=>c.id),o=this.calculateClusteringMetrics(n,e.length);return f({clusters:n,outliers:a,clusteringMetrics:o})}catch(e){return p(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 p(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(xs)){let o=a.indicators.filter(c=>n.includes(c.toLowerCase()));if(o.length>0){let c=e.get(s);c?(c.defects.push(i.id),c.indicators.push(...o.filter(l=>!c.indicators.includes(l)))):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=xs[i];r.push({id:v(),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(xs))e.some(s=>s.name.toLowerCase().includes(r.replace("-"," ")))||e.push({id:v(),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 c of i){if(c.defect.id===s.id||n.has(c.defect.id))continue;await this.computeSimilarity(a,c.embedding)>=this.config.clusterThreshold&&(o.push(c.defect.id),n.add(c.defect.id))}if(o.length>=e){let c=v(),l=this.findCommonFactors(t.filter(d=>o.includes(d.id)));r.set(c,{id:c,label:this.generateClusterLabel(t.filter(d=>o.includes(d.id))),defects:o,commonFactors:l,suggestedFix:this.suggestFix(l)})}}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 c=0;c<r;c++)i[c]=t[c],n[c]=e[c],s[c]=e[c];let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=0;for(let c=0;c<r;c++)o+=a[c]*t[c];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=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Behavioral: ${n.replace(/\|/g,", ")}`,defects:s.map(c=>c.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=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Temporal: ${n}`,defects:s.map(c=>c.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(xs))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((c,l)=>c+l.defects.length,0),i=r/t.length,n=r/e,s=t.map(c=>c.defects.length),a=s.reduce((c,l)=>c+Math.pow(l-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(`
2761
2762
  `)}formatPatternForEmbedding(t){return[`Pattern: ${t.name}`,`Indicators: ${t.indicators.join(", ")}`,`Prevention: ${t.prevention}`,`Frequency: ${t.frequency}`].filter(Boolean).join(`
2762
2763
  `)}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}};M();A();H();var Dh={maxTimelineEvents:20,maxRelatedFiles:10,minConfidenceThreshold:.3,analyzerNamespace:"defect-intelligence:root-cause",enableDeepAnalysis:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},Ps={"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"]}},Mh=R.create("defect-intelligence/root-cause-analyzer"),pr=class{config;memory;llmRouter;constructor(t,e={}){this.config={...Dh,...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){switch(t){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}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.
2763
2764
  Analyze the provided defect information and provide:
@@ -2809,7 +2810,7 @@ ${r}
2809
2810
  `).filter(i=>i.trim())[0]?.replace(/^(root cause:|the root cause is|caused by)/i,"").trim()||"Unable to parse root cause",explanation:t,contributingFactors:[],recommendedFixes:[],preventionStrategies:[]}}async analyzeRootCause(t){try{let{defectId:e,symptoms:r,context:i={}}=t;if(r.length===0)return p(new Error("No symptoms provided for analysis"));if(this.isLLMAnalysisAvailable()){let d=await this.analyzeRootCauseWithLLM({defectId:e,symptoms:r,context:i},i.stackTrace,i.codeContext);if(d){let m=await this.findRelatedFiles(e,r),g=await this.generateTimeline(e),h=[...d.recommendedFixes.map(b=>b.codeExample?`${b.description}
2810
2811
  \`\`\`
2811
2812
  ${b.codeExample}
2812
- \`\`\``:b.description),...d.preventionStrategies];return await this.storeAnalysis({defectId:e,rootCause:d.rootCause,category:"llm-analyzed",confidence:.85,symptoms:r,timestamp:new Date}),f({defectId:e,rootCause:d.rootCause,confidence:.85,contributingFactors:d.contributingFactors,relatedFiles:m,recommendations:h,timeline:g.success?g.value:[]})}}let n=this.identifyRootCauseCategory(r),s=this.calculateConfidence(n,r);if(s<this.config.minConfidenceThreshold)return f({defectId:e,rootCause:"Unable to determine root cause with sufficient confidence",confidence:s,contributingFactors:[],relatedFiles:[],recommendations:["Provide more symptoms for better analysis"],timeline:[]});let a=await this.identifyContributingFactors(n.category,r,i),o=await this.findRelatedFiles(e,r),c=this.generateRecommendations(n,a),l=await this.generateTimeline(e);return await this.storeAnalysis({defectId:e,rootCause:n.rootCause,category:n.category,confidence:s,symptoms:r,timestamp:new Date}),f({defectId:e,rootCause:n.rootCause,confidence:s,contributingFactors:a,relatedFiles:o,recommendations:c,timeline:l.success?l.value:[]})}catch(e){return p(y(e))}}async findRelatedDefects(t){try{let e=await this.memory.get(`${this.config.analyzerNamespace}:analysis:${t}`);if(!e)return f([]);let r=await this.memory.search(`${this.config.analyzerNamespace}:analysis:*`,50),i=[];for(let n of r){let s=await this.memory.get(n);s&&s.defectId!==t&&s.category===e.category&&i.push(s.defectId)}return f(i)}catch(e){return p(y(e))}}async generateTimeline(t){try{let e=[],r=`${this.config.analyzerNamespace}:events:${t}`,i=await this.memory.get(r);i&&e.push(...i);let n=await this.memory.search("code-intelligence:change:*",this.config.maxTimelineEvents);for(let a of n){let o=await this.memory.get(a);o&&e.push({timestamp:new Date(o.timestamp),event:`Code change: ${o.description}`,relevance:.5})}let s=e.sort((a,o)=>o.timestamp.getTime()-a.timestamp.getTime()).slice(0,this.config.maxTimelineEvents);return f(s)}catch(e){return p(y(e))}}async suggestRemediation(t){let e=[];for(let[r,i]of Object.entries(Ps))(t.toLowerCase().includes(r)||i.causes.some(n=>t.toLowerCase().includes(n.toLowerCase())))&&e.push(...i.remediation);return e.length===0&&(e.push("Review the affected code thoroughly"),e.push("Add tests to prevent regression"),e.push("Document the fix for future reference")),[...new Set(e)]}identifyRootCauseCategory(t){let e={category:"unknown",rootCause:"Undetermined root cause",matchScore:0},r=t.join(" ").toLowerCase();for(let[i,n]of Object.entries(Ps)){let s=0;for(let a of n.symptoms)r.includes(a.toLowerCase())&&(s+=1);if(s=s/n.symptoms.length,s>e.matchScore){let a=this.selectLikelyCause(n.causes,r);e={category:i,rootCause:a,matchScore:s}}}return e}selectLikelyCause(t,e){let r=t[0],i=0;for(let n of t){let s=n.toLowerCase().split(/\s+/),a=0;for(let o of s)o.length>3&&e.includes(o)&&(a+=1);a>i&&(i=a,r=n)}return r}calculateConfidence(t,e){let r=t.matchScore;return e.length>=3?r*=1.1:e.length===1&&(r*=.8),Math.min(1,Math.max(0,r))}async identifyContributingFactors(t,e,r){let i=[],n=Ps[t];if(!n)return i;i.push({factor:`Category: ${t}`,impact:n.impact,evidence:e.slice(0,3)}),r.recentChanges&&i.push({factor:"Recent code changes",impact:"high",evidence:["Code was recently modified"]}),r.highTraffic&&i.push({factor:"High traffic conditions",impact:"medium",evidence:["Occurred during peak load"]}),r.environment&&i.push({factor:`Environment: ${r.environment}`,impact:"medium",evidence:[`Observed in ${r.environment} environment`]});let s=await this.getHistoricalFactors(t);return i.push(...s),i}async getHistoricalFactors(t){let e=[],r=`${this.config.analyzerNamespace}:history:${t}`,i=await this.memory.get(r);return i&&i.occurrences>1&&e.push({factor:"Recurring issue pattern",impact:"high",evidence:[`Similar issues occurred ${i.occurrences} times`,...i.commonFactors.slice(0,2)]}),e}async findRelatedFiles(t,e){let r=new Set;for(let n of e){let s=n.match(/[\w\-]+\.(ts|js|tsx|jsx|py|java|go)/g);s&&s.forEach(o=>r.add(o));let a=n.match(/(?:src|lib|app)\/[\w\/\-]+/g);a&&a.forEach(o=>r.add(o))}let i=await this.memory.search("code-intelligence:file:*",this.config.maxRelatedFiles);for(let n of i.slice(0,this.config.maxRelatedFiles-r.size)){let s=await this.memory.get(n);s&&r.add(s.path)}return Array.from(r).slice(0,this.config.maxRelatedFiles)}generateRecommendations(t,e){let r=[],i=Ps[t.category];i&&r.push(...i.remediation);for(let n of e)n.impact==="high"&&r.push(`Address: ${n.factor}`);return r.push("Add regression tests for this scenario"),r.push("Document the root cause and fix"),[...new Set(r)].slice(0,8)}async storeAnalysis(t){await this.memory.set(`${this.config.analyzerNamespace}:analysis:${t.defectId}`,t,{namespace:"defect-intelligence",persist:!0});let e=`${this.config.analyzerNamespace}:history:${t.category}`,r=await this.memory.get(e)||{occurrences:0,commonFactors:[]};r.occurrences+=1;for(let i of t.symptoms.slice(0,2))r.commonFactors.includes(i)||r.commonFactors.push(i);r.commonFactors=r.commonFactors.slice(0,10),await this.memory.set(e,r,{namespace:"defect-intelligence",persist:!0})}};qe();var Fh={maxLag:5,alpha:.05,minSeriesLength:30},Lh=200,Le=1e-10,Pi=1e-12;function ks(u){if(u<=0)return 1/0;let t=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,15056327351493116e-23];if(u<.5)return Math.log(Math.PI/Math.sin(Math.PI*u))-ks(1-u);u-=1;let e=t[0];for(let i=1;i<9;i++)e+=t[i]/(u+i);let r=u+7.5;return .5*Math.log(2*Math.PI)+(u+.5)*Math.log(r)-r+Math.log(e)}function $h(u,t){return ks(u)+ks(t)-ks(u+t)}function gd(u,t,e){if(u<=0)return 0;if(u>=1)return 1;if(t<=0||e<=0)return NaN;if(u>(t+1)/(t+e+2))return 1-gd(1-u,e,t);let r=Math.exp(t*Math.log(u)+e*Math.log(1-u)-$h(t,e)-Math.log(t)),i=1,n=1-(t+e)*u/(t+1);Math.abs(n)<Le&&(n=Le),n=1/n;let s=n;for(let a=1;a<=Lh;a++){let o=a*(e-a)*u/((t+2*a-1)*(t+2*a));n=1+o*n,Math.abs(n)<Le&&(n=Le),i=1+o/i,Math.abs(i)<Le&&(i=Le),n=1/n,s*=i*n,o=-(t+a)*(t+e+a)*u/((t+2*a)*(t+2*a+1)),n=1+o*n,Math.abs(n)<Le&&(n=Le),i=1+o/i,Math.abs(i)<Le&&(i=Le),n=1/n;let c=i*n;if(s*=c,Math.abs(c-1)<Le)break}return r*s}function Oh(u,t,e){return u<=0?0:t<=0||e<=0?NaN:isFinite(u)?gd(t*u/(t*u+e),t/2,e/2):1}function Nh(u,t){let e=t.length,r=u.map((n,s)=>[...n,t[s]]);for(let n=0;n<e;n++){let s=Math.abs(r[n][n]),a=n;for(let o=n+1;o<e;o++){let c=Math.abs(r[o][n]);c>s&&(s=c,a=o)}if(s<Pi)return null;a!==n&&([r[n],r[a]]=[r[a],r[n]]);for(let o=n+1;o<e;o++){let c=r[o][n]/r[n][n];for(let l=n;l<=e;l++)r[o][l]-=c*r[n][l]}}let i=new Array(e).fill(0);for(let n=e-1;n>=0;n--){if(Math.abs(r[n][n])<Pi)return null;let s=r[n][e];for(let a=n+1;a<e;a++)s-=r[n][a]*i[a];i[n]=s/r[n][n]}return i}function md(u,t){let e=t.length,r=u[0].length,i=Array.from({length:r},()=>new Array(r).fill(0));for(let s=0;s<r;s++)for(let a=s;a<r;a++){let o=0;for(let c=0;c<e;c++)o+=u[c][s]*u[c][a];i[s][a]=o,i[a][s]=o}let n=new Array(r).fill(0);for(let s=0;s<r;s++){let a=0;for(let o=0;o<e;o++)a+=u[o][s]*t[o];n[s]=a}return Nh(i,n)}function pd(u,t,e){let r=0;for(let i=0;i<t.length;i++){let n=0;for(let a=0;a<e.length;a++)n+=u[i][a]*e[a];let s=t[i]-n;r+=s*s}return r}function Vh(u,t){let e=Math.max(u.timestamps[0]??1/0,t.timestamps[0]??1/0),r=Math.min(u.timestamps[u.timestamps.length-1]??-1/0,t.timestamps[t.timestamps.length-1]??-1/0);if(e>=r)return null;let i=[];for(let c of[u,t])for(let l=1;l<c.timestamps.length;l++){let d=c.timestamps[l]-c.timestamps[l-1];d>0&&i.push(d)}if(i.length===0)return null;i.sort((c,l)=>c-l);let n=i[Math.floor(i.length/2)];if(n<=0)return null;let s=Math.floor((r-e)/n)+1;if(s<2)return null;let a=new Array(s).fill(0),o=new Array(s).fill(0);for(let[c,l]of[[u,a],[t,o]])for(let d=0;d<c.timestamps.length;d++){let m=Math.round((c.timestamps[d]-e)/n);m>=0&&m<s&&(l[m]=c.outcomes[d])}return{sourceOutcomes:a,targetOutcomes:o}}var ki=class{config;constructor(t){this.config={...Fh,...t}}analyzeCausality(t){if(t.length<2)return[];let e=[];for(let r=0;r<t.length;r++)for(let i=0;i<t.length;i++){if(r===i)continue;let n=t[r],s=t[i];if(n.outcomes.length<this.config.minSeriesLength||s.outcomes.length<this.config.minSeriesLength)continue;let a=null;for(let o=1;o<=this.config.maxLag;o++){let c=this.testPairwise(n,s,o);this.significanceTest(c)&&(a===null||c.pValue<a.pValue)&&(a=c)}a&&e.push(a)}return e.sort((r,i)=>r.pValue-i.pValue),e}testPairwise(t,e,r){let i={sourceTestId:t.testId,targetTestId:e.testId,lag:r,fStatistic:0,pValue:1,strength:0,direction:"positive"},n,s;if(this.arraysEqual(t.timestamps,e.timestamps))n=t.outcomes,s=e.outcomes;else{let G=Vh(t,e);if(!G)return i;n=G.sourceOutcomes,s=G.targetOutcomes}let a=s.length,o=a-r,c=o-2*r-1;if(c<=0||o<this.config.minSeriesLength)return i;let l=new Array(o);for(let G=0;G<o;G++)l[G]=s[G+r];let d=l.reduce((G,ne)=>G+ne,0)/l.length;if(l.reduce((G,ne)=>G+(ne-d)**2,0)<Pi)return i;let m=new Array(o);for(let G=0;G<o;G++){let ne=new Array(r+1);ne[0]=1;for(let X=1;X<=r;X++)ne[X]=s[G+r-X];m[G]=ne}let g=new Array(o);for(let G=0;G<o;G++){let ne=new Array(2*r+1);ne[0]=1;for(let X=1;X<=r;X++)ne[X]=s[G+r-X];for(let X=1;X<=r;X++)ne[r+X]=n[G+r-X];g[G]=ne}let h=md(m,l);if(!h)return i;let b=pd(m,l,h),w=md(g,l);if(!w)return i;let C=pd(g,l,w);if(C>b)return i;let S=(b-C)/r,P=C/c,k=w.slice(r+1,2*r+1),O=k.reduce((G,ne)=>G+Math.abs(ne),0)/r,K=k.reduce((G,ne)=>G+ne,0)/r>=0?"positive":"negative";if(P<Pi){let G=S>Pi?1e6:0;return{...i,fStatistic:G,pValue:G>0?0:1,strength:O,direction:K}}let Ce=S/P,Y=1-Oh(Ce,r,c);return{sourceTestId:t.testId,targetTestId:e.testId,lag:r,fStatistic:Math.max(0,Ce),pValue:Math.max(0,Math.min(1,Y)),strength:O,direction:K}}significanceTest(t){return t.pValue<this.config.alpha&&t.fStatistic>0}arraysEqual(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}};var _h={maxConcurrentWorkflows:5,defaultTimeout:6e4,enablePatternLearning:!0,publishEvents:!0,autoAnalyzeThreshold:.7,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Ii=R.create("defect-intelligence"),Is=class extends Q{constructor(e,r,i,n={}){let s={..._h,...n};super(e,"defect-intelligence",s,{verifyFindingTypes:["defect-prediction","root-cause","regression-risk","pattern-classification"],...s.consensusConfig});this.memory=r;this.agentCoordinator=i;this.predictor=new dr(r),this.patternLearner=new mr(r),this.rootCauseAnalyzer=new pr(r)}memory;agentCoordinator;predictor;patternLearner;rootCauseAnalyzer;testExecutionHistory=new Map;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState()}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}getDomainWeakVertices(){return this.minCutMixin.getDomainWeakVertices()}onTopologyHealthChange(e){return this.minCutMixin.onTopologyHealthChange(e)}requiresConsensus(e){return this.consensusMixin.requiresConsensus(e)}async verifyFinding(e){return this.consensusMixin.verifyFinding(e)}async predictDefects(e){let r=v();try{if(this.startWorkflow(r,"predict"),this.config.enableMinCutAwareness&&this.minCutMixin.shouldPauseOperations()&&Ii.warn("Topology is critical, proceeding with caution"),!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn prediction agents"));let i=await this.spawnPredictionAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.predictor.predictDefects(e);if(n.success){let s=await this.verifyHighConfidencePredictions(n.value.predictions),a={...n.value,predictions:s};if(this.completeWorkflow(r),this.config.publishEvents&&await this.publishPredictionEvent(a),this.config.enablePatternLearning&&await this.autoAnalyzeHighRisk(a),bt().useGrangerCausality)try{let o=Date.now();for(let l of a.predictions){let d=this.testExecutionHistory.get(l.file)??{timestamps:[],outcomes:[]};d.timestamps.push(o),d.outcomes.push(l.probability>.5?0:1),d.timestamps.length>500&&(d.timestamps.splice(0,d.timestamps.length-500),d.outcomes.splice(0,d.outcomes.length-500)),this.testExecutionHistory.set(l.file,d)}let c=Array.from(this.testExecutionHistory.entries()).filter(([,l])=>l.timestamps.length>=30).map(([l,d])=>({testId:l,timestamps:d.timestamps,outcomes:d.outcomes}));if(c.length>=3){let d=new ki({maxLag:5,alpha:.05}).analyzeCausality(c);d.length>0&&Ii.info("Granger causality found causal links in defect predictions",{linkCount:d.length,historyDepth:c[0].timestamps.length,topLink:`${d[0].sourceTestId} \u2192 ${d[0].targetTestId} (lag=${d[0].lag}, p=${d[0].pValue.toFixed(4)})`})}}catch(o){Ii.warn("Granger causality analysis failed (non-fatal)",{error:o instanceof Error?o.message:"unknown"})}return await this.agentCoordinator.stop(i.value),f(a)}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),{success:!1,error:n}}}async verifyHighConfidencePredictions(e){if(!this.config.enableConsensus)return e;let r=[];for(let i of e)if(i.probability>=this.config.consensusThreshold){let n={id:v(),type:"defect-prediction",confidence:i.probability,severity:i.riskLevel==="critical"||i.riskLevel==="high"?i.riskLevel:"medium",description:`Defect prediction for ${i.file}: ${i.probability*100}% probability`,payload:i,detectedAt:new Date,detectedBy:"defect-intelligence-coordinator"};if(this.consensusMixin.requiresConsensus(n))try{let s=await this.consensusMixin.verifyFinding(n);s.success?s.value.verdict==="verified"?r.push({...i,recommendations:[...i.recommendations,"[Consensus Verified] This prediction has been confirmed by multiple AI models."]}):s.value.verdict==="disputed"&&r.push({...i,probability:i.probability*.6,recommendations:[...i.recommendations,"[Consensus Disputed] This prediction requires human review."]}):r.push(i)}catch{Ii.warn(`Consensus verification failed for ${i.file}`),r.push(i)}else r.push(i)}else r.push(i);return r}async analyzeRootCause(e){let r=v();try{this.startWorkflow(r,"analyze");let i=await this.spawnAnalysisAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.rootCauseAnalyzer.analyzeRootCause(e);if(n.success){let s=await this.verifyRootCauseAnalysis(n.value);return this.completeWorkflow(r),this.config.publishEvents&&await this.publishRootCauseEvent(s),await this.agentCoordinator.stop(i.value),f(s)}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async verifyRootCauseAnalysis(e){if(!this.config.enableConsensus||e.confidence<this.config.consensusThreshold)return e;let r={id:v(),type:"root-cause",confidence:e.confidence,severity:"high",description:`Root cause identified for ${e.defectId}: ${e.rootCause}`,payload:e,detectedAt:new Date,detectedBy:"defect-intelligence-coordinator"};if(this.consensusMixin.requiresConsensus(r))try{let i=await this.consensusMixin.verifyFinding(r);if(i.success)return{...e,recommendations:[...e.recommendations,i.value.verdict==="verified"?"[Consensus Verified] This root cause analysis has been confirmed by multiple AI models.":"[Consensus Disputed] This root cause analysis requires human review."],confidence:i.value.verdict==="verified"?Math.min(1,e.confidence*1.1):e.confidence*.7}}catch{Ii.warn("Consensus verification failed for root cause")}return e}async analyzeRegressionRisk(e){let r=v();try{this.startWorkflow(r,"regression");let i=await this.spawnRegressionAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.predictor.analyzeRegressionRisk(e);return n.success?(this.completeWorkflow(r),this.config.publishEvents&&await this.publishRegressionEvent(n.value)):this.failWorkflow(r,n.error.message),await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async clusterDefects(e){let r=v();try{this.startWorkflow(r,"cluster");let i=await this.patternLearner.clusterDefects(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async learnPatterns(e){let r=v();try{this.startWorkflow(r,"learn");let i=await this.patternLearner.learnPatterns(e);return i.success?(this.completeWorkflow(r),this.config.publishEvents&&i.value.modelUpdated&&await this.publishPatternLearnedEvent(i.value)):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async spawnPredictionAgent(e,r){let i={name:`defect-predictor-${e.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["defect-prediction","ml-analysis"],config:{workflowId:e,files:r.files,threshold:r.threshold}};return this.agentCoordinator.spawn(i)}async spawnAnalysisAgent(e,r){let i={name:`root-cause-analyzer-${e.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["root-cause-analysis","symptom-analysis"],config:{workflowId:e,defectId:r.defectId,symptoms:r.symptoms}};return this.agentCoordinator.spawn(i)}async spawnRegressionAgent(e,r){let i={name:`regression-analyzer-${e.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["regression-analysis","impact-analysis"],config:{workflowId:e,changeset:r.changeset,depth:r.depth}};return this.agentCoordinator.spawn(i)}async publishPredictionEvent(e){for(let r of e.predictions)if(r.probability>=this.config.autoAnalyzeThreshold){let i=D(Zi.DefectPredicted,"defect-intelligence",{predictionId:v(),file:r.file,probability:r.probability,factors:r.factors.map(n=>n.name),recommendations:r.recommendations});await this.eventBus.publish(i)}}async publishRootCauseEvent(e){let r=D(Zi.RootCauseIdentified,"defect-intelligence",{analysisId:v(),defectId:e.defectId,rootCause:e.rootCause,confidence:e.confidence,relatedFiles:e.relatedFiles});await this.eventBus.publish(r)}async publishRegressionEvent(e){let r=D(Zi.RegressionRiskAnalyzed,"defect-intelligence",{riskLevel:e.riskLevel,overallRisk:e.overallRisk,impactedAreas:e.impactedAreas.length,recommendedTests:e.recommendedTests.length});await this.eventBus.publish(r)}async publishPatternLearnedEvent(e){let r=D("defect-intelligence.PatternLearned","defect-intelligence",{patternCount:e.patterns.length,modelUpdated:e.modelUpdated,improvementEstimate:e.improvementEstimate});await this.eventBus.publish(r)}async handleTestRunCompleted(e){let r=e.payload;r.failed>0&&this.config.enablePatternLearning&&await this.memory.set(`defect-intelligence:failed-tests:${Date.now()}`,{timestamp:new Date().toISOString(),failedCount:r.failed,testIds:r.testIds},{namespace:"defect-intelligence",ttl:86400*7})}async handleImpactAnalysis(e){let r=e.payload;r.changedFiles.length>3&&await this.analyzeRegressionRisk({changeset:r.changedFiles,depth:"shallow"})}async autoAnalyzeHighRisk(e){let r=e.predictions.filter(i=>i.probability>=this.config.autoAnalyzeThreshold);for(let i of r.slice(0,3))await this.memory.set(`defect-intelligence:high-risk:${i.file}`,{file:i.file,probability:i.probability,factors:i.factors,detectedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("defect-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("defect-intelligence:coordinator:workflows",e,{namespace:"defect-intelligence",persist:!0})}};A();var dc=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;predictor=null;patternLearner=null;rootCauseAnalyzer=null;pluginConfig;get name(){return"defect-intelligence"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{predictDefects:this.predictDefects.bind(this),analyzeRootCause:this.analyzeRootCause.bind(this),analyzeRegressionRisk:this.analyzeRegressionRisk.bind(this),clusterDefects:this.clusterDefects.bind(this),learnPatterns:this.learnPatterns.bind(this),getCoordinator:()=>this.coordinator,getPredictor:()=>this.predictor,getPatternLearner:()=>this.patternLearner,getRootCauseAnalyzer:()=>this.rootCauseAnalyzer}}getTaskHandlers(){return new Map([["predict-defects",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.files,i=e.threshold;return!r||r.length===0?p(new Error("Invalid predict-defects payload: missing files")):this.coordinator.predictDefects({files:r,threshold:i??.7})}],["analyze-root-cause",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.defectId;if(!r)return p(new Error("Invalid analyze-root-cause payload: missing defectId"));let i=e.stackTrace?[e.stackTrace]:e.symptoms??[];return this.coordinator.analyzeRootCause({defectId:r,symptoms:i,context:e.context})}],["analyze-regression-risk",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.changedFiles;return!r||r.length===0?p(new Error("Invalid analyze-regression-risk payload: missing changedFiles")):this.coordinator.analyzeRegressionRisk({changeset:r,baseline:e.commitHash})}],["cluster-defects",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.defects;return!r||r.length===0?p(new Error("Invalid cluster-defects payload: missing defects")):this.coordinator.clusterDefects({defects:r.map(i=>({id:i.id,title:i.title??`Defect ${i.id}`,description:i.description??""})),method:e.method??"semantic"})}],["learn-patterns",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.defectHistory,i=e.defects,n=r??i;return!n||n.length===0?p(new Error("Invalid learn-patterns payload: missing defectHistory")):this.coordinator.learnPatterns({defects:n.map(s=>({id:s.id,title:s.title??`Defect ${s.id}`,description:s.description??""})),includeResolutions:e.includeResolutions})}]])}async onInitialize(){this.predictor=new dr(this.memory,this.pluginConfig.predictor),this.patternLearner=new mr(this.memory,this.pluginConfig.patternLearner),this.rootCauseAnalyzer=new pr(this.memory,this.pluginConfig.rootCauseAnalyzer),this.coordinator=new Is(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,this.predictor=null,this.patternLearner=null,this.rootCauseAnalyzer=null}subscribeToEvents(){this.eventBus.subscribe("test-execution.FlakyTestDetected",this.handleFlakyTest.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-execution.FlakyTestDetected":await this.handleFlakyTest(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;default:break}}async predictDefects(e){this.ensureInitialized();try{let r=await this.coordinator.predictDefects(e);return r.success?this.trackSuccessfulOperation("predict"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async analyzeRootCause(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeRootCause(e);return r.success?this.trackSuccessfulOperation("analyze"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async analyzeRegressionRisk(e){this.ensureInitialized();try{return await this.coordinator.analyzeRegressionRisk(e)}catch(r){return this.handleError(r)}}async clusterDefects(e){this.ensureInitialized();try{return await this.coordinator.clusterDefects(e)}catch(r){return this.handleError(r)}}async learnPatterns(e){this.ensureInitialized();try{let r=await this.coordinator.learnPatterns(e);return r.success&&this.trackSuccessfulOperation("learn"),r}catch(r){return this.handleError(r)}}async handleFlakyTest(e){let r=e.payload;await this.memory.set(`defect-intelligence:flaky-test:${r.testId}`,{...r,detectedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*30}),r.failureRate>.3&&r.testFile&&await this.coordinator?.predictDefects({files:[r.testFile],threshold:.5})}async handleCoverageGap(e){let r=e.payload;r.riskScore>=.7&&await this.memory.set(`defect-intelligence:coverage-gap:${r.gapId}`,{...r,analyzedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}async handleImpactAnalysis(e){let r=e.payload;await this.memory.set(`defect-intelligence:impact:${r.analysisId}`,{...r,recordedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400})}async handleQualityGate(e){let r=e.payload;if(!r.passed){let i=r.checks.filter(n=>!n.passed);await this.memory.set(`defect-intelligence:quality-failure:${r.gateId}`,{failedChecks:i.map(n=>n.name),timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}}ensureInitialized(){if(!this._initialized)throw new Error("DefectIntelligencePlugin is not initialized");if(!this.coordinator||!this.predictor||!this.patternLearner||!this.rootCauseAnalyzer)throw new Error("DefectIntelligencePlugin 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 hd(u,t,e,r){return new dc(u,t,e,r)}M();A();M();A();H();var zh={enableAmbiguityDetection:!0,minAcceptanceCriteria:1,strictMode:!1,forbiddenTermsDefault:[],enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},mc={fast:["within 100ms","under 1 second","response time < 500ms"],quickly:["within 100ms","under 1 second","response time < 500ms"],"user-friendly":["meets WCAG 2.1 AA","usability score > 80","task completion < 3 clicks"],intuitive:["no training required","task completion rate > 90%"],secure:["encrypted with AES-256","authenticated via OAuth2","passes OWASP Top 10"],scalable:["handles 10K concurrent users","horizontal scaling supported"],reliable:["99.9% uptime","MTBF > 1000 hours"],efficient:["O(n) complexity","memory usage < 100MB"],easy:["single click action","no training required"],simple:["single-page workflow","under 5 steps"],flexible:["configurable via settings","supports multiple formats"],robust:["handles edge cases","graceful degradation"],appropriate:["defined by business rules","within acceptable range"],reasonable:["defined threshold","measurable criteria"],adequate:["meets minimum requirements","specified capacity"],good:["measurable quality metric","defined acceptance criteria"],better:["defined improvement metric","baseline comparison"],best:["top-ranked by metric","optimal solution"],several:["specify count: 3-5","defined quantity"],many:["specify count: 10+","defined quantity"],few:["specify count: 2-3","defined quantity"],some:["specify percentage or count","defined subset"],most:["specify percentage > 50%","defined majority"],etc:["complete list","defined scope"],"and/or":["specify condition","boolean logic"]},fd=R.create("requirements-validation/requirements-validator"),gr=class{config;memory;llmRouter;constructor(t,e={}){this.config={...zh,...e},"memory"in t&&typeof t.memory=="object"?(this.memory=t.memory,this.llmRouter=t.llmRouter):this.memory=t}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(t){switch(t){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async analyzeRequirementsWithLLM(t,e){if(!this.isLLMAnalysisAvailable())return f(this.getBasicAnalysis(t));try{let r=this.getModelForTier(this.config.llmModelTier??2),i=this.buildRequirementsAnalysisPrompt(t,e),n=await this.llmRouter.chat({messages:[{role:"system",content:`You are a senior requirements engineer and QA specialist. Analyze requirements for:
2813
+ \`\`\``:b.description),...d.preventionStrategies];return await this.storeAnalysis({defectId:e,rootCause:d.rootCause,category:"llm-analyzed",confidence:.85,symptoms:r,timestamp:new Date}),f({defectId:e,rootCause:d.rootCause,confidence:.85,contributingFactors:d.contributingFactors,relatedFiles:m,recommendations:h,timeline:g.success?g.value:[]})}}let n=this.identifyRootCauseCategory(r),s=this.calculateConfidence(n,r);if(s<this.config.minConfidenceThreshold)return f({defectId:e,rootCause:"Unable to determine root cause with sufficient confidence",confidence:s,contributingFactors:[],relatedFiles:[],recommendations:["Provide more symptoms for better analysis"],timeline:[]});let a=await this.identifyContributingFactors(n.category,r,i),o=await this.findRelatedFiles(e,r),c=this.generateRecommendations(n,a),l=await this.generateTimeline(e);return await this.storeAnalysis({defectId:e,rootCause:n.rootCause,category:n.category,confidence:s,symptoms:r,timestamp:new Date}),f({defectId:e,rootCause:n.rootCause,confidence:s,contributingFactors:a,relatedFiles:o,recommendations:c,timeline:l.success?l.value:[]})}catch(e){return p(y(e))}}async findRelatedDefects(t){try{let e=await this.memory.get(`${this.config.analyzerNamespace}:analysis:${t}`);if(!e)return f([]);let r=await this.memory.search(`${this.config.analyzerNamespace}:analysis:*`,50),i=[];for(let n of r){let s=await this.memory.get(n);s&&s.defectId!==t&&s.category===e.category&&i.push(s.defectId)}return f(i)}catch(e){return p(y(e))}}async generateTimeline(t){try{let e=[],r=`${this.config.analyzerNamespace}:events:${t}`,i=await this.memory.get(r);i&&e.push(...i);let n=await this.memory.search("code-intelligence:change:*",this.config.maxTimelineEvents);for(let a of n){let o=await this.memory.get(a);o&&e.push({timestamp:new Date(o.timestamp),event:`Code change: ${o.description}`,relevance:.5})}let s=e.sort((a,o)=>o.timestamp.getTime()-a.timestamp.getTime()).slice(0,this.config.maxTimelineEvents);return f(s)}catch(e){return p(y(e))}}async suggestRemediation(t){let e=[];for(let[r,i]of Object.entries(Ps))(t.toLowerCase().includes(r)||i.causes.some(n=>t.toLowerCase().includes(n.toLowerCase())))&&e.push(...i.remediation);return e.length===0&&(e.push("Review the affected code thoroughly"),e.push("Add tests to prevent regression"),e.push("Document the fix for future reference")),[...new Set(e)]}identifyRootCauseCategory(t){let e={category:"unknown",rootCause:"Undetermined root cause",matchScore:0},r=t.join(" ").toLowerCase();for(let[i,n]of Object.entries(Ps)){let s=0;for(let a of n.symptoms)r.includes(a.toLowerCase())&&(s+=1);if(s=s/n.symptoms.length,s>e.matchScore){let a=this.selectLikelyCause(n.causes,r);e={category:i,rootCause:a,matchScore:s}}}return e}selectLikelyCause(t,e){let r=t[0],i=0;for(let n of t){let s=n.toLowerCase().split(/\s+/),a=0;for(let o of s)o.length>3&&e.includes(o)&&(a+=1);a>i&&(i=a,r=n)}return r}calculateConfidence(t,e){let r=t.matchScore;return e.length>=3?r*=1.1:e.length===1&&(r*=.8),Math.min(1,Math.max(0,r))}async identifyContributingFactors(t,e,r){let i=[],n=Ps[t];if(!n)return i;i.push({factor:`Category: ${t}`,impact:n.impact,evidence:e.slice(0,3)}),r.recentChanges&&i.push({factor:"Recent code changes",impact:"high",evidence:["Code was recently modified"]}),r.highTraffic&&i.push({factor:"High traffic conditions",impact:"medium",evidence:["Occurred during peak load"]}),r.environment&&i.push({factor:`Environment: ${r.environment}`,impact:"medium",evidence:[`Observed in ${r.environment} environment`]});let s=await this.getHistoricalFactors(t);return i.push(...s),i}async getHistoricalFactors(t){let e=[],r=`${this.config.analyzerNamespace}:history:${t}`,i=await this.memory.get(r);return i&&i.occurrences>1&&e.push({factor:"Recurring issue pattern",impact:"high",evidence:[`Similar issues occurred ${i.occurrences} times`,...i.commonFactors.slice(0,2)]}),e}async findRelatedFiles(t,e){let r=new Set;for(let n of e){let s=n.match(/[\w\-]+\.(ts|js|tsx|jsx|py|java|go)/g);s&&s.forEach(o=>r.add(o));let a=n.match(/(?:src|lib|app)\/[\w\/\-]+/g);a&&a.forEach(o=>r.add(o))}let i=await this.memory.search("code-intelligence:file:*",this.config.maxRelatedFiles);for(let n of i.slice(0,this.config.maxRelatedFiles-r.size)){let s=await this.memory.get(n);s&&r.add(s.path)}return Array.from(r).slice(0,this.config.maxRelatedFiles)}generateRecommendations(t,e){let r=[],i=Ps[t.category];i&&r.push(...i.remediation);for(let n of e)n.impact==="high"&&r.push(`Address: ${n.factor}`);return r.push("Add regression tests for this scenario"),r.push("Document the root cause and fix"),[...new Set(r)].slice(0,8)}async storeAnalysis(t){await this.memory.set(`${this.config.analyzerNamespace}:analysis:${t.defectId}`,t,{namespace:"defect-intelligence",persist:!0});let e=`${this.config.analyzerNamespace}:history:${t.category}`,r=await this.memory.get(e)||{occurrences:0,commonFactors:[]};r.occurrences+=1;for(let i of t.symptoms.slice(0,2))r.commonFactors.includes(i)||r.commonFactors.push(i);r.commonFactors=r.commonFactors.slice(0,10),await this.memory.set(e,r,{namespace:"defect-intelligence",persist:!0})}};qe();var Fh={maxLag:5,alpha:.05,minSeriesLength:30},Lh=200,Le=1e-10,Pi=1e-12;function ks(u){if(u<=0)return 1/0;let t=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,15056327351493116e-23];if(u<.5)return Math.log(Math.PI/Math.sin(Math.PI*u))-ks(1-u);u-=1;let e=t[0];for(let i=1;i<9;i++)e+=t[i]/(u+i);let r=u+7.5;return .5*Math.log(2*Math.PI)+(u+.5)*Math.log(r)-r+Math.log(e)}function $h(u,t){return ks(u)+ks(t)-ks(u+t)}function gd(u,t,e){if(u<=0)return 0;if(u>=1)return 1;if(t<=0||e<=0)return NaN;if(u>(t+1)/(t+e+2))return 1-gd(1-u,e,t);let r=Math.exp(t*Math.log(u)+e*Math.log(1-u)-$h(t,e)-Math.log(t)),i=1,n=1-(t+e)*u/(t+1);Math.abs(n)<Le&&(n=Le),n=1/n;let s=n;for(let a=1;a<=Lh;a++){let o=a*(e-a)*u/((t+2*a-1)*(t+2*a));n=1+o*n,Math.abs(n)<Le&&(n=Le),i=1+o/i,Math.abs(i)<Le&&(i=Le),n=1/n,s*=i*n,o=-(t+a)*(t+e+a)*u/((t+2*a)*(t+2*a+1)),n=1+o*n,Math.abs(n)<Le&&(n=Le),i=1+o/i,Math.abs(i)<Le&&(i=Le),n=1/n;let c=i*n;if(s*=c,Math.abs(c-1)<Le)break}return r*s}function Oh(u,t,e){return u<=0?0:t<=0||e<=0?NaN:isFinite(u)?gd(t*u/(t*u+e),t/2,e/2):1}function Nh(u,t){let e=t.length,r=u.map((n,s)=>[...n,t[s]]);for(let n=0;n<e;n++){let s=Math.abs(r[n][n]),a=n;for(let o=n+1;o<e;o++){let c=Math.abs(r[o][n]);c>s&&(s=c,a=o)}if(s<Pi)return null;a!==n&&([r[n],r[a]]=[r[a],r[n]]);for(let o=n+1;o<e;o++){let c=r[o][n]/r[n][n];for(let l=n;l<=e;l++)r[o][l]-=c*r[n][l]}}let i=new Array(e).fill(0);for(let n=e-1;n>=0;n--){if(Math.abs(r[n][n])<Pi)return null;let s=r[n][e];for(let a=n+1;a<e;a++)s-=r[n][a]*i[a];i[n]=s/r[n][n]}return i}function md(u,t){let e=t.length,r=u[0].length,i=Array.from({length:r},()=>new Array(r).fill(0));for(let s=0;s<r;s++)for(let a=s;a<r;a++){let o=0;for(let c=0;c<e;c++)o+=u[c][s]*u[c][a];i[s][a]=o,i[a][s]=o}let n=new Array(r).fill(0);for(let s=0;s<r;s++){let a=0;for(let o=0;o<e;o++)a+=u[o][s]*t[o];n[s]=a}return Nh(i,n)}function pd(u,t,e){let r=0;for(let i=0;i<t.length;i++){let n=0;for(let a=0;a<e.length;a++)n+=u[i][a]*e[a];let s=t[i]-n;r+=s*s}return r}function Vh(u,t){let e=Math.max(u.timestamps[0]??1/0,t.timestamps[0]??1/0),r=Math.min(u.timestamps[u.timestamps.length-1]??-1/0,t.timestamps[t.timestamps.length-1]??-1/0);if(e>=r)return null;let i=[];for(let c of[u,t])for(let l=1;l<c.timestamps.length;l++){let d=c.timestamps[l]-c.timestamps[l-1];d>0&&i.push(d)}if(i.length===0)return null;i.sort((c,l)=>c-l);let n=i[Math.floor(i.length/2)];if(n<=0)return null;let s=Math.floor((r-e)/n)+1;if(s<2)return null;let a=new Array(s).fill(0),o=new Array(s).fill(0);for(let[c,l]of[[u,a],[t,o]])for(let d=0;d<c.timestamps.length;d++){let m=Math.round((c.timestamps[d]-e)/n);m>=0&&m<s&&(l[m]=c.outcomes[d])}return{sourceOutcomes:a,targetOutcomes:o}}var ki=class{config;constructor(t){this.config={...Fh,...t}}analyzeCausality(t){if(t.length<2)return[];let e=[];for(let r=0;r<t.length;r++)for(let i=0;i<t.length;i++){if(r===i)continue;let n=t[r],s=t[i];if(n.outcomes.length<this.config.minSeriesLength||s.outcomes.length<this.config.minSeriesLength)continue;let a=null;for(let o=1;o<=this.config.maxLag;o++){let c=this.testPairwise(n,s,o);this.significanceTest(c)&&(a===null||c.pValue<a.pValue)&&(a=c)}a&&e.push(a)}return e.sort((r,i)=>r.pValue-i.pValue),e}testPairwise(t,e,r){let i={sourceTestId:t.testId,targetTestId:e.testId,lag:r,fStatistic:0,pValue:1,strength:0,direction:"positive"},n,s;if(this.arraysEqual(t.timestamps,e.timestamps))n=t.outcomes,s=e.outcomes;else{let G=Vh(t,e);if(!G)return i;n=G.sourceOutcomes,s=G.targetOutcomes}let a=s.length,o=a-r,c=o-2*r-1;if(c<=0||o<this.config.minSeriesLength)return i;let l=new Array(o);for(let G=0;G<o;G++)l[G]=s[G+r];let d=l.reduce((G,ne)=>G+ne,0)/l.length;if(l.reduce((G,ne)=>G+(ne-d)**2,0)<Pi)return i;let m=new Array(o);for(let G=0;G<o;G++){let ne=new Array(r+1);ne[0]=1;for(let X=1;X<=r;X++)ne[X]=s[G+r-X];m[G]=ne}let g=new Array(o);for(let G=0;G<o;G++){let ne=new Array(2*r+1);ne[0]=1;for(let X=1;X<=r;X++)ne[X]=s[G+r-X];for(let X=1;X<=r;X++)ne[r+X]=n[G+r-X];g[G]=ne}let h=md(m,l);if(!h)return i;let b=pd(m,l,h),w=md(g,l);if(!w)return i;let C=pd(g,l,w);if(C>b)return i;let S=(b-C)/r,k=C/c,P=w.slice(r+1,2*r+1),O=P.reduce((G,ne)=>G+Math.abs(ne),0)/r,K=P.reduce((G,ne)=>G+ne,0)/r>=0?"positive":"negative";if(k<Pi){let G=S>Pi?1e6:0;return{...i,fStatistic:G,pValue:G>0?0:1,strength:O,direction:K}}let Ce=S/k,Y=1-Oh(Ce,r,c);return{sourceTestId:t.testId,targetTestId:e.testId,lag:r,fStatistic:Math.max(0,Ce),pValue:Math.max(0,Math.min(1,Y)),strength:O,direction:K}}significanceTest(t){return t.pValue<this.config.alpha&&t.fStatistic>0}arraysEqual(t,e){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++)if(t[r]!==e[r])return!1;return!0}};var _h={maxConcurrentWorkflows:5,defaultTimeout:6e4,enablePatternLearning:!0,publishEvents:!0,autoAnalyzeThreshold:.7,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Ii=R.create("defect-intelligence"),Is=class extends Q{constructor(e,r,i,n={}){let s={..._h,...n};super(e,"defect-intelligence",s,{verifyFindingTypes:["defect-prediction","root-cause","regression-risk","pattern-classification"],...s.consensusConfig});this.memory=r;this.agentCoordinator=i;this.predictor=new dr(r),this.patternLearner=new mr(r),this.rootCauseAnalyzer=new pr(r)}memory;agentCoordinator;predictor;patternLearner;rootCauseAnalyzer;testExecutionHistory=new Map;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState()}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}getDomainWeakVertices(){return this.minCutMixin.getDomainWeakVertices()}onTopologyHealthChange(e){return this.minCutMixin.onTopologyHealthChange(e)}requiresConsensus(e){return this.consensusMixin.requiresConsensus(e)}async verifyFinding(e){return this.consensusMixin.verifyFinding(e)}async predictDefects(e){let r=v();try{if(this.startWorkflow(r,"predict"),this.config.enableMinCutAwareness&&this.minCutMixin.shouldPauseOperations()&&Ii.warn("Topology is critical, proceeding with caution"),!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn prediction agents"));let i=await this.spawnPredictionAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.predictor.predictDefects(e);if(n.success){let s=await this.verifyHighConfidencePredictions(n.value.predictions),a={...n.value,predictions:s};if(this.completeWorkflow(r),this.config.publishEvents&&await this.publishPredictionEvent(a),this.config.enablePatternLearning&&await this.autoAnalyzeHighRisk(a),bt().useGrangerCausality)try{let o=Date.now();for(let l of a.predictions){let d=this.testExecutionHistory.get(l.file)??{timestamps:[],outcomes:[]};d.timestamps.push(o),d.outcomes.push(l.probability>.5?0:1),d.timestamps.length>500&&(d.timestamps.splice(0,d.timestamps.length-500),d.outcomes.splice(0,d.outcomes.length-500)),this.testExecutionHistory.set(l.file,d)}let c=Array.from(this.testExecutionHistory.entries()).filter(([,l])=>l.timestamps.length>=30).map(([l,d])=>({testId:l,timestamps:d.timestamps,outcomes:d.outcomes}));if(c.length>=3){let d=new ki({maxLag:5,alpha:.05}).analyzeCausality(c);d.length>0&&Ii.info("Granger causality found causal links in defect predictions",{linkCount:d.length,historyDepth:c[0].timestamps.length,topLink:`${d[0].sourceTestId} \u2192 ${d[0].targetTestId} (lag=${d[0].lag}, p=${d[0].pValue.toFixed(4)})`})}}catch(o){Ii.warn("Granger causality analysis failed (non-fatal)",{error:o instanceof Error?o.message:"unknown"})}return await this.agentCoordinator.stop(i.value),f(a)}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),{success:!1,error:n}}}async verifyHighConfidencePredictions(e){if(!this.config.enableConsensus)return e;let r=[];for(let i of e)if(i.probability>=this.config.consensusThreshold){let n={id:v(),type:"defect-prediction",confidence:i.probability,severity:i.riskLevel==="critical"||i.riskLevel==="high"?i.riskLevel:"medium",description:`Defect prediction for ${i.file}: ${i.probability*100}% probability`,payload:i,detectedAt:new Date,detectedBy:"defect-intelligence-coordinator"};if(this.consensusMixin.requiresConsensus(n))try{let s=await this.consensusMixin.verifyFinding(n);s.success?s.value.verdict==="verified"?r.push({...i,recommendations:[...i.recommendations,"[Consensus Verified] This prediction has been confirmed by multiple AI models."]}):s.value.verdict==="disputed"&&r.push({...i,probability:i.probability*.6,recommendations:[...i.recommendations,"[Consensus Disputed] This prediction requires human review."]}):r.push(i)}catch{Ii.warn(`Consensus verification failed for ${i.file}`),r.push(i)}else r.push(i)}else r.push(i);return r}async analyzeRootCause(e){let r=v();try{this.startWorkflow(r,"analyze");let i=await this.spawnAnalysisAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.rootCauseAnalyzer.analyzeRootCause(e);if(n.success){let s=await this.verifyRootCauseAnalysis(n.value);return this.completeWorkflow(r),this.config.publishEvents&&await this.publishRootCauseEvent(s),await this.agentCoordinator.stop(i.value),f(s)}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async verifyRootCauseAnalysis(e){if(!this.config.enableConsensus||e.confidence<this.config.consensusThreshold)return e;let r={id:v(),type:"root-cause",confidence:e.confidence,severity:"high",description:`Root cause identified for ${e.defectId}: ${e.rootCause}`,payload:e,detectedAt:new Date,detectedBy:"defect-intelligence-coordinator"};if(this.consensusMixin.requiresConsensus(r))try{let i=await this.consensusMixin.verifyFinding(r);if(i.success)return{...e,recommendations:[...e.recommendations,i.value.verdict==="verified"?"[Consensus Verified] This root cause analysis has been confirmed by multiple AI models.":"[Consensus Disputed] This root cause analysis requires human review."],confidence:i.value.verdict==="verified"?Math.min(1,e.confidence*1.1):e.confidence*.7}}catch{Ii.warn("Consensus verification failed for root cause")}return e}async analyzeRegressionRisk(e){let r=v();try{this.startWorkflow(r,"regression");let i=await this.spawnRegressionAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=await this.predictor.analyzeRegressionRisk(e);return n.success?(this.completeWorkflow(r),this.config.publishEvents&&await this.publishRegressionEvent(n.value)):this.failWorkflow(r,n.error.message),await this.agentCoordinator.stop(i.value),n}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async clusterDefects(e){let r=v();try{this.startWorkflow(r,"cluster");let i=await this.patternLearner.clusterDefects(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async learnPatterns(e){let r=v();try{this.startWorkflow(r,"learn");let i=await this.patternLearner.learnPatterns(e);return i.success?(this.completeWorkflow(r),this.config.publishEvents&&i.value.modelUpdated&&await this.publishPatternLearnedEvent(i.value)):this.failWorkflow(r,i.error.message),i}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async spawnPredictionAgent(e,r){let i={name:`defect-predictor-${e.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["defect-prediction","ml-analysis"],config:{workflowId:e,files:r.files,threshold:r.threshold}};return this.agentCoordinator.spawn(i)}async spawnAnalysisAgent(e,r){let i={name:`root-cause-analyzer-${e.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["root-cause-analysis","symptom-analysis"],config:{workflowId:e,defectId:r.defectId,symptoms:r.symptoms}};return this.agentCoordinator.spawn(i)}async spawnRegressionAgent(e,r){let i={name:`regression-analyzer-${e.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["regression-analysis","impact-analysis"],config:{workflowId:e,changeset:r.changeset,depth:r.depth}};return this.agentCoordinator.spawn(i)}async publishPredictionEvent(e){for(let r of e.predictions)if(r.probability>=this.config.autoAnalyzeThreshold){let i=D(Zi.DefectPredicted,"defect-intelligence",{predictionId:v(),file:r.file,probability:r.probability,factors:r.factors.map(n=>n.name),recommendations:r.recommendations});await this.eventBus.publish(i)}}async publishRootCauseEvent(e){let r=D(Zi.RootCauseIdentified,"defect-intelligence",{analysisId:v(),defectId:e.defectId,rootCause:e.rootCause,confidence:e.confidence,relatedFiles:e.relatedFiles});await this.eventBus.publish(r)}async publishRegressionEvent(e){let r=D(Zi.RegressionRiskAnalyzed,"defect-intelligence",{riskLevel:e.riskLevel,overallRisk:e.overallRisk,impactedAreas:e.impactedAreas.length,recommendedTests:e.recommendedTests.length});await this.eventBus.publish(r)}async publishPatternLearnedEvent(e){let r=D("defect-intelligence.PatternLearned","defect-intelligence",{patternCount:e.patterns.length,modelUpdated:e.modelUpdated,improvementEstimate:e.improvementEstimate});await this.eventBus.publish(r)}async handleTestRunCompleted(e){let r=e.payload;r.failed>0&&this.config.enablePatternLearning&&await this.memory.set(`defect-intelligence:failed-tests:${Date.now()}`,{timestamp:new Date().toISOString(),failedCount:r.failed,testIds:r.testIds},{namespace:"defect-intelligence",ttl:86400*7})}async handleImpactAnalysis(e){let r=e.payload;r.changedFiles.length>3&&await this.analyzeRegressionRisk({changeset:r.changedFiles,depth:"shallow"})}async autoAnalyzeHighRisk(e){let r=e.predictions.filter(i=>i.probability>=this.config.autoAnalyzeThreshold);for(let i of r.slice(0,3))await this.memory.set(`defect-intelligence:high-risk:${i.file}`,{file:i.file,probability:i.probability,factors:i.factors,detectedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("defect-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("defect-intelligence:coordinator:workflows",e,{namespace:"defect-intelligence",persist:!0})}};A();var dc=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;predictor=null;patternLearner=null;rootCauseAnalyzer=null;pluginConfig;get name(){return"defect-intelligence"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{predictDefects:this.predictDefects.bind(this),analyzeRootCause:this.analyzeRootCause.bind(this),analyzeRegressionRisk:this.analyzeRegressionRisk.bind(this),clusterDefects:this.clusterDefects.bind(this),learnPatterns:this.learnPatterns.bind(this),getCoordinator:()=>this.coordinator,getPredictor:()=>this.predictor,getPatternLearner:()=>this.patternLearner,getRootCauseAnalyzer:()=>this.rootCauseAnalyzer}}getTaskHandlers(){return new Map([["predict-defects",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.files,i=e.threshold;return!r||r.length===0?p(new Error("Invalid predict-defects payload: missing files")):this.coordinator.predictDefects({files:r,threshold:i??.7})}],["analyze-root-cause",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.defectId;if(!r)return p(new Error("Invalid analyze-root-cause payload: missing defectId"));let i=e.stackTrace?[e.stackTrace]:e.symptoms??[];return this.coordinator.analyzeRootCause({defectId:r,symptoms:i,context:e.context})}],["analyze-regression-risk",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.changedFiles;return!r||r.length===0?p(new Error("Invalid analyze-regression-risk payload: missing changedFiles")):this.coordinator.analyzeRegressionRisk({changeset:r,baseline:e.commitHash})}],["cluster-defects",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.defects;return!r||r.length===0?p(new Error("Invalid cluster-defects payload: missing defects")):this.coordinator.clusterDefects({defects:r.map(i=>({id:i.id,title:i.title??`Defect ${i.id}`,description:i.description??""})),method:e.method??"semantic"})}],["learn-patterns",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.defectHistory,i=e.defects,n=r??i;return!n||n.length===0?p(new Error("Invalid learn-patterns payload: missing defectHistory")):this.coordinator.learnPatterns({defects:n.map(s=>({id:s.id,title:s.title??`Defect ${s.id}`,description:s.description??""})),includeResolutions:e.includeResolutions})}]])}async onInitialize(){this.predictor=new dr(this.memory,this.pluginConfig.predictor),this.patternLearner=new mr(this.memory,this.pluginConfig.patternLearner),this.rootCauseAnalyzer=new pr(this.memory,this.pluginConfig.rootCauseAnalyzer),this.coordinator=new Is(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,this.predictor=null,this.patternLearner=null,this.rootCauseAnalyzer=null}subscribeToEvents(){this.eventBus.subscribe("test-execution.FlakyTestDetected",this.handleFlakyTest.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-execution.FlakyTestDetected":await this.handleFlakyTest(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;default:break}}async predictDefects(e){this.ensureInitialized();try{let r=await this.coordinator.predictDefects(e);return r.success?this.trackSuccessfulOperation("predict"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async analyzeRootCause(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeRootCause(e);return r.success?this.trackSuccessfulOperation("analyze"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async analyzeRegressionRisk(e){this.ensureInitialized();try{return await this.coordinator.analyzeRegressionRisk(e)}catch(r){return this.handleError(r)}}async clusterDefects(e){this.ensureInitialized();try{return await this.coordinator.clusterDefects(e)}catch(r){return this.handleError(r)}}async learnPatterns(e){this.ensureInitialized();try{let r=await this.coordinator.learnPatterns(e);return r.success&&this.trackSuccessfulOperation("learn"),r}catch(r){return this.handleError(r)}}async handleFlakyTest(e){let r=e.payload;await this.memory.set(`defect-intelligence:flaky-test:${r.testId}`,{...r,detectedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*30}),r.failureRate>.3&&r.testFile&&await this.coordinator?.predictDefects({files:[r.testFile],threshold:.5})}async handleCoverageGap(e){let r=e.payload;r.riskScore>=.7&&await this.memory.set(`defect-intelligence:coverage-gap:${r.gapId}`,{...r,analyzedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}async handleImpactAnalysis(e){let r=e.payload;await this.memory.set(`defect-intelligence:impact:${r.analysisId}`,{...r,recordedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400})}async handleQualityGate(e){let r=e.payload;if(!r.passed){let i=r.checks.filter(n=>!n.passed);await this.memory.set(`defect-intelligence:quality-failure:${r.gateId}`,{failedChecks:i.map(n=>n.name),timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}}ensureInitialized(){if(!this._initialized)throw new Error("DefectIntelligencePlugin is not initialized");if(!this.coordinator||!this.predictor||!this.patternLearner||!this.rootCauseAnalyzer)throw new Error("DefectIntelligencePlugin 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 hd(u,t,e,r){return new dc(u,t,e,r)}M();A();M();A();H();var zh={enableAmbiguityDetection:!0,minAcceptanceCriteria:1,strictMode:!1,forbiddenTermsDefault:[],enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},mc={fast:["within 100ms","under 1 second","response time < 500ms"],quickly:["within 100ms","under 1 second","response time < 500ms"],"user-friendly":["meets WCAG 2.1 AA","usability score > 80","task completion < 3 clicks"],intuitive:["no training required","task completion rate > 90%"],secure:["encrypted with AES-256","authenticated via OAuth2","passes OWASP Top 10"],scalable:["handles 10K concurrent users","horizontal scaling supported"],reliable:["99.9% uptime","MTBF > 1000 hours"],efficient:["O(n) complexity","memory usage < 100MB"],easy:["single click action","no training required"],simple:["single-page workflow","under 5 steps"],flexible:["configurable via settings","supports multiple formats"],robust:["handles edge cases","graceful degradation"],appropriate:["defined by business rules","within acceptable range"],reasonable:["defined threshold","measurable criteria"],adequate:["meets minimum requirements","specified capacity"],good:["measurable quality metric","defined acceptance criteria"],better:["defined improvement metric","baseline comparison"],best:["top-ranked by metric","optimal solution"],several:["specify count: 3-5","defined quantity"],many:["specify count: 10+","defined quantity"],few:["specify count: 2-3","defined quantity"],some:["specify percentage or count","defined subset"],most:["specify percentage > 50%","defined majority"],etc:["complete list","defined scope"],"and/or":["specify condition","boolean logic"]},fd=R.create("requirements-validation/requirements-validator"),gr=class{config;memory;llmRouter;constructor(t,e={}){this.config={...zh,...e},"memory"in t&&typeof t.memory=="object"?(this.memory=t.memory,this.llmRouter=t.llmRouter):this.memory=t}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(t){switch(t){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async analyzeRequirementsWithLLM(t,e){if(!this.isLLMAnalysisAvailable())return f(this.getBasicAnalysis(t));try{let r=this.getModelForTier(this.config.llmModelTier??2),i=this.buildRequirementsAnalysisPrompt(t,e),n=await this.llmRouter.chat({messages:[{role:"system",content:`You are a senior requirements engineer and QA specialist. Analyze requirements for:
2813
2814
  1. Completeness - Are all necessary details present?
2814
2815
  2. Testability - Can acceptance criteria be converted to test cases?
2815
2816
  3. Ambiguity - Are there vague terms that need clarification?
@@ -2844,8 +2845,8 @@ Please analyze these requirements for:
2844
2845
  4. Missing acceptance criteria
2845
2846
  5. General recommendations for improvement`,r}getBasicAnalysis(t){let e=0,r=0,i=[],n=[];for(let o of t){let c=0;o.title&&o.title.length>=5&&(c+=30),o.description&&o.description.length>=20&&(c+=30),o.acceptanceCriteria.length>=1&&(c+=40),e+=c;let l=o.acceptanceCriteria.length>0?50:0;for(let m of o.acceptanceCriteria)(m.toLowerCase().includes("given")||m.toLowerCase().includes("when")||m.toLowerCase().includes("then"))&&(l+=10);l=Math.min(100,l),r+=l;let d=`${o.title} ${o.description}`;for(let m of Object.keys(mc))d.toLowerCase().includes(m)&&i.push({text:m,issue:`Term "${m}" is ambiguous`,suggestion:`Replace with specific criteria like: ${mc[m].slice(0,2).join(" or ")}`});o.acceptanceCriteria.length===0&&n.push(`Add acceptance criteria for "${o.title}" using Given-When-Then format`)}let s=t.length>0?Math.round(e/t.length):0,a=t.length>0?Math.round(r/t.length):0;return{completenessScore:s,testabilityScore:a,ambiguities:i.slice(0,5),missingCriteria:n.slice(0,5),recommendations:["Use Given-When-Then format for acceptance criteria","Replace ambiguous terms with measurable criteria","Include both positive and negative test scenarios"],llmEnhanced:!1}}async storeAnalysisResult(t,e){let r=v();await this.memory.set(`requirements-validation:llm-analysis:${r}`,{requirementIds:t.map(i=>i.id),analysis:e,analyzedAt:new Date().toISOString()},{namespace:"requirements-validation",ttl:86400*7})}async validate(t){try{let e=[];return e.push(...this.validateRequiredFields(t)),e.push(...this.validateAcceptanceCriteria(t)),e.push(...this.validateDescriptionQuality(t)),e.push(...this.validateTitle(t)),e.push(...this.checkForbiddenTerms(t,this.config.forbiddenTermsDefault)),await this.storeValidationResult(t.id,e),f(e)}catch(e){return p(y(e))}}async validateAgainstCriteria(t,e){try{let r=[];e.requireAcceptanceCriteria&&t.acceptanceCriteria.length===0&&r.push({code:"MISSING_AC",message:"Acceptance criteria are required but not provided",severity:"error",suggestion:"Add at least one acceptance criterion using Given-When-Then format"}),r.push(...this.checkForbiddenTerms(t,e.forbiddenTerms));for(let i of e.requiredTags)this.checkForTag(t,i)||r.push({code:"MISSING_TAG",message:`Required tag or keyword missing: ${i}`,severity:"warning",suggestion:`Include ${i} in the requirement or acceptance criteria`});return f(r)}catch(r){return p(y(r))}}async detectAmbiguity(t){try{let e=[],r=`${t.title} ${t.description} ${t.acceptanceCriteria.join(" ")}`,i=r.toLowerCase();for(let[l,d]of Object.entries(mc)){let m=new RegExp(`\\b${l}\\b`,"gi");if(i.match(m)){let h=i.indexOf(l.toLowerCase()),b=Math.max(0,h-30),w=Math.min(r.length,h+l.length+30),C=r.slice(b,w).trim();e.push({term:l,context:`...${C}...`,alternatives:d})}}let n=r.split(/\s+/).length,s=e.length/n,a=Math.round(Math.max(0,100-s*500)),o=this.generateAmbiguitySuggestions(e),c={ambiguousTerms:e,overallScore:a,suggestions:o};return await this.memory.set(`requirements-validation:ambiguity:${t.id}`,c,{namespace:"requirements-validation",ttl:86400}),f(c)}catch(e){return p(y(e))}}async analyzeDependencies(t){try{let e=t.map(s=>({id:s.id,title:s.title,type:s.type})),r=[];for(let s of t){let a=this.extractDependencies(s,t);r.push(...a)}let i={nodes:e,edges:r},n=v();return await this.memory.set(`requirements-validation:dependency-graph:${n}`,i,{namespace:"requirements-validation",persist:!0}),f(i)}catch(e){return p(y(e))}}validateRequiredFields(t){let e=[];return t.id||e.push({code:"MISSING_ID",message:"Requirement ID is missing",severity:"error"}),(!t.title||t.title.trim().length===0)&&e.push({code:"MISSING_TITLE",message:"Requirement title is missing or empty",severity:"error",suggestion:"Add a clear, concise title that summarizes the requirement"}),(!t.description||t.description.trim().length===0)&&e.push({code:"MISSING_DESCRIPTION",message:"Requirement description is missing or empty",severity:"error",suggestion:"Add a detailed description of what should be implemented"}),e}validateAcceptanceCriteria(t){let e=[];t.acceptanceCriteria.length<this.config.minAcceptanceCriteria&&e.push({code:"INSUFFICIENT_AC",message:`Requirement has ${t.acceptanceCriteria.length} acceptance criteria, minimum is ${this.config.minAcceptanceCriteria}`,severity:this.config.strictMode?"error":"warning",suggestion:"Add acceptance criteria using Given-When-Then format for testability"});for(let r=0;r<t.acceptanceCriteria.length;r++){let i=t.acceptanceCriteria[r];i.length<10&&e.push({code:"AC_TOO_SHORT",message:`Acceptance criterion ${r+1} is too short to be meaningful`,severity:"warning",suggestion:"Expand the criterion with specific, testable conditions"}),!(i.toLowerCase().includes("given")||i.toLowerCase().includes("when")||i.toLowerCase().includes("then"))&&this.config.strictMode&&e.push({code:"AC_NOT_GWT",message:`Acceptance criterion ${r+1} does not follow Given-When-Then format`,severity:"info",suggestion:"Consider using Given-When-Then format for better testability"})}return e}validateDescriptionQuality(t){let e=[],r=t.description;return r.length<20&&e.push({code:"DESC_TOO_SHORT",message:"Description is too short to provide sufficient detail",severity:"warning",suggestion:"Expand the description to include context, purpose, and expected behavior"}),t.type==="user-story"&&(r.toLowerCase().includes("as a")||r.toLowerCase().includes("i want")||r.toLowerCase().includes("so that")||e.push({code:"NOT_USER_STORY_FORMAT",message:'User story does not follow "As a...I want...So that" format',severity:"warning",suggestion:'Use format: "As a [role], I want [feature] so that [benefit]"'})),e}validateTitle(t){let e=[],r=t.title;return r.length<5&&e.push({code:"TITLE_TOO_SHORT",message:"Title is too short to be descriptive",severity:"warning"}),r.length>100&&e.push({code:"TITLE_TOO_LONG",message:"Title is too long, consider summarizing",severity:"info",suggestion:"Keep title under 100 characters and move details to description"}),!["add","create","implement","enable","allow","support","provide","display","show","update","delete","remove","fix","improve","optimize"].some(s=>r.toLowerCase().startsWith(s))&&this.config.strictMode&&e.push({code:"NO_ACTION_VERB",message:"Title should start with an action verb",severity:"info",suggestion:"Start with verbs like: Add, Create, Implement, Enable, Support"}),e}checkForbiddenTerms(t,e){let r=[],i=`${t.title} ${t.description} ${t.acceptanceCriteria.join(" ")}`;for(let n of e)i.toLowerCase().includes(n.toLowerCase())&&r.push({code:"FORBIDDEN_TERM",message:`Forbidden term found: "${n}"`,severity:"error",suggestion:`Remove or replace the term "${n}" with a more specific alternative`});return r}checkForTag(t,e){return`${t.title} ${t.description} ${t.acceptanceCriteria.join(" ")}`.toLowerCase().includes(e.toLowerCase())}generateAmbiguitySuggestions(t){let e=[];if(t.length===0)return e.push("Requirement language is clear and specific"),e;for(let r of t.slice(0,3))e.push(`Replace "${r.term}" with specific criteria like: ${r.alternatives.slice(0,2).join(" or ")}`);return t.length>3&&e.push(`${t.length-3} additional ambiguous terms found. Consider reviewing the full ambiguity report.`),e}extractDependencies(t,e){let r=[],n=`${t.description} ${t.acceptanceCriteria.join(" ")}`.toLowerCase(),s=[/depends on\s+(\w+[-\d]*)/gi,/requires\s+(\w+[-\d]*)/gi,/after\s+(\w+[-\d]*)/gi,/blocked by\s+(\w+[-\d]*)/gi];for(let o of s){let c;for(;(c=o.exec(n))!==null;){let l=c[1],d=e.find(m=>m.id.toLowerCase()===l||m.title.toLowerCase().includes(l));d&&d.id!==t.id&&r.push({from:t.id,to:d.id,type:"depends-on"})}}let a=[/related to\s+(\w+[-\d]*)/gi,/see also\s+(\w+[-\d]*)/gi];for(let o of a){let c;for(;(c=o.exec(n))!==null;){let l=c[1],d=e.find(m=>m.id.toLowerCase()===l||m.title.toLowerCase().includes(l));d&&d.id!==t.id&&r.push({from:t.id,to:d.id,type:"related-to"})}}return r}async storeValidationResult(t,e){await this.memory.set(`requirements-validation:result:${t}`,{requirementId:t,errors:e,validatedAt:new Date().toISOString(),errorCount:e.filter(r=>r.severity==="error").length,warningCount:e.filter(r=>r.severity==="warning").length},{namespace:"requirements-validation",ttl:86400*7})}};A();var Bh={defaultExampleCount:3,includeBackgroundScenarios:!0,generateNegativeScenarios:!0,maxScenariosPerRequirement:10},hr=class{constructor(t,e={}){this.memory=t;this.config={...Bh,...e}}memory;config;async generateScenarios(t){try{let e=[],r=this.extractFeatureName(t);for(let s of t.acceptanceCriteria){let a=this.generateScenarioFromCriteria(r,s,t);a&&e.push(a)}let i=this.generateAdditionalScenarios(t,r);if(e.push(...i),this.config.generateNegativeScenarios){let s=this.generateNegativeScenarios(t,r);e.push(...s)}let n=e.slice(0,this.config.maxScenariosPerRequirement);return await this.storeScenarios(t.id,n),f(n)}catch(e){return p(y(e))}}async generateScenariosWithExamples(t,e){try{let r=await this.generateScenarios(t);if(!r.success)return r;let i=r.value.map(n=>{let s=this.generateExamplesForScenario(n,e);return{...n,examples:s}});return f(i)}catch(r){return p(y(r))}}toGherkin(t){if(t.length===0)return"";let e=t[0].feature,r=[];r.push(`Feature: ${e}`),r.push("");let i=this.groupScenariosByTags(t);for(let n of i){n.tags.length>0&&r.push(` ${n.tags.map(o=>`@${o}`).join(" ")}`);let s=n.examples&&n.examples.rows.length>0,a=s?"Scenario Outline":"Scenario";r.push(` ${a}: ${n.scenario}`);for(let o=0;o<n.given.length;o++){let c=o===0?"Given":"And";r.push(` ${c} ${n.given[o]}`)}for(let o=0;o<n.when.length;o++){let c=o===0?"When":"And";r.push(` ${c} ${n.when[o]}`)}for(let o=0;o<n.then.length;o++){let c=o===0?"Then":"And";r.push(` ${c} ${n.then[o]}`)}if(s&&n.examples){r.push(""),r.push(" Examples:"),r.push(` | ${n.examples.headers.join(" | ")} |`);for(let o of n.examples.rows)r.push(` | ${o.join(" | ")} |`)}r.push("")}return r.join(`
2846
2847
  `)}parseGherkin(t){try{let e=[],r=t.split(`
2847
- `).map(c=>c.trim()),i="",n=null,s=[],a=null,o=null;for(let c of r)if(!(!c||c.startsWith("#"))){if(c.startsWith("@")){s=c.split(/\s+/).map(l=>l.replace("@",""));continue}if(c.startsWith("Feature:")){i=c.replace("Feature:","").trim();continue}if(c.startsWith("Scenario:")||c.startsWith("Scenario Outline:")){n&&(o&&(n.examples=o),e.push(this.convertToReadonly(n)));let l=c.replace("Scenario Outline:","").replace("Scenario:","").trim();n={id:v(),feature:i,scenario:l,given:[],when:[],then:[],tags:[...s]},s=[],a=null,o=null;continue}if(c.startsWith("Given"))a="given",n?.given.push(c.replace("Given","").trim());else if(c.startsWith("When"))a="when",n?.when.push(c.replace("When","").trim());else if(c.startsWith("Then"))a="then",n?.then.push(c.replace("Then","").trim());else if(c.startsWith("And")&&a&&n&&a!=="examples"){let l=c.replace("And","").trim();n[a].push(l)}else if(c.startsWith("But")&&a&&n&&a!=="examples"){let l=c.replace("But","").trim();n[a].push(l)}if(c.startsWith("Examples:")){a="examples",o={headers:[],rows:[]};continue}if(c.startsWith("|")&&o){let l=c.split("|").slice(1,-1).map(d=>d.trim());o.headers.length===0?o.headers=l:o.rows.push(l)}}return n&&(o&&(n.examples=o),e.push(this.convertToReadonly(n))),f(e)}catch(e){return p(y(e))}}convertToReadonly(t){return{id:t.id,feature:t.feature,scenario:t.scenario,given:t.given,when:t.when,then:t.then,tags:t.tags,examples:t.examples}}generateScenarioFromCriteria(t,e,r){let i=/given\s+(.+?)\s+when\s+(.+?)\s+then\s+(.+?)(?:\s+and\s+(.+))?$/i,n=e.match(i);return n?{id:v(),feature:t,scenario:this.extractScenarioTitle(e),given:[n[1].trim()],when:[n[2].trim()],then:n[4]?[n[3].trim(),n[4].trim()]:[n[3].trim()],tags:this.inferTags(r)}:this.generateScenarioFromPlainText(t,e,r)}generateScenarioFromPlainText(t,e,r){let i=[],n=[],s=[],a=e.toLowerCase();return r.type==="user-story"?i.push("the user is authenticated"):r.type==="functional"?i.push("the system is in a valid state"):i.push("the preconditions are met"),a.includes("click")||a.includes("press")?n.push("the user performs the action"):a.includes("enter")||a.includes("input")?n.push("the user provides the required input"):a.includes("submit")||a.includes("send")?n.push("the user submits the form"):a.includes("select")||a.includes("choose")?n.push("the user makes a selection"):n.push("the action is performed"),a.includes("display")||a.includes("show")?s.push("the expected content is displayed"):a.includes("save")||a.includes("store")?s.push("the data is persisted correctly"):a.includes("error")||a.includes("fail")?s.push("an appropriate error message is shown"):a.includes("redirect")||a.includes("navigate")?s.push("the user is redirected to the expected page"):a.includes("notify")||a.includes("email")?s.push("a notification is sent"):s.push("the expected outcome is achieved"),{id:v(),feature:t,scenario:this.extractScenarioTitle(e),given:i,when:n,then:s,tags:this.inferTags(r)}}generateAdditionalScenarios(t,e){let r=[];switch(t.type){case"user-story":r.push(this.createScenario(e,"First-time user flow",t,{given:["a new user visits the application"],when:["they complete the onboarding process"],then:["they can access the main features"]}));break;case"non-functional":(t.description.toLowerCase().includes("performance")||t.description.toLowerCase().includes("speed"))&&r.push(this.createScenario(e,"Performance under load",t,{given:["the system is under normal load"],when:["100 concurrent users perform operations"],then:["response time remains under threshold"]}));break;case"technical":r.push(this.createScenario(e,"System integration",t,{given:["all dependent services are available"],when:["the system initializes"],then:["all integrations are established successfully"]}));break}return r}generateNegativeScenarios(t,e){let r=[];return r.push(this.createScenario(e,"Invalid input handling",t,{given:["the user is on the input form"],when:["they submit invalid data"],then:["validation errors are displayed","the form is not submitted"],tags:["negative","validation"]})),(t.type==="user-story"||t.type==="functional")&&r.push(this.createScenario(e,"Unauthorized access attempt",t,{given:["the user is not authenticated"],when:["they attempt to access protected resources"],then:["access is denied","a login prompt is displayed"],tags:["negative","security"]})),r.push(this.createScenario(e,"Error recovery",t,{given:["an error has occurred during operation"],when:["the user attempts to recover"],then:["the system returns to a valid state","no data is lost"],tags:["negative","error-handling"]})),r}createScenario(t,e,r,i){return{id:v(),feature:t,scenario:e,given:i.given,when:i.when,then:i.then,tags:i.tags||this.inferTags(r)}}extractFeatureName(t){return t.title.replace(/^(as a|i want|enable|implement|add|create)\s+/i,"").trim()}extractScenarioTitle(t){let r=t.split(/\s+/).slice(0,8).join(" ");return r.length>60&&(r=r.slice(0,57)+"..."),r.charAt(0).toUpperCase()+r.slice(1)}inferTags(t){let e=[];e.push(t.type),e.push(`priority-${t.priority}`);let r=`${t.title} ${t.description}`.toLowerCase();return(r.includes("api")||r.includes("endpoint"))&&e.push("api"),(r.includes("ui")||r.includes("interface")||r.includes("display"))&&e.push("ui"),(r.includes("database")||r.includes("persist")||r.includes("storage"))&&e.push("database"),(r.includes("security")||r.includes("auth")||r.includes("permission"))&&e.push("security"),(r.includes("performance")||r.includes("speed")||r.includes("fast"))&&e.push("performance"),e}generateExamplesForScenario(t,e){let r=new Set,i=/<(\w+)>/g,n=[...t.given,...t.when,...t.then];for(let o of n){let c;for(;(c=i.exec(o))!==null;)r.add(c[1])}let s=r.size>0?Array.from(r):["input","expected_result"],a=[];for(let o=0;o<e;o++){let c=s.map(l=>this.generateExampleValue(l,o));a.push(c)}return{headers:s,rows:a}}generateExampleValue(t,e){let r=t.toLowerCase();if(r.includes("name")||r.includes("user"))return`test_user_${e+1}`;if(r.includes("email"))return`user${e+1}@example.com`;if(r.includes("password"))return e===0?"ValidPass123!":e===1?"short":"";if(r.includes("amount")||r.includes("price"))return String((e+1)*100);if(r.includes("count")||r.includes("quantity"))return String(e+1);if(r.includes("date")){let i=new Date;return i.setDate(i.getDate()+e),i.toISOString().split("T")[0]}return r.includes("result")||r.includes("expected")?e===0?"success":e===1?"failure":"error":r.includes("status")?["active","pending","inactive"][e]||"unknown":`value_${e+1}`}groupScenariosByTags(t){return[...t].sort((e,r)=>{let i=e.tags.includes("negative"),n=r.tags.includes("negative");return i!==n?i?1:-1:e.scenario.localeCompare(r.scenario)})}async storeScenarios(t,e){await this.memory.set(`requirements-validation:scenarios:${t}`,{requirementId:t,scenarios:e,generatedAt:new Date().toISOString(),count:e.length},{namespace:"requirements-validation",persist:!0})}};A();var yd={specificity:.2,measurability:.25,atomicity:.15,feasibility:.15,traceability:.1,independency:.15},qh={defaultThreshold:60,weights:yd,enableAIScoring:!1},fr=class{constructor(t,e={}){this.memory=t;this.config={...qh,...e,weights:{...yd,...e.weights}}}memory;config;async scoreRequirement(t){try{let e=[];e.push(this.scoreSpecificity(t)),e.push(this.scoreMeasurability(t)),e.push(this.scoreAtomicity(t)),e.push(this.scoreFeasibility(t)),e.push(this.scoreTraceability(t)),e.push(this.scoreIndependency(t));let r=e.reduce((o,c)=>o+c.weight,0),i=e.reduce((o,c)=>o+c.score*c.weight,0),n=Math.round(i/r),s=this.categorizeScore(n),a={value:n,category:s,factors:e};return await this.storeScore(t.id,a),f(a)}catch(e){return p(y(e))}}async scoreRequirements(t){try{let e=new Map;for(let r of t){let i=await this.scoreRequirement(r);i.success&&e.set(r.id,i.value)}return f(e)}catch(e){return p(y(e))}}async suggestImprovements(t,e){try{let r=[],i=[...e.factors].sort((s,a)=>s.score-a.score);for(let s of i){if(s.score<70){let a=this.getSuggestionsForFactor(s,t);r.push(...a)}for(let a of s.issues)r.push(`Fix: ${a}`)}e.value<50?(r.push("Consider rewriting the requirement with clearer, more specific language"),r.push("Add measurable acceptance criteria using Given-When-Then format")):e.value<70&&r.push("Add quantifiable metrics where possible (response times, limits, thresholds)");let n=[...new Set(r)];return f(n.slice(0,10))}catch(r){return p(y(r))}}meetsThreshold(t,e){return t.value>=e}scoreSpecificity(t){let e=100,r=[],i=`${t.title} ${t.description} ${t.acceptanceCriteria.join(" ")}`,n=i.toLowerCase(),s=["fast","quickly","efficient","user-friendly","intuitive","simple","easy","flexible","robust","appropriate","reasonable","adequate","good","better","best","several","many","few","some","most","etc"];for(let c of s)n.includes(c)&&(e-=8,r.push(`Contains ambiguous term: "${c}"`));return/\d+/.test(i)||(e-=15,r.push("No specific numbers or metrics provided")),/\b(user|admin|system|customer|developer)\b/i.test(i)||(e-=10,r.push("No clear actor/subject specified")),t.description.length<50&&(e-=10,r.push("Description is too brief for specificity")),{name:"Specificity",score:Math.max(0,e),weight:this.config.weights.specificity,issues:r}}scoreMeasurability(t){let e=100,r=[],i=`${t.description} ${t.acceptanceCriteria.join(" ")}`,n=i.toLowerCase();[/\d+\s*(ms|seconds?|minutes?|hours?)/i,/\d+\s*%/,/\d+\s*(users?|requests?|transactions?)/i,/\d+\s*(mb|gb|kb)/i,/(less than|more than|at least|maximum|minimum)\s*\d+/i,/\b(must|shall|should)\b.*\b(be|have|support)\b/i].some(c=>c.test(i))||(e-=25,r.push("No measurable criteria found")),t.acceptanceCriteria.length===0?(e-=30,r.push("No acceptance criteria defined")):t.acceptanceCriteria.filter(l=>{let d=l.toLowerCase();return/\bthen\b/i.test(l)||/\b(verify|confirm|check|ensure|assert)\b/i.test(d)||/\b(should|must|shall)\b/i.test(d)}).length<t.acceptanceCriteria.length*.5&&(e-=15,r.push("Less than half of acceptance criteria are clearly verifiable"));let o=["looks good","feels right","works well","properly"];for(let c of o)n.includes(c)&&(e-=10,r.push(`Contains subjective term: "${c}"`));return{name:"Measurability",score:Math.max(0,e),weight:this.config.weights.measurability,issues:r}}scoreAtomicity(t){let e=100,r=[],n=t.description.toLowerCase(),s=[/\band\b.*\band\b/i,/\bor\b/i,/\bas well as\b/i,/\bin addition\b/i,/\balso\b/i,/\bfurthermore\b/i];for(let c of s)if(c.test(n)){e-=12,r.push("Contains compound statements that may need splitting");break}t.acceptanceCriteria.length>7&&(e-=15,r.push("Too many acceptance criteria - consider splitting requirement"));let a=["feature","capability","function","ability"],o=0;for(let c of a){let l=n.match(new RegExp(c,"g"));l&&(o+=l.length)}return o>2&&(e-=15,r.push("Multiple features/capabilities mentioned - may not be atomic")),t.description.length>500&&(e-=10,r.push("Description length suggests requirement may not be atomic")),{name:"Atomicity",score:Math.max(0,e),weight:this.config.weights.atomicity,issues:r}}scoreFeasibility(t){let e=100,r=[],n=`${t.description} ${t.acceptanceCriteria.join(" ")}`.toLowerCase(),s=[/100%\s*(availability|uptime|coverage)/i,/zero\s*(defects?|bugs?|errors?)/i,/never\s+(fail|crash|error)/i,/always\s+work/i,/infinite/i,/unlimited/i];for(let o of s)if(o.test(n)){e-=20,r.push("Contains unrealistic or impossible to verify conditions");break}let a=["third-party","external service","external api","hardware","physical","manual"];for(let o of a)n.includes(o)&&(e-=10,r.push(`Testing complicated by external dependency: ${o}`));return/real-time|real time/i.test(n)&&(e-=5,r.push("Real-time requirements require specialized testing")),/compliance|regulation|legal|gdpr|hipaa/i.test(n)&&(e-=5,r.push("Compliance testing may require specialized expertise")),{name:"Feasibility",score:Math.max(0,e),weight:this.config.weights.feasibility,issues:r}}scoreTraceability(t){let e=100,r=[];return(!t.id||t.id.trim()==="")&&(e-=30,r.push("Requirement lacks a unique identifier")),t.title.length<10&&(e-=15,r.push("Title is too short for effective traceability")),t.type||(e-=15,r.push("Requirement type not specified")),t.priority||(e-=10,r.push("Requirement priority not specified")),t.acceptanceCriteria.filter(n=>/\[AC[-\d]+\]|#\d+|AC\d+/i.test(n)).length===0&&t.acceptanceCriteria.length>0&&(e-=10,r.push("Acceptance criteria lack identifiers for test traceability")),{name:"Traceability",score:Math.max(0,e),weight:this.config.weights.traceability,issues:r}}scoreIndependency(t){let e=100,r=[],i=`${t.description} ${t.acceptanceCriteria.join(" ")}`,n=i.toLowerCase(),s=[/depends on/i,/requires\s+(that|the)/i,/after\s+(the|completing)/i,/following\s+completion/i,/prerequisite/i,/blocked by/i];for(let c of s)if(c.test(n)){e-=15,r.push("Has explicit dependencies that complicate isolated testing");break}let a=[/REQ[-_]?\d+/gi,/requirement\s+\d+/gi,/see\s+(also|requirement)/i,/as described in/i];for(let c of a)if(c.test(i)){e-=10,r.push("References other requirements");break}let o=["global state","shared","common data","same session","across all","system-wide"];for(let c of o)if(n.includes(c)){e-=10,r.push(`Involves shared state: "${c}"`);break}return{name:"Independency",score:Math.max(0,e),weight:this.config.weights.independency,issues:r}}categorizeScore(t){return t>=80?"excellent":t>=60?"good":t>=40?"fair":"poor"}getSuggestionsForFactor(t,e){let r=[];switch(t.name){case"Specificity":r.push("Replace ambiguous terms with specific, measurable values"),r.push("Define clear actors (user, system, admin) for each action"),r.push("Add concrete examples or scenarios");break;case"Measurability":r.push("Add quantifiable acceptance criteria (time limits, percentages)"),r.push("Use Given-When-Then format for each acceptance criterion"),r.push("Define success/failure conditions explicitly");break;case"Atomicity":r.push("Split compound requirements into separate, focused items"),r.push("Each requirement should describe one testable behavior"),r.push('Remove "and" chains by creating separate requirements');break;case"Feasibility":r.push("Replace absolute terms (100%, never, always) with realistic thresholds"),r.push("Document test environment requirements for external dependencies"),r.push("Consider mock/stub strategies for third-party integrations");break;case"Traceability":r.push("Ensure requirement has a unique, persistent identifier"),r.push("Add identifiers to each acceptance criterion (e.g., AC-1, AC-2)"),r.push("Link to related design documents or user stories");break;case"Independency":r.push("Document dependencies explicitly for test planning"),r.push("Consider if the requirement can be broken down to reduce dependencies"),r.push("Design tests that can run in isolation with proper setup/teardown");break}return r}async storeScore(t,e){await this.memory.set(`requirements-validation:testability:${t}`,{requirementId:t,score:e,scoredAt:new Date().toISOString()},{namespace:"requirements-validation",ttl:86400*30});let r=`requirements-validation:testability-trend:${t}`,n=await this.memory.get(r)||{scores:[]};n.scores.push({score:e.value,date:new Date().toISOString()}),n.scores.length>10&&(n.scores=n.scores.slice(-10)),await this.memory.set(r,n,{namespace:"requirements-validation",persist:!0})}};se();var Gh={stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],clipEpsilon:.2,lambdaGAE:.95,epochs:4,miniBatchSize:64,entropyCoeff:.01},Ds=class extends ae{actor;critic;oldActor;ppoConfig;actions=[];constructor(t={}){super("ppo","actor-critic"),this.ppoConfig={...Gh,...t},this.initializeActions(),this.actor=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.actorHiddenLayers,this.ppoConfig.actionSize],activations:Array(this.ppoConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.criticHiddenLayers,1],activations:Array(this.ppoConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.oldActor=this.actor.clone()}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.actor.forward(e),i=pe.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:`PPO: ${s.type}`}}async trainCore(t){this.oldActor=this.actor.clone();let e=this.calculateAdvantages(t),r=0;for(let i=0;i<this.ppoConfig.epochs;i++)for(let n=0;n<t.length;n+=this.ppoConfig.miniBatchSize){let s=Math.min(n+this.ppoConfig.miniBatchSize,t.length);for(let a=n;a<s;a++){let o=t[a],c=this.prepareState(o.state),l=this.actionToIndex(o.action),d=e[a]||0,m=this.actor.forward(c),g=pe.forward(m),h=this.oldActor.forward(c),b=pe.forward(h),w=(g[l]+1e-10)/(b[l]+1e-10),C=Math.max(1-this.ppoConfig.clipEpsilon,Math.min(1+this.ppoConfig.clipEpsilon,w)),S=w*d,P=C*d,k=-Math.min(S,P),O=this.critic.forward(c)[0],z=o.reward+this.config.discountFactor*(this.critic.forward(this.prepareState(o.nextState))[0]||0),K=(O-z)**2,Ce=this.calculateEntropy(g),Y=-this.ppoConfig.entropyCoeff*Ce;r+=Math.abs(k+.5*K+Y);let G=new Float32Array(g.length);for(let X=0;X<G.length;X++)G[X]=X===l?-d:0;this.actor.backward(G);for(let X of this.actor.layers)X.update(this.config.learningRate*.1);let ne=new Float32Array([z]);this.critic.train(c,ne,new fe)}}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/(t.length*this.ppoConfig.epochs),explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural PPO for Adaptive Retry Strategies",capabilities:["Clipped surrogate objective","GAE advantage estimation","Multiple epochs per batch"],hyperparameters:{stateSize:this.ppoConfig.stateSize,actionSize:this.ppoConfig.actionSize,clipEpsilon:this.ppoConfig.clipEpsilon,epochs:this.ppoConfig.epochs},stats:this.stats}}calculateAdvantages(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--){let n=t[i],s=this.prepareState(n.state),a=this.prepareState(n.nextState),o=this.critic.forward(s)[0],c=n.done?0:this.critic.forward(a)[0];r=n.reward+this.config.discountFactor*c-o+this.config.discountFactor*this.ppoConfig.lambdaGAE*r,e.unshift(r)}return e}prepareState(t){let e=t.features.slice(0,this.ppoConfig.stateSize);for(;e.length<this.ppoConfig.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:"retry",value:1},{type:"retry",value:2},{type:"retry",value:3},{type:"skip-retry",value:0},{type:"adjust-timeout",value:1.5}],this.ppoConfig.actionSize=this.actions.length,this.actor=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.actorHiddenLayers,this.ppoConfig.actionSize],activations:Array(this.ppoConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.criticHiddenLayers,1],activations:Array(this.ppoConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.oldActor=this.actor.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}sampleAction(t){if(L()<this.config.explorationRate)return le(0,this.actions.length);let e=L(),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(),ppoConfig:this.ppoConfig}}async importCustomData(t){t.actor&&this.actor.setParameters(t.actor),t.critic&&this.critic.setParameters(t.critic),t.ppoConfig&&(this.ppoConfig={...this.ppoConfig,...t.ppoConfig}),this.initialized=!0}async resetAlgorithm(){this.actor=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.actorHiddenLayers,this.ppoConfig.actionSize],activations:Array(this.ppoConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.criticHiddenLayers,1],activations:Array(this.ppoConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.oldActor=this.actor.clone()}};var Ms={RequirementAnalyzed:"requirements-validation.RequirementAnalyzed",BDDScenariosGenerated:"requirements-validation.BDDScenariosGenerated",RequirementValidated:"requirements-validation.RequirementValidated",SprintValidated:"requirements-validation.SprintValidated",ValidationFailed:"requirements-validation.ValidationFailed"},Hh={maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,minTestabilityThreshold:60,enablePPO:!0,enableSONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},pc=class{constructor(t){this.memory=t}memory;requirements=new Map;async findById(t){if(this.requirements.has(t))return this.requirements.get(t)||null;let e=await this.memory.get(`requirement:${t}`);return e?(this.requirements.set(t,e),e):null}async findByStatus(t){return Array.from(this.requirements.values()).filter(e=>e.status===t)}async findByPriority(t){return Array.from(this.requirements.values()).filter(e=>e.priority===t)}async save(t){this.requirements.set(t.id,t),await this.memory.set(`requirement:${t.id}`,t,{namespace:"requirements-validation",persist:!0})}async delete(t){this.requirements.delete(t),await this.memory.delete(`requirement:${t}`)}},Se=R.create("requirements-validation"),Fs=class extends Q{constructor(e,r,i,n={}){let s={...Hh,...n};super(e,"requirements-validation",s,{verifyFindingTypes:["requirement-conflict","testability-assessment","ambiguous-requirement"]});this.memory=r;this.agentCoordinator=i;this.validator=new gr(r),this.bddWriter=new hr(r),this.testabilityScorer=new fr(r),this.repository=new pc(r)}memory;agentCoordinator;validator;bddWriter;testabilityScorer;repository;ppoAlgorithm;sonaEngine;rlInitialized=!1;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enablePPO||this.config.enableSONA)&&await this.initializeRLIntegrations()}async initializeRLIntegrations(){try{if(this.config.enablePPO&&(this.ppoAlgorithm=new Ds({stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],clipEpsilon:.2,lambdaGAE:.95,epochs:10,miniBatchSize:32,entropyCoeff:.01})),this.config.enableSONA)try{this.sonaEngine=await me({domain:"requirements-validation",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),Se.info("PersistentSONAEngine initialized for pattern learning")}catch(e){Se.error("Failed to initialize PersistentSONAEngine",e instanceof Error?e:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(e){throw Se.error("Failed to initialize RL integrations",e instanceof Error?e:void 0),e}}async onDispose(){if(await this.saveWorkflowState(),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(e){Se.error("Error closing SONA engine",e instanceof Error?e:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async analyzeRequirement(e){let r=v();try{if(this.startWorkflow(r,"analyze"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Se.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Operation paused: topology is in critical state"));let i=await this.repository.findById(e);if(!i)return p(new Error(`Requirement not found: ${e}`));if(this.config.enableSONA&&this.sonaEngine){let d=await this.adaptRequirementPattern(i);d.success&&d.pattern&&Se.info(`[SONA] Adapted pattern with ${d.similarity.toFixed(3)} similarity`)}let n=await this.spawnAnalysisAgent(r,i);if(!n.success)return this.failWorkflow(r,n.error.message),p(n.error);this.addAgentToWorkflow(r,n.value),this.updateWorkflowProgress(r,10);let s=await this.validator.validate(i);if(!s.success)return this.failWorkflow(r,s.error.message),p(s.error);this.updateWorkflowProgress(r,30);let a=await this.testabilityScorer.scoreRequirement(i);if(!a.success)return this.failWorkflow(r,a.error.message),p(a.error);this.updateWorkflowProgress(r,50);let o=await this.validator.detectAmbiguity(i);if(!o.success)return this.failWorkflow(r,o.error.message),p(o.error);this.updateWorkflowProgress(r,70);let c=await this.testabilityScorer.suggestImprovements(i,a.value);this.updateWorkflowProgress(r,90);let l={requirement:i,testabilityScore:a.value,validationErrors:s.value,ambiguityReport:o.value,suggestedImprovements:c.success?c.value:[]};return this.config.enableSONA&&this.sonaEngine&&await this.storeRequirementPattern(i,a.value.value,l),await this.agentCoordinator.stop(n.value),this.completeWorkflow(r),this.config.publishEvents&&await this.publishRequirementAnalyzed(l),f(l)}catch(i){let n=y(i);return this.failWorkflow(r,n.message),this.config.publishEvents&&await this.publishValidationFailed(n,"analyzeRequirement"),{success:!1,error:n}}}async generateTestArtifacts(e){let r=v();try{this.startWorkflow(r,"generate-artifacts");let i=await this.repository.findById(e);if(!i)return p(new Error(`Requirement not found: ${e}`));let n=await this.spawnBDDAgent(r,i);if(!n.success)return this.failWorkflow(r,n.error.message),p(n.error);this.addAgentToWorkflow(r,n.value),this.updateWorkflowProgress(r,20);let s=3;if(this.config.enablePPO&&this.ppoAlgorithm){let g=await this.optimizeScenarioGeneration(i);g.success&&g.value&&(s=this.extractScenarioCount(g.value),Se.info(`[PPO] Optimized scenario count to ${s}`))}let a=await this.bddWriter.generateScenariosWithExamples(i,s);if(!a.success)return this.failWorkflow(r,a.error.message),p(a.error);this.updateWorkflowProgress(r,50);let o=a.value;this.config.enablePPO&&this.ppoAlgorithm&&(o=await this.optimizeScenarioOrdering(i,o));let c=this.bddWriter.toGherkin(o),l={path:`features/${this.sanitizeFilename(i.title)}.feature`,content:c,scenarioCount:o.length};this.updateWorkflowProgress(r,70);let d=this.generateTestCaseOutlines(i,o);this.updateWorkflowProgress(r,90);let m={requirementId:e,bddScenarios:o,gherkinFiles:[l],testCaseOutlines:d};return this.config.enablePPO&&this.ppoAlgorithm&&await this.trainPPOWithScenarioFeedback(i,o,m),await this.agentCoordinator.stop(n.value),this.completeWorkflow(r),this.config.publishEvents&&await this.publishBDDScenariosGenerated(e,o),f(m)}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async validateSprintRequirements(e){let r=v();try{this.startWorkflow(r,"validate-sprint");let i=[];for(let g of e){let h=await this.repository.findById(g);h&&i.push(h)}if(i.length===0)return p(new Error("No requirements found for the specified IDs"));this.updateWorkflowProgress(r,10);let n=await this.testabilityScorer.scoreRequirements(i);if(!n.success)return this.failWorkflow(r,n.error.message),p(n.error);this.updateWorkflowProgress(r,40);let s=new Map;for(let g of i){let h=await this.validator.validate(g);h.success&&s.set(g.id,h.value)}this.updateWorkflowProgress(r,70);let a=await this.validator.analyzeDependencies(i);this.updateWorkflowProgress(r,80);let o=[],c=0,l=0;for(let g of i){let h=n.value.get(g.id),b=s.get(g.id)||[];h&&(l+=h.value,h.value<this.config.minTestabilityThreshold&&o.push({requirementId:g.id,reason:`Testability score (${h.value}) below threshold (${this.config.minTestabilityThreshold})`,severity:h.value<30?"critical":"high"}));let w=b.filter(C=>C.severity==="error");w.length===0?c++:o.push({requirementId:g.id,reason:`Has ${w.length} validation error(s)`,severity:w.length>2?"critical":"high"})}let d=this.generateSprintRecommendations(i,n.value,o,a.success?a.value:void 0),m={totalRequirements:i.length,validRequirements:c,averageTestability:Math.round(l/i.length),blockers:o,recommendations:d};return this.completeWorkflow(r),this.config.publishEvents&&await this.publishSprintValidated(m),f(m)}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async optimizeScenarioGeneration(e){if(!this.ppoAlgorithm||!this.rlInitialized)return p(new Error("PPO not initialized"));try{let r={id:`req-${e.id}`,features:this.extractRequirementFeatures(e)},i=await this.ppoAlgorithm.predict(r);return f(i)}catch(r){return p(y(r))}}async optimizeScenarioOrdering(e,r){if(!this.ppoAlgorithm||!this.rlInitialized)return r;try{let i=await Promise.all(r.map(async n=>{let s=n.given.length+n.when.length+n.then.length,a={id:`scenario-${n.scenario}`,features:[...this.extractRequirementFeatures(e),s,n.examples?.rows.length||0]},o=await this.ppoAlgorithm.predict(a);return{scenario:n,score:o.value||0}}));return i.sort((n,s)=>s.score-n.score),i.map(n=>n.scenario)}catch(i){return Se.error("Failed to optimize scenario ordering",i instanceof Error?i:void 0),r}}async trainPPOWithScenarioFeedback(e,r,i){if(!(!this.ppoAlgorithm||!this.rlInitialized))try{let n={id:`req-${e.id}`,features:this.extractRequirementFeatures(e)},s={type:"generate-scenarios",value:r.length},a=this.calculateScenarioReward(r,i),o={state:n,action:s,reward:a,nextState:n,done:!0};await this.ppoAlgorithm.train(o),Se.info(`[PPO] Trained with reward: ${a.toFixed(3)}`)}catch(n){Se.error("Failed to train PPO",n instanceof Error?n:void 0)}}calculateScenarioReward(e,r){let i=.5,n=e.length;n>=3&&n<=5?i+=.2:n>5&&(i-=.1);let s=r.testCaseOutlines.length;i+=Math.min(.3,s*.05);let a=e.filter(o=>o.examples&&o.examples.rows.length>0).length;return i+=a/e.length*.2,Math.max(0,Math.min(1,i))}extractScenarioCount(e){return e.action.type==="generate-scenarios"&&typeof e.action.value=="number"?Math.max(1,Math.min(10,Math.round(e.action.value))):3}extractRequirementFeatures(e){return[e.title.length,e.description.length,e.acceptanceCriteria.length,e.priority==="critical"?1:e.priority==="high"?.5:0,e.type==="functional"?1:0,e.type==="non-functional"?1:0,e.dependencies?.length||0,(e.tags??[]).length,e.estimatedComplexity||.5,e.status==="approved"?1:0]}async adaptRequirementPattern(e){if(!this.sonaEngine||!this.rlInitialized)return{success:!1,pattern:null,similarity:0};try{let r={id:`req-${e.id}`,features:this.extractRequirementFeatures(e)},i=await this.sonaEngine.adaptPattern(r,"test-generation","requirements-validation");return{success:i.success,pattern:i.pattern,similarity:i.similarity}}catch(r){return Se.error("Failed to adapt requirement pattern",r instanceof Error?r:void 0),{success:!1,pattern:null,similarity:0}}}async storeRequirementPattern(e,r,i){if(!(!this.sonaEngine||!this.rlInitialized))try{let n={id:`req-${e.id}`,features:this.extractRequirementFeatures(e)},s={type:"validate",value:r},a={reward:r/100,success:r>=this.config.minTestabilityThreshold,quality:r/100},o=this.sonaEngine.createPattern(n,s,a,"test-generation","requirements-validation",{requirementId:e.id,requirementType:e.type,validationErrorCount:i.validationErrors.length,ambiguityScore:i.ambiguityReport.overallScore});Se.info(`[SONA] Stored pattern ${o.id} for requirement ${e.id}`)}catch(n){Se.error("Failed to store requirement pattern",n instanceof Error?n:void 0)}}async spawnAnalysisAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`req-analyzer-${e.slice(0,8)}`,domain:"requirements-validation",type:"analyzer",capabilities:["requirements-analysis","testability-scoring","ambiguity-detection"],config:{workflowId:e,requirementId:r.id,requirementType:r.type}};return this.agentCoordinator.spawn(i)}async spawnBDDAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`bdd-generator-${e.slice(0,8)}`,domain:"requirements-validation",type:"generator",capabilities:["bdd-generation","gherkin","scenario-writing"],config:{workflowId:e,requirementId:r.id}};return this.agentCoordinator.spawn(i)}async publishRequirementAnalyzed(e){let r=D(Ms.RequirementAnalyzed,"requirements-validation",{requirementId:e.requirement.id,testabilityScore:e.testabilityScore.value,testabilityCategory:e.testabilityScore.category,validationErrorCount:e.validationErrors.length,ambiguityScore:e.ambiguityReport.overallScore,suggestedImprovementsCount:e.suggestedImprovements.length});await this.eventBus.publish(r)}async publishBDDScenariosGenerated(e,r){let i=D(Ms.BDDScenariosGenerated,"requirements-validation",{requirementId:e,scenarioCount:r.length,tags:[...new Set(r.flatMap(n=>n.tags))]});await this.eventBus.publish(i)}async publishSprintValidated(e){let r=D(Ms.SprintValidated,"requirements-validation",{totalRequirements:e.totalRequirements,validRequirements:e.validRequirements,averageTestability:e.averageTestability,blockerCount:e.blockers.length,criticalBlockers:e.blockers.filter(i=>i.severity==="critical").length});await this.eventBus.publish(r)}async publishValidationFailed(e,r){let i=D(Ms.ValidationFailed,"requirements-validation",{error:e.message,context:r,timestamp:new Date().toISOString()});await this.eventBus.publish(i)}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this))}async handleImpactAnalysis(e){}async handleTestGenerated(e){}generateTestCaseOutlines(e,r){return r.map((i,n)=>({id:`TC-${e.id}-${n+1}`,title:i.scenario,steps:[...i.given.map(s=>`Setup: ${s}`),...i.when.map(s=>`Action: ${s}`),...i.then.map(s=>`Verify: ${s}`)],expectedResults:i.then,testData:i.examples?this.extractTestDataFromExamples(i.examples):{}}))}extractTestDataFromExamples(e){let r={};for(let i=0;i<e.headers.length;i++){let n=e.headers[i];r[n]=e.rows.map(s=>s[i])}return r}generateSprintRecommendations(e,r,i,n){let s=[],a=i.filter(d=>d.severity==="critical");a.length>0&&s.push(`Address ${a.length} critical blocker(s) before sprint planning`);let o=Array.from(r.entries()).filter(([,d])=>d.value<this.config.minTestabilityThreshold);if(o.length>0&&s.push(`Improve testability for ${o.length} requirement(s) scoring below ${this.config.minTestabilityThreshold}`),n){let d=this.findHeavilyDependedRequirements(e,n.edges);d.length>0&&s.push(`Prioritize ${d.length} requirement(s) that block others`)}let c=e.filter(d=>d.priority==="critical");c.length>0&&s.push(`Ensure ${c.length} critical priority requirement(s) are addressed first`);let l=Array.from(r.values()).reduce((d,m)=>d+m.value,0)/r.size;return l<70&&s.push(`Overall testability average (${Math.round(l)}) is below recommended level of 70`),s.length===0&&s.push("Sprint requirements are well-defined and ready for development"),s}findHeavilyDependedRequirements(e,r){let i=new Map;for(let n of r)if(n.type==="depends-on"){let s=i.get(n.to)||0;i.set(n.to,s+1)}return Array.from(i.entries()).filter(([,n])=>n>=2).map(([n])=>n)}sanitizeFilename(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}async loadWorkflowState(){let e=await this.memory.get("requirements-validation: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("requirements-validation:coordinator:workflows",e,{namespace:"requirements-validation",persist:!0})}requiresConsensus(e){return this.consensusMixin.requiresConsensus(e)}async verifyFinding(e){return this.consensusMixin.verifyFinding(e)}async verifyRequirementConflict(e,r){let i=V({id:v(),type:"requirement-conflict",confidence:r,description:`Requirement conflict detected: ${e.description}`,payload:e,detectedBy:"requirements-validation-coordinator",severity:e.severity==="high"?"high":e.severity==="medium"?"medium":"low"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return!!(n.success&&n.value.verdict==="verified")}return!0}async verifyTestabilityAssessment(e,r){let i=V({id:v(),type:"testability-assessment",confidence:r,description:`Testability assessment for ${e.requirementId}: score ${e.score} (${e.category})`,payload:e,detectedBy:"requirements-validation-coordinator",severity:e.score<30?"critical":e.score<60?"high":"medium"});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)}};A();se();var gc=class{initialized=!1;memory;constructor(t){this.memory=t}async initialize(){this.initialized||(this.initialized=!0)}async dispose(){this.initialized=!1}registerWorkflowActions(t){if(!this.initialized)throw new Error("QCSDIdeationPlugin must be initialized before registering workflow actions");t.registerAction("requirements-validation","analyzeQualityCriteria",this.analyzeQualityCriteria.bind(this)),t.registerAction("requirements-validation","assessTestability",this.assessTestability.bind(this)),t.registerAction("requirements-validation","assessRisks",this.assessRisks.bind(this)),t.registerAction("requirements-validation","validateRequirements",this.validateRequirements.bind(this)),t.registerAction("security-compliance","modelSecurityThreats",this.modelSecurityThreats.bind(this)),t.registerAction("requirements-validation","generateIdeationReport",this.generateIdeationReport.bind(this)),t.registerAction("learning-optimization","storeIdeationLearnings",this.storeIdeationLearnings.bind(this)),t.registerAction("requirements-validation","extractWebsiteContent",this.extractWebsiteContent.bind(this)),t.registerAction("visual-accessibility","auditAccessibility",this.auditAccessibility.bind(this)),t.registerAction("coordination","analyzeQualityExperience",this.analyzeQualityExperience.bind(this))}async extractWebsiteContent(t,e){try{let r=t.url||e.input.url;if(!r)return f({url:"",isWebsite:!1,extractedDescription:e.input.description||"",extractedFeatures:[],extractedAcceptanceCriteria:e.input.acceptanceCriteria||[],detectedFlags:{hasUI:!1,hasSecurity:!1,hasUX:!1}});let i;try{i=new URL(r)}catch{return p(new Error(`Invalid URL: ${r}`))}let n=await this.fetchWebsiteContent(i.toString());if(!n.success)return p(n.error);let s=n.value,a=this.parseWebsiteContent(s,i),o=this.buildEpicDescription(a,i),c=this.generateAcceptanceCriteria(a),l=this.detectContentFlags(s,a);return f({url:i.toString(),isWebsite:!0,extractedDescription:o,extractedFeatures:a.features,extractedAcceptanceCriteria:c,detectedFlags:l,metadata:{title:a.title,pageCount:1,extractedAt:new Date().toISOString()}})}catch(r){return p(new Error(`Website extraction failed: ${T(r)}`))}}async fetchWebsiteContent(t){try{let e=await fetch(t,{headers:{"User-Agent":"AQE-QCSD-Ideation-Swarm/1.0 (Quality Assessment Bot)",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language":"en-US,en;q=0.5"},signal:AbortSignal.timeout(3e4)});if(!e.ok)return p(new Error(`HTTP ${e.status}: ${e.statusText}`));let r=await e.text();return f(r)}catch(e){return p(new Error(`Fetch failed: ${T(e)}`))}}parseWebsiteContent(t,e){let r=[],i=[],n=[],s=t.match(/<title[^>]*>([^<]+)<\/title>/i),a=s?s[1].trim():e.hostname,o=[{pattern:/type\s*=\s*["']search["']/i,feature:"Search functionality",ui:"Search input"},{pattern:/shopping[-_]?cart|cart[-_]?icon|add[-_]?to[-_]?cart/i,feature:"Shopping cart",ui:"Cart component"},{pattern:/login|sign[-_]?in|log[-_]?in/i,feature:"User authentication",ui:"Login form"},{pattern:/register|sign[-_]?up|create[-_]?account/i,feature:"User registration",ui:"Registration form"},{pattern:/checkout|payment|pay[-_]?now/i,feature:"Checkout process",ui:"Checkout flow"},{pattern:/product[-_]?list|product[-_]?grid|catalog/i,feature:"Product catalog",ui:"Product grid"},{pattern:/filter|sort[-_]?by|refine/i,feature:"Filtering and sorting",ui:"Filter controls"},{pattern:/wishlist|favorites|save[-_]?for[-_]?later/i,feature:"Wishlist functionality",ui:"Wishlist button"},{pattern:/review|rating|stars/i,feature:"Reviews and ratings",ui:"Rating component"},{pattern:/newsletter|subscribe|email[-_]?signup/i,feature:"Newsletter subscription",ui:"Subscription form"},{pattern:/navigation|nav[-_]?menu|main[-_]?menu/i,feature:"Site navigation",ui:"Navigation menu"},{pattern:/footer|site[-_]?map/i,feature:"Footer navigation",ui:"Footer component"},{pattern:/modal|popup|dialog/i,feature:"Modal dialogs",ui:"Modal component"},{pattern:/carousel|slider|slideshow/i,feature:"Image carousel",ui:"Carousel component"},{pattern:/accordion|collapsible|expandable/i,feature:"Accordion sections",ui:"Accordion component"},{pattern:/tab|tabbed[-_]?content/i,feature:"Tabbed content",ui:"Tab component"},{pattern:/form|input|textarea|select/i,feature:"Form interactions",ui:"Form elements"},{pattern:/video|player|embed/i,feature:"Video content",ui:"Video player"},{pattern:/chat|support|help[-_]?desk/i,feature:"Customer support",ui:"Chat widget"},{pattern:/cookie|consent|gdpr|privacy/i,feature:"Privacy compliance",ui:"Consent banner"}];for(let{pattern:b,feature:w,ui:C}of o)b.test(t)&&(r.push(w),C&&i.push(C));let c=[{pattern:/password|passwd/i,feature:"Password handling"},{pattern:/https|ssl|secure/i,feature:"Secure connection"},{pattern:/oauth|sso|single[-_]?sign[-_]?on/i,feature:"OAuth/SSO authentication"},{pattern:/2fa|two[-_]?factor|mfa/i,feature:"Multi-factor authentication"},{pattern:/captcha|recaptcha/i,feature:"Bot protection"},{pattern:/csrf|token/i,feature:"CSRF protection"},{pattern:/encrypt|crypto/i,feature:"Data encryption"}];for(let{pattern:b,feature:w}of c)b.test(t)&&n.push(w);let l=(t.match(/<form/gi)||[]).length,d=(t.match(/<button/gi)||[]).length,m=(t.match(/<input/gi)||[]).length,g=(t.match(/<a\s+[^>]*href/gi)||[]).length,h=(t.match(/<img/gi)||[]).length;return{title:a,features:[...new Set(r)],uiComponents:[...new Set(i)],securityFeatures:[...new Set(n)],metrics:{formCount:l,buttonCount:d,inputCount:m,linkCount:g,imageCount:h}}}buildEpicDescription(t,e){let r=[`## Website Analysis: ${t.title}`,`**URL**: ${e.toString()}`,`**Domain**: ${e.hostname}`,"","### Detected Features"];if(t.features.length>0)for(let i of t.features)r.push(`- ${i}`);else r.push("- Basic web content");if(r.push("","### UI Components"),t.uiComponents.length>0)for(let i of t.uiComponents)r.push(`- ${i}`);else r.push("- Standard HTML elements");if(t.securityFeatures.length>0){r.push("","### Security Features");for(let i of t.securityFeatures)r.push(`- ${i}`)}return r.push("","### Page Metrics"),r.push(`- Forms: ${t.metrics.formCount}`),r.push(`- Buttons: ${t.metrics.buttonCount}`),r.push(`- Input fields: ${t.metrics.inputCount}`),r.push(`- Links: ${t.metrics.linkCount}`),r.push(`- Images: ${t.metrics.imageCount}`),r.join(`
2848
- `)}generateAcceptanceCriteria(t){let e=[],r={"Search functionality":"User can search for content and receive relevant results","Shopping cart":"User can add items to cart and view cart contents","User authentication":"User can log in with valid credentials","User registration":"New user can create an account","Checkout process":"User can complete purchase with valid payment","Product catalog":"User can browse and view product listings","Filtering and sorting":"User can filter and sort content by various criteria","Wishlist functionality":"User can save items for later","Reviews and ratings":"User can view and submit reviews","Newsletter subscription":"User can subscribe to email updates","Site navigation":"User can navigate between all main sections","Modal dialogs":"Modal dialogs are accessible and dismissible","Form interactions":"All forms validate input and show clear error messages","Video content":"Video content is playable and accessible","Customer support":"User can access help and support resources","Privacy compliance":"Cookie consent is properly implemented"};for(let i of t.features)r[i]&&e.push(r[i]);return e.length===0&&e.push("Page loads within acceptable time","Content is readable and well-structured","Navigation is intuitive"),e}detectContentFlags(t,e){let r=e.uiComponents.length>0||e.metrics.formCount>0||e.metrics.buttonCount>0||/<(button|input|select|form|img|video|canvas)/i.test(t),i=e.securityFeatures.length>0||/login|password|auth|token|session|credential/i.test(t),n=e.features.length>=3||e.metrics.formCount>=2||/user[-_]?experience|ux|journey|onboarding|tutorial/i.test(t);return{hasUI:r,hasSecurity:i,hasUX:n}}async analyzeQualityCriteria(t,e){try{let r=t.targetId||e.input.targetId,i=t.targetType||e.input.targetType,n=t.description||e.input.description||"",s=t.acceptanceCriteria||e.input.acceptanceCriteria||[],a=this.analyzeHTSMCategories(r,i,n,s),o=this.calculateQualityScore(a);return await this.memory.set(`qcsd-ideation:quality-criteria:${r}`,{criteria:a,qualityScore:o,timestamp:new Date().toISOString()},{namespace:"qcsd-ideation",ttl:3600}),f({qualityCriteria:a,qualityScore:o})}catch(r){return p(y(r))}}async assessTestability(t,e){try{let r=t.targetId||e.input.targetId,i=t.description||e.input.description||"",n=t.acceptanceCriteria||e.input.acceptanceCriteria||[],s=this.assessTestabilityPrinciples(i,n),a=Math.round(Object.values(s).reduce((d,m)=>d+m,0)/10),{blockers:o,recommendations:c}=this.identifyTestabilityIssues(s),l={id:v(),targetId:r,overallScore:a,principles:s,blockers:o,recommendations:c};return await this.memory.set(`qcsd-ideation:testability:${r}`,l,{namespace:"qcsd-ideation",ttl:3600}),f(l)}catch(r){return p(y(r))}}async assessRisks(t,e){try{let r=t.targetId||e.input.targetId,i=t.targetType||e.input.targetType,n=t.description||e.input.description||"",s=this.analyzeRiskFactors(i,n),a=Math.round(s.reduce((d,m)=>d+m.score,0)/s.length*4),o=this.determineRiskLevel(a),c=this.generateMitigations(s),l={id:v(),targetId:r,overallRisk:o,riskScore:a,factors:s,mitigations:c};return await this.memory.set(`qcsd-ideation:risk:${r}`,l,{namespace:"qcsd-ideation",ttl:3600}),f(l)}catch(r){return p(y(r))}}async validateRequirements(t,e){try{let r=t.targetId||e.input.targetId,i=t.description||e.input.description||"",n=t.acceptanceCriteria||e.input.acceptanceCriteria||[],s=[],a=[];i.length<50&&(s.push("Description is too short (< 50 characters)"),a.push("Add more context about the business value and user need"));let o=["should","could","might","maybe","possibly","etc","and so on"];for(let d of o)i.toLowerCase().includes(d)&&(s.push(`Ambiguous term detected: "${d}"`),a.push(`Replace "${d}" with specific, measurable criteria`));n.length===0?(s.push("No acceptance criteria defined"),a.push("Add Given/When/Then acceptance criteria")):n.length<3&&(s.push("Too few acceptance criteria (< 3)"),a.push("Consider adding criteria for happy path, error cases, and edge cases")),!n.some(d=>d.toLowerCase().includes("given")||d.toLowerCase().includes("when")||d.toLowerCase().includes("then"))&&n.length>0&&a.push("Consider using Given/When/Then format for clearer test scenarios");let l=s.length===0;return f({valid:l,issues:s,suggestions:a})}catch(r){return p(y(r))}}async modelSecurityThreats(t,e){try{let r=t.targetId||e.input.targetId,i=t.description||e.input.description||"",n=t.securityCritical||e.input.securityCritical||!1,s=this.analyzeSTRIDEThreats(i,n),a=Math.max(...s.map(d=>d.likelihood*d.impact),0),o=this.determineRiskLevel(a*4),c=this.generateSecurityRecommendations(s),l={id:v(),targetId:r,threats:s,overallRisk:o,recommendations:c};return await this.memory.set(`qcsd-ideation:threat-model:${r}`,l,{namespace:"qcsd-ideation",ttl:3600}),f(l)}catch(r){return p(y(r))}}async generateIdeationReport(t,e){try{let r=t.targetId||e.input.targetId,i=t.targetType||e.input.targetType||"requirement",n=await this.memory.get(`qcsd-ideation:quality-criteria:${r}`),s=await this.memory.get(`qcsd-ideation:testability:${r}`),a=await this.memory.get(`qcsd-ideation:risk:${r}`),o=await this.memory.get(`qcsd-ideation:threat-model:${r}`),c=e.results,l=n?.criteria||c["quality-criteria-analysis"]?.qualityCriteria||[],d=n?.qualityScore||c["quality-criteria-analysis"]?.qualityScore||0,m=s||c["testability-assessment"],g=a||c["risk-assessment"],h=o||c["security-threat-modeling"],b=this.generateSWOTInsights(l,m,g),w=this.generateRecommendations(l,m,g,h),C=this.generateTestStrategy(l,m,g),S=this.identifyBlockers(m,g,h),P=S.length===0,k={id:v(),timestamp:new Date().toISOString(),targetId:r,targetType:i,qualityCriteria:l,qualityScore:d,testability:m,risk:g,threatModel:h,insights:b,recommendations:w,testStrategy:C,readyForDevelopment:P,blockers:S};return await this.memory.set(`qcsd-ideation:report:${r}`,k,{namespace:"qcsd-ideation",persist:!0}),f(k)}catch(r){return p(y(r))}}async storeIdeationLearnings(t,e){try{let r=t.targetId||e.input.targetId,i=t.report||e.results["aggregate-ideation-report"];if(!i)return p(new Error("No ideation report found to store"));let n=`ideation-pattern-${Date.now()}`,s={id:n,timestamp:new Date().toISOString(),targetType:i.targetType,qualityScore:i.qualityScore,testabilityScore:i.testability.overallScore,riskLevel:i.risk.overallRisk,blockerCount:i.blockers.length,readyForDevelopment:i.readyForDevelopment,features:{hasSecurityThreats:!!i.threatModel&&i.threatModel.threats.length>0,avgPrincipleScore:i.testability.overallScore,riskFactorCount:i.risk.factors.length,qualityCriteriaCount:i.qualityCriteria.length}};await this.memory.set(`qcsd-patterns:${n}`,s,{namespace:"learning",persist:!0});let a=await this.memory.get("qcsd-patterns:index")||[];return a.push(n),await this.memory.set("qcsd-patterns:index",a,{namespace:"learning",persist:!0}),f({stored:!0,patternId:n})}catch(r){return p(y(r))}}analyzeHTSMCategories(t,e,r,i){let n=["capability","reliability","usability","charisma","security","scalability","compatibility","performance","installability","supportability"],s=r.toLowerCase(),a=i.join(" ").toLowerCase();return n.map(o=>{let{weight:c,testabilityScore:l,risks:d,testIdeas:m}=this.analyzeCategory(o,s,a);return{id:`${t}-${o}`,category:o,name:o.charAt(0).toUpperCase()+o.slice(1),description:this.getCategoryDescription(o),weight:c,testabilityScore:l,risks:d,testIdeas:m}})}analyzeCategory(t,e,r){let n={capability:["function","feature","ability","can","must","shall"],reliability:["reliable","consistent","stable","fault","error","recover"],usability:["user","easy","intuitive","accessible","ux","interface"],charisma:["design","look","feel","brand","aesthetic","appeal"],security:["secure","auth","encrypt","protect","permission","role"],scalability:["scale","load","concurrent","throughput","capacity"],compatibility:["integrate","api","browser","device","version","legacy"],performance:["fast","response","latency","speed","efficient","optimize"],installability:["install","deploy","setup","configure","provision"],supportability:["log","monitor","debug","maintain","document","support"]}[t],s=n.filter(m=>e.includes(m)||r.includes(m)).length,a=Math.min(10,3+s*2),c=n.some(m=>r.includes(m))?70+L()*20:40+L()*30,l=this.generateCategoryRisks(t,s===0),d=this.generateCategoryTestIdeas(t);return{weight:a,testabilityScore:Math.round(c),risks:l,testIdeas:d}}getCategoryDescription(t){return{capability:"Core functionality and features the system must provide",reliability:"Consistency and stability under various conditions",usability:"Ease of use and user experience quality",charisma:"Visual appeal and brand alignment",security:"Protection against threats and unauthorized access",scalability:"Ability to handle growth and increased load",compatibility:"Integration with other systems and environments",performance:"Speed, responsiveness, and resource efficiency",installability:"Ease of deployment and configuration",supportability:"Maintainability and operational support"}[t]}generateCategoryRisks(t,e){let r=[];e&&r.push(`${t.charAt(0).toUpperCase()+t.slice(1)} requirements not explicitly defined`);let i={capability:["Feature gaps may emerge late","Edge cases not covered"],reliability:["System may fail under load","Error handling unclear"],usability:["User confusion possible","Accessibility gaps"],charisma:["Brand inconsistency risk","Visual regression possible"],security:["Vulnerability exposure","Data breach risk"],scalability:["Performance degradation at scale","Resource exhaustion"],compatibility:["Integration failures","Version conflicts"],performance:["Slow response times","Resource bottlenecks"],installability:["Deployment complexity","Configuration errors"],supportability:["Debugging difficulty","Maintenance burden"]};return r.push(...i[t].slice(0,e?2:1)),r}generateCategoryTestIdeas(t){return{capability:["Happy path scenarios","Boundary value analysis","State transition tests"],reliability:["Stress testing","Recovery testing","Long-running tests"],usability:["User journey tests","Accessibility audits","Heuristic evaluation"],charisma:["Visual regression tests","Brand guideline validation","A/B testing"],security:["Penetration testing","Auth flow tests","Input validation"],scalability:["Load testing","Capacity testing","Horizontal scaling tests"],compatibility:["Cross-browser tests","API contract tests","Migration tests"],performance:["Response time tests","Throughput tests","Resource monitoring"],installability:["Deployment verification","Configuration tests","Rollback tests"],supportability:["Log validation","Monitoring checks","Runbook validation"]}[t]}calculateQualityScore(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n.weight,0),r=t.reduce((i,n)=>i+n.testabilityScore*n.weight/e,0);return Math.round(r)}assessTestabilityPrinciples(t,e){let r=e.length,i=t.length,n=e.some(s=>s.toLowerCase().includes("given")||s.toLowerCase().includes("when"));return{controllability:Math.min(100,40+r*10),observability:n?80:50,isolability:Math.min(100,50+L()*30),separationOfConcerns:Math.min(100,40+L()*40),simplicity:Math.max(30,100-i/20),stability:Math.min(100,60+L()*20),informationCapture:n?85:45,automationSupport:n?90:40,selfDocumenting:Math.min(100,30+i/10),independence:Math.min(100,50+L()*30)}}identifyTestabilityIssues(t){let e=[],r=[];return t.controllability<50&&e.push("Low controllability - test setup may be difficult"),t.observability<50&&e.push("Low observability - verifying outcomes may be challenging"),t.automationSupport<50&&r.push("Add explicit acceptance criteria in Given/When/Then format"),t.isolability<60&&r.push("Consider breaking into smaller, isolated components"),t.simplicity<40&&r.push("Simplify requirements - current description is complex"),{blockers:e,recommendations:r}}analyzeRiskFactors(t,e){let r=[],i=e.toLowerCase();return e.length>500&&r.push({category:"Complexity",description:"High description complexity increases misunderstanding risk",likelihood:4,impact:3,score:12}),(i.includes("api")||i.includes("integrate"))&&r.push({category:"Integration",description:"External dependencies may cause integration issues",likelihood:3,impact:4,score:12}),(i.includes("user")||i.includes("data")||i.includes("auth"))&&r.push({category:"Security",description:"User data handling requires security considerations",likelihood:3,impact:5,score:15}),(i.includes("real-time")||i.includes("fast")||i.includes("scale"))&&r.push({category:"Performance",description:"Performance requirements may be challenging to meet",likelihood:3,impact:3,score:9}),r.length===0&&r.push({category:"General",description:"Standard development risks apply",likelihood:2,impact:2,score:4}),r}determineRiskLevel(t){return t>=80?"critical":t>=60?"high":t>=40?"medium":"low"}generateMitigations(t){let e=[];for(let r of t)switch(r.category){case"Complexity":e.push("Break down into smaller, more manageable stories");break;case"Integration":e.push("Define API contracts early with contract testing");break;case"Security":e.push("Conduct threat modeling and security review");break;case"Performance":e.push("Establish performance baselines and monitoring");break;default:e.push("Apply standard QE practices")}return e}analyzeSTRIDEThreats(t,e){let r=[],i=t.toLowerCase();return(i.includes("auth")||i.includes("login")||i.includes("user"))&&r.push({category:"spoofing",name:"Identity Spoofing",description:"Attacker may impersonate legitimate users",likelihood:e?4:2,impact:4,mitigations:["Implement MFA","Use strong session management"]}),(i.includes("data")||i.includes("update")||i.includes("edit"))&&r.push({category:"tampering",name:"Data Tampering",description:"Data may be modified maliciously",likelihood:e?3:2,impact:4,mitigations:["Implement input validation","Use integrity checks"]}),(i.includes("personal")||i.includes("sensitive")||i.includes("private"))&&r.push({category:"informationDisclosure",name:"Information Disclosure",description:"Sensitive information may be exposed",likelihood:e?4:3,impact:5,mitigations:["Encrypt data at rest and in transit","Implement access controls"]}),r.length===0&&!e&&r.push({category:"denial",name:"Service Denial",description:"Service availability may be impacted",likelihood:2,impact:3,mitigations:["Implement rate limiting","Add monitoring and alerts"]}),r}generateSecurityRecommendations(t){let e=new Set;for(let r of t)for(let i of r.mitigations)e.add(i);return Array.from(e)}generateSWOTInsights(t,e,r){let i=[],n=[],s=[],a=[],o=t.filter(l=>l.testabilityScore>=70);o.length>5&&i.push(`${o.length}/10 quality categories have high testability`),e.overallScore>=70&&i.push("Overall testability score is good"),r.overallRisk==="low"&&i.push("Risk profile is manageable");let c=t.filter(l=>l.testabilityScore<50);return c.length>0&&n.push(`${c.length} quality categories need more definition`),e.blockers.length>0&&n.push(...e.blockers.slice(0,2)),e.principles.automationSupport>=70&&s.push("High automation potential for test coverage"),s.push("Early quality assessment enables shift-left testing"),r.factors.some(l=>l.score>=15)&&a.push("High-severity risks require immediate attention"),a.push(...r.factors.filter(l=>l.score>=10).map(l=>l.description).slice(0,2)),{strengths:i,weaknesses:n,opportunities:s,threats:a}}generateRecommendations(t,e,r,i){let n=[];e.overallScore<60&&n.push({priority:"high",category:"Testability",description:"Improve acceptance criteria with specific, measurable outcomes",effort:"low"});for(let a of r.factors.filter(o=>o.score>=12))n.push({priority:a.score>=15?"critical":"high",category:"Risk Mitigation",description:r.mitigations[0]||`Address ${a.category} risk`,effort:"medium"});i&&i.threats.length>0&&n.push({priority:i.overallRisk==="critical"?"critical":"high",category:"Security",description:i.recommendations[0]||"Implement security controls",effort:"high"});let s=t.filter(a=>a.testabilityScore<50);return s.length>0&&n.push({priority:"medium",category:"Quality Definition",description:`Define clearer criteria for: ${s.map(a=>a.category).join(", ")}`,effort:"low"}),n.sort((a,o)=>{let c={critical:0,high:1,medium:2,low:3};return c[a.priority]-c[o.priority]})}generateTestStrategy(t,e,r){let i="Standard test pyramid with unit, integration, and E2E tests";(r.overallRisk==="high"||r.overallRisk==="critical")&&(i="Risk-based testing with enhanced coverage for high-risk areas"),e.overallScore>=80&&(i+=" with high automation potential");let n=t.filter(c=>c.weight>=5).flatMap(c=>c.testIdeas.slice(0,2)),s=r.factors.filter(c=>c.score>=9).map(c=>`${c.category}: ${c.description}`),a=t.reduce((c,l)=>c+l.weight,0),o="Medium (3-5 days)";return a>60?o="High (1-2 weeks)":a<40&&(o="Low (1-2 days)"),{approach:i,coverage:[...new Set(n)].slice(0,8),riskAreas:s.slice(0,4),estimatedEffort:o}}async auditAccessibility(t,e){try{let r=t.targetId||e.input.targetId,i=t.url||e.input.url,n=t.description||e.input.description||"",s=t.features||e.input.features||[],a=[],o=[],c={"Image carousel":{issue:"Carousels may lack pause controls and keyboard navigation",rec:"Ensure carousel has pause button, keyboard controls, and ARIA labels"},"Form interactions":{issue:"Forms may lack proper labels and error announcements",rec:"Add aria-describedby for errors, ensure all inputs have associated labels"},"Modal dialogs":{issue:"Modals may trap focus or lack escape key handling",rec:"Implement focus trap, escape key closure, and return focus on close"},"Video content":{issue:"Videos may lack captions and audio descriptions",rec:"Add WebVTT captions and audio description track for video content"},"Site navigation":{issue:"Navigation may lack skip links and landmark roles",rec:"Add skip-to-main link, use proper landmark roles (nav, main, aside)"},"Newsletter subscription":{issue:"Signup forms may lack clear success/error feedback",rec:"Use aria-live regions for form submission feedback"}};for(let d of s){let m=c[d];m&&(a.push(m.issue),o.push(m.rec))}o.push("Verify color contrast meets WCAG 2.2 AA (4.5:1 for text)","Test with screen reader (NVDA/VoiceOver)","Verify keyboard navigation for all interactive elements","Check focus indicators are visible");let l=a.length>5?"Likely fails AA":a.length>2?"Partial AA compliance":"Potential AA compliance";return await this.memory.set(`qcsd-ideation:accessibility:${r}`,{wcagLevel:l,violations:a,recommendations:o,url:i,timestamp:new Date().toISOString()},{namespace:"qcsd-ideation",ttl:3600}),f({wcagLevel:l,violations:a,recommendations:o})}catch(r){return p(y(r))}}async analyzeQualityExperience(t,e){try{let r=t.targetId||e.input.targetId,i=t.url||e.input.url,n=t.description||e.input.description||"",s=t.features||e.input.features||[],a=[],o=[],c=[],l={"Newsletter subscription":{journey:"Content subscription flow: Landing -> Email signup -> Confirmation",friction:"Multi-step signup may cause abandonment",rec:"Implement single-field inline signup with immediate feedback"},"Search functionality":{journey:"Content discovery flow: Search -> Filter -> Select -> Read",friction:"Poor search results relevance frustrates users",rec:'Add search suggestions, filters, and "no results" helpful messaging'},"User authentication":{journey:"Account access flow: Login page -> Auth -> Dashboard",friction:"Password requirements and recovery flow complexity",rec:"Add social login options, clear password requirements, easy recovery"},"Shopping cart":{journey:"Purchase flow: Browse -> Add to cart -> Checkout -> Payment",friction:"Cart abandonment at checkout due to complexity",rec:"Guest checkout, progress indicator, saved cart, multiple payment options"},"Comment system":{journey:"Engagement flow: Read article -> Scroll to comments -> Write comment",friction:"Login requirement for commenting reduces engagement",rec:"Allow guest comments with moderation, or social login for quick auth"},"PDF downloads":{journey:"Content access flow: Browse catalog -> Select issue -> Download PDF",friction:"Large file sizes and unclear progress",rec:"Show file size before download, progress indicator, resume support"}};for(let d of s){let m=l[d];m&&(a.push(m.journey),o.push(m.friction),c.push(m.rec))}return c.push("Map complete user journeys with entry/exit points","Identify drop-off points using analytics","Test critical paths with real users","Monitor Core Web Vitals for performance impact on UX"),await this.memory.set(`qcsd-ideation:qx:${r}`,{journeys:a,frictionPoints:o,recommendations:c,url:i,timestamp:new Date().toISOString()},{namespace:"qcsd-ideation",ttl:3600}),f({journeys:a,frictionPoints:o,recommendations:c})}catch(r){return p(y(r))}}identifyBlockers(t,e,r){let i=[];return t.overallScore<40&&i.push("Testability score too low - cannot verify acceptance criteria"),i.push(...t.blockers),e.overallRisk==="critical"&&i.push("Critical risk level requires risk mitigation before development"),r&&r.overallRisk==="critical"&&i.push("Critical security threats must be addressed before development"),i}};function vd(u){return new gc(u)}A();var hc=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;validator=null;bddWriter=null;testabilityScorer=null;qcsdIdeationPlugin=null;pluginConfig;get name(){return"requirements-validation"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{validate:this.validate.bind(this),validateAgainstCriteria:this.validateAgainstCriteria.bind(this),detectAmbiguity:this.detectAmbiguity.bind(this),analyzeDependencies:this.analyzeDependencies.bind(this),scoreRequirement:this.scoreRequirement.bind(this),scoreRequirements:this.scoreRequirements.bind(this),suggestImprovements:this.suggestImprovements.bind(this),meetsThreshold:this.meetsThreshold.bind(this),generateScenarios:this.generateScenarios.bind(this),generateScenariosWithExamples:this.generateScenariosWithExamples.bind(this),toGherkin:this.toGherkin.bind(this),parseGherkin:this.parseGherkin.bind(this),analyzeRequirement:this.analyzeRequirement.bind(this),generateTestArtifacts:this.generateTestArtifacts.bind(this),validateSprintRequirements:this.validateSprintRequirements.bind(this),getCoordinator:()=>this.coordinator,getValidator:()=>this.validator,getBDDWriter:()=>this.bddWriter,getTestabilityScorer:()=>this.testabilityScorer,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[],registerWorkflowActions:this.registerWorkflowActions.bind(this)}}registerWorkflowActions(e){if(this.ensureInitialized(),!this.qcsdIdeationPlugin)throw new Error("QCSD Ideation Plugin not initialized");this.qcsdIdeationPlugin.registerWorkflowActions(e)}getTaskHandlers(){return new Map([["validate",async e=>{if(!this.validator)return p(new Error("Validator not initialized"));let r=e.requirement;return r?this.validator.validate(r):p(new Error("Invalid validate payload: missing requirement"))}],["generate-scenarios",async e=>{if(!this.bddWriter)return p(new Error("BDD writer not initialized"));let r=e.requirement,i=e.requirementId;if(r)return this.bddWriter.generateScenarios(r);if(i){let n={id:i,title:`Requirement ${i}`,description:"",acceptanceCriteria:[],type:"functional",priority:"medium",status:"draft"};return this.bddWriter.generateScenarios(n)}return p(new Error("Invalid generate-scenarios payload: missing requirementId"))}],["score-testability",async e=>{if(!this.testabilityScorer)return p(new Error("Testability scorer not initialized"));let r=e.requirement;return r?this.testabilityScorer.scoreRequirement(r):p(new Error("Invalid score-testability payload: missing requirement"))}],["detect-ambiguity",async e=>{if(!this.validator)return p(new Error("Validator not initialized"));let r=e.requirement;return r?this.validator.detectAmbiguity(r):p(new Error("Invalid detect-ambiguity payload: missing requirement"))}],["analyze-dependencies",async e=>{if(!this.validator)return p(new Error("Validator not initialized"));let r=e.requirements;return!r||r.length===0?p(new Error("Invalid analyze-dependencies payload: missing requirements")):this.validator.analyzeDependencies(r)}]])}async onInitialize(){this.validator=new gr(this.memory,this.pluginConfig.validator),this.bddWriter=new hr(this.memory,this.pluginConfig.bddWriter),this.testabilityScorer=new fr(this.memory,this.pluginConfig.testabilityScorer),this.coordinator=new Fs(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.qcsdIdeationPlugin=vd(this.memory),await this.qcsdIdeationPlugin.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.qcsdIdeationPlugin&&await this.qcsdIdeationPlugin.dispose(),this.coordinator=null,this.validator=null,this.bddWriter=null,this.testabilityScorer=null,this.qcsdIdeationPlugin=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.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"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;default:break}}async validate(e){this.ensureInitialized();try{return await this.validator.validate(e)}catch(r){return this.handleError(r)}}async validateAgainstCriteria(e,r){this.ensureInitialized();try{return await this.validator.validateAgainstCriteria(e,r)}catch(i){return this.handleError(i)}}async detectAmbiguity(e){this.ensureInitialized();try{return await this.validator.detectAmbiguity(e)}catch(r){return this.handleError(r)}}async analyzeDependencies(e){this.ensureInitialized();try{return await this.validator.analyzeDependencies(e)}catch(r){return this.handleError(r)}}async scoreRequirement(e){this.ensureInitialized();try{return await this.testabilityScorer.scoreRequirement(e)}catch(r){return this.handleError(r)}}async scoreRequirements(e){this.ensureInitialized();try{return await this.testabilityScorer.scoreRequirements(e)}catch(r){return this.handleError(r)}}async suggestImprovements(e,r){this.ensureInitialized();try{return await this.testabilityScorer.suggestImprovements(e,r)}catch(i){return this.handleError(i)}}meetsThreshold(e,r){return this.ensureInitialized(),this.testabilityScorer.meetsThreshold(e,r)}async generateScenarios(e){this.ensureInitialized();try{return await this.bddWriter.generateScenarios(e)}catch(r){return this.handleError(r)}}async generateScenariosWithExamples(e,r){this.ensureInitialized();try{return await this.bddWriter.generateScenariosWithExamples(e,r)}catch(i){return this.handleError(i)}}toGherkin(e){return this.ensureInitialized(),this.bddWriter.toGherkin(e)}parseGherkin(e){return this.ensureInitialized(),this.bddWriter.parseGherkin(e)}async analyzeRequirement(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeRequirement(e);return r.success?this.trackSuccessfulOperation("analyze"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async generateTestArtifacts(e){this.ensureInitialized();try{let r=await this.coordinator.generateTestArtifacts(e);return r.success?this.trackSuccessfulOperation("generate-artifacts"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async validateSprintRequirements(e){this.ensureInitialized();try{let r=await this.coordinator.validateSprintRequirements(e);return r.success?this.trackSuccessfulOperation("validate-sprint"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async handleTestGenerated(e){let r=e.payload;await this.memory.set(`requirements-validation:test-link:${r.testId}`,{testId:r.testId,sourceFile:r.sourceFile,linkedAt:new Date().toISOString()},{namespace:"requirements-validation",ttl:86400*30})}async handleImpactAnalysis(e){let r=e.payload;await this.memory.set(`requirements-validation:impact:${r.analysisId}`,r,{namespace:"requirements-validation",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("RequirementsValidationPlugin is not initialized");if(!this.coordinator||!this.validator||!this.bddWriter||!this.testabilityScorer)throw new Error("RequirementsValidationPlugin 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 bd(u,t,e,r){return new hc(u,t,e,r)}M();A();M();import*as Xe from"path";import*as Ne from"fs/promises";A();function wd(u){return Date.now()-u.cachedAt.getTime()<u.ttlMs}function Cd(u){let t=u.toLowerCase();return t.includes("controller")?"controller":t.includes("service")?"service":t.includes("repository")?"repository":t.includes("facade")?"facade":t.includes("factory")?"factory":t.includes("adapter")?"adapter":t.includes("gateway")?"gateway":t.includes("handler")?"handler":t.includes("validator")?"validator":t.includes("transformer")?"transformer":t.includes("util")||t.includes("helper")?"utility":t.includes("domain")?"feature":t.includes("infra")?"layer":t.includes("package")||t.includes("pkg")?"package":"module"}function Ls(u){return u.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}H();var Wh={cacheTtlMs:36e5,publishEvents:!0,excludePatterns:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/coverage/**"],maxFiles:1e3},jh={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"}},$t=R.create("code-intelligence/product-factors-bridge"),$s=class{constructor(t,e,r={}){this.eventBus=t;this.memory=e;this.config={...Wh,...r}}eventBus;memory;config;initialized=!1;eventSubscriptions=[];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(tt.KnowledgeGraphUpdated,this.handleKnowledgeGraphUpdated.bind(this));this.eventSubscriptions.push(t);let e=this.eventBus.subscribe(tt.ImpactAnalysisCompleted,this.handleImpactAnalysisCompleted.bind(this));this.eventSubscriptions.push(e)}async handleKnowledgeGraphUpdated(t){$t.info("[ProductFactorsBridge] Knowledge graph updated, considering cache invalidation")}async handleImpactAnalysisCompleted(t){let e=t.payload;e.changedFiles&&e.changedFiles.length>0&&$t.info(`[ProductFactorsBridge] Impact analysis detected ${e.changedFiles.length} changed files`)}async requestC4Diagrams(t){let e=Date.now(),r=v();try{let i=await this.getCachedDiagrams(t.projectPath);if(i)return $t.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 p(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 l=await this.analyzeComponents(t.projectPath);n=l.components,s=l.relationships}let a;t.analyzeCoupling&&n.length>1&&(a=this.analyzeCoupling(n,s));let o={};t.includeContext!==!1&&(o.context=this.generateContextDiagram(r,i)),t.includeContainer!==!1&&(o.container=this.generateContainerDiagram(r,i)),t.includeComponent!==!1&&n.length>0&&(o.component=this.generateComponentDiagram(r.name,n,s)),t.includeDependency&&n.length>0&&(o.dependency=this.generateDependencyGraph(n,s));let c={projectName:r.name,projectDescription:r.description,generatedAt:new Date,source:"codebase-analysis",analysisMetadata:{filesAnalyzed:n.reduce((l,d)=>l+d.files.length,0),componentsDetected:n.length,externalSystemsDetected:i.length,analysisTimeMs:Date.now()-e}};return f({diagrams:o,metadata:c,externalSystems:i,components:n,relationships:s,couplingAnalysis:a})}catch(r){let i=y(r);return p(i)}}generateContextDiagram(t,e){let r=`C4Context
2848
+ `).map(c=>c.trim()),i="",n=null,s=[],a=null,o=null;for(let c of r)if(!(!c||c.startsWith("#"))){if(c.startsWith("@")){s=c.split(/\s+/).map(l=>l.replace("@",""));continue}if(c.startsWith("Feature:")){i=c.replace("Feature:","").trim();continue}if(c.startsWith("Scenario:")||c.startsWith("Scenario Outline:")){n&&(o&&(n.examples=o),e.push(this.convertToReadonly(n)));let l=c.replace("Scenario Outline:","").replace("Scenario:","").trim();n={id:v(),feature:i,scenario:l,given:[],when:[],then:[],tags:[...s]},s=[],a=null,o=null;continue}if(c.startsWith("Given"))a="given",n?.given.push(c.replace("Given","").trim());else if(c.startsWith("When"))a="when",n?.when.push(c.replace("When","").trim());else if(c.startsWith("Then"))a="then",n?.then.push(c.replace("Then","").trim());else if(c.startsWith("And")&&a&&n&&a!=="examples"){let l=c.replace("And","").trim();n[a].push(l)}else if(c.startsWith("But")&&a&&n&&a!=="examples"){let l=c.replace("But","").trim();n[a].push(l)}if(c.startsWith("Examples:")){a="examples",o={headers:[],rows:[]};continue}if(c.startsWith("|")&&o){let l=c.split("|").slice(1,-1).map(d=>d.trim());o.headers.length===0?o.headers=l:o.rows.push(l)}}return n&&(o&&(n.examples=o),e.push(this.convertToReadonly(n))),f(e)}catch(e){return p(y(e))}}convertToReadonly(t){return{id:t.id,feature:t.feature,scenario:t.scenario,given:t.given,when:t.when,then:t.then,tags:t.tags,examples:t.examples}}generateScenarioFromCriteria(t,e,r){let i=/given\s+(.+?)\s+when\s+(.+?)\s+then\s+(.+?)(?:\s+and\s+(.+))?$/i,n=e.match(i);return n?{id:v(),feature:t,scenario:this.extractScenarioTitle(e),given:[n[1].trim()],when:[n[2].trim()],then:n[4]?[n[3].trim(),n[4].trim()]:[n[3].trim()],tags:this.inferTags(r)}:this.generateScenarioFromPlainText(t,e,r)}generateScenarioFromPlainText(t,e,r){let i=[],n=[],s=[],a=e.toLowerCase();return r.type==="user-story"?i.push("the user is authenticated"):r.type==="functional"?i.push("the system is in a valid state"):i.push("the preconditions are met"),a.includes("click")||a.includes("press")?n.push("the user performs the action"):a.includes("enter")||a.includes("input")?n.push("the user provides the required input"):a.includes("submit")||a.includes("send")?n.push("the user submits the form"):a.includes("select")||a.includes("choose")?n.push("the user makes a selection"):n.push("the action is performed"),a.includes("display")||a.includes("show")?s.push("the expected content is displayed"):a.includes("save")||a.includes("store")?s.push("the data is persisted correctly"):a.includes("error")||a.includes("fail")?s.push("an appropriate error message is shown"):a.includes("redirect")||a.includes("navigate")?s.push("the user is redirected to the expected page"):a.includes("notify")||a.includes("email")?s.push("a notification is sent"):s.push("the expected outcome is achieved"),{id:v(),feature:t,scenario:this.extractScenarioTitle(e),given:i,when:n,then:s,tags:this.inferTags(r)}}generateAdditionalScenarios(t,e){let r=[];switch(t.type){case"user-story":r.push(this.createScenario(e,"First-time user flow",t,{given:["a new user visits the application"],when:["they complete the onboarding process"],then:["they can access the main features"]}));break;case"non-functional":(t.description.toLowerCase().includes("performance")||t.description.toLowerCase().includes("speed"))&&r.push(this.createScenario(e,"Performance under load",t,{given:["the system is under normal load"],when:["100 concurrent users perform operations"],then:["response time remains under threshold"]}));break;case"technical":r.push(this.createScenario(e,"System integration",t,{given:["all dependent services are available"],when:["the system initializes"],then:["all integrations are established successfully"]}));break}return r}generateNegativeScenarios(t,e){let r=[];return r.push(this.createScenario(e,"Invalid input handling",t,{given:["the user is on the input form"],when:["they submit invalid data"],then:["validation errors are displayed","the form is not submitted"],tags:["negative","validation"]})),(t.type==="user-story"||t.type==="functional")&&r.push(this.createScenario(e,"Unauthorized access attempt",t,{given:["the user is not authenticated"],when:["they attempt to access protected resources"],then:["access is denied","a login prompt is displayed"],tags:["negative","security"]})),r.push(this.createScenario(e,"Error recovery",t,{given:["an error has occurred during operation"],when:["the user attempts to recover"],then:["the system returns to a valid state","no data is lost"],tags:["negative","error-handling"]})),r}createScenario(t,e,r,i){return{id:v(),feature:t,scenario:e,given:i.given,when:i.when,then:i.then,tags:i.tags||this.inferTags(r)}}extractFeatureName(t){return t.title.replace(/^(as a|i want|enable|implement|add|create)\s+/i,"").trim()}extractScenarioTitle(t){let r=t.split(/\s+/).slice(0,8).join(" ");return r.length>60&&(r=r.slice(0,57)+"..."),r.charAt(0).toUpperCase()+r.slice(1)}inferTags(t){let e=[];e.push(t.type),e.push(`priority-${t.priority}`);let r=`${t.title} ${t.description}`.toLowerCase();return(r.includes("api")||r.includes("endpoint"))&&e.push("api"),(r.includes("ui")||r.includes("interface")||r.includes("display"))&&e.push("ui"),(r.includes("database")||r.includes("persist")||r.includes("storage"))&&e.push("database"),(r.includes("security")||r.includes("auth")||r.includes("permission"))&&e.push("security"),(r.includes("performance")||r.includes("speed")||r.includes("fast"))&&e.push("performance"),e}generateExamplesForScenario(t,e){let r=new Set,i=/<(\w+)>/g,n=[...t.given,...t.when,...t.then];for(let o of n){let c;for(;(c=i.exec(o))!==null;)r.add(c[1])}let s=r.size>0?Array.from(r):["input","expected_result"],a=[];for(let o=0;o<e;o++){let c=s.map(l=>this.generateExampleValue(l,o));a.push(c)}return{headers:s,rows:a}}generateExampleValue(t,e){let r=t.toLowerCase();if(r.includes("name")||r.includes("user"))return`test_user_${e+1}`;if(r.includes("email"))return`user${e+1}@example.com`;if(r.includes("password"))return e===0?"ValidPass123!":e===1?"short":"";if(r.includes("amount")||r.includes("price"))return String((e+1)*100);if(r.includes("count")||r.includes("quantity"))return String(e+1);if(r.includes("date")){let i=new Date;return i.setDate(i.getDate()+e),i.toISOString().split("T")[0]}return r.includes("result")||r.includes("expected")?e===0?"success":e===1?"failure":"error":r.includes("status")?["active","pending","inactive"][e]||"unknown":`value_${e+1}`}groupScenariosByTags(t){return[...t].sort((e,r)=>{let i=e.tags.includes("negative"),n=r.tags.includes("negative");return i!==n?i?1:-1:e.scenario.localeCompare(r.scenario)})}async storeScenarios(t,e){await this.memory.set(`requirements-validation:scenarios:${t}`,{requirementId:t,scenarios:e,generatedAt:new Date().toISOString(),count:e.length},{namespace:"requirements-validation",persist:!0})}};A();var yd={specificity:.2,measurability:.25,atomicity:.15,feasibility:.15,traceability:.1,independency:.15},qh={defaultThreshold:60,weights:yd,enableAIScoring:!1},fr=class{constructor(t,e={}){this.memory=t;this.config={...qh,...e,weights:{...yd,...e.weights}}}memory;config;async scoreRequirement(t){try{let e=[];e.push(this.scoreSpecificity(t)),e.push(this.scoreMeasurability(t)),e.push(this.scoreAtomicity(t)),e.push(this.scoreFeasibility(t)),e.push(this.scoreTraceability(t)),e.push(this.scoreIndependency(t));let r=e.reduce((o,c)=>o+c.weight,0),i=e.reduce((o,c)=>o+c.score*c.weight,0),n=Math.round(i/r),s=this.categorizeScore(n),a={value:n,category:s,factors:e};return await this.storeScore(t.id,a),f(a)}catch(e){return p(y(e))}}async scoreRequirements(t){try{let e=new Map;for(let r of t){let i=await this.scoreRequirement(r);i.success&&e.set(r.id,i.value)}return f(e)}catch(e){return p(y(e))}}async suggestImprovements(t,e){try{let r=[],i=[...e.factors].sort((s,a)=>s.score-a.score);for(let s of i){if(s.score<70){let a=this.getSuggestionsForFactor(s,t);r.push(...a)}for(let a of s.issues)r.push(`Fix: ${a}`)}e.value<50?(r.push("Consider rewriting the requirement with clearer, more specific language"),r.push("Add measurable acceptance criteria using Given-When-Then format")):e.value<70&&r.push("Add quantifiable metrics where possible (response times, limits, thresholds)");let n=[...new Set(r)];return f(n.slice(0,10))}catch(r){return p(y(r))}}meetsThreshold(t,e){return t.value>=e}scoreSpecificity(t){let e=100,r=[],i=`${t.title} ${t.description} ${t.acceptanceCriteria.join(" ")}`,n=i.toLowerCase(),s=["fast","quickly","efficient","user-friendly","intuitive","simple","easy","flexible","robust","appropriate","reasonable","adequate","good","better","best","several","many","few","some","most","etc"];for(let c of s)n.includes(c)&&(e-=8,r.push(`Contains ambiguous term: "${c}"`));return/\d+/.test(i)||(e-=15,r.push("No specific numbers or metrics provided")),/\b(user|admin|system|customer|developer)\b/i.test(i)||(e-=10,r.push("No clear actor/subject specified")),t.description.length<50&&(e-=10,r.push("Description is too brief for specificity")),{name:"Specificity",score:Math.max(0,e),weight:this.config.weights.specificity,issues:r}}scoreMeasurability(t){let e=100,r=[],i=`${t.description} ${t.acceptanceCriteria.join(" ")}`,n=i.toLowerCase();[/\d+\s*(ms|seconds?|minutes?|hours?)/i,/\d+\s*%/,/\d+\s*(users?|requests?|transactions?)/i,/\d+\s*(mb|gb|kb)/i,/(less than|more than|at least|maximum|minimum)\s*\d+/i,/\b(must|shall|should)\b.*\b(be|have|support)\b/i].some(c=>c.test(i))||(e-=25,r.push("No measurable criteria found")),t.acceptanceCriteria.length===0?(e-=30,r.push("No acceptance criteria defined")):t.acceptanceCriteria.filter(l=>{let d=l.toLowerCase();return/\bthen\b/i.test(l)||/\b(verify|confirm|check|ensure|assert)\b/i.test(d)||/\b(should|must|shall)\b/i.test(d)}).length<t.acceptanceCriteria.length*.5&&(e-=15,r.push("Less than half of acceptance criteria are clearly verifiable"));let o=["looks good","feels right","works well","properly"];for(let c of o)n.includes(c)&&(e-=10,r.push(`Contains subjective term: "${c}"`));return{name:"Measurability",score:Math.max(0,e),weight:this.config.weights.measurability,issues:r}}scoreAtomicity(t){let e=100,r=[],n=t.description.toLowerCase(),s=[/\band\b.*\band\b/i,/\bor\b/i,/\bas well as\b/i,/\bin addition\b/i,/\balso\b/i,/\bfurthermore\b/i];for(let c of s)if(c.test(n)){e-=12,r.push("Contains compound statements that may need splitting");break}t.acceptanceCriteria.length>7&&(e-=15,r.push("Too many acceptance criteria - consider splitting requirement"));let a=["feature","capability","function","ability"],o=0;for(let c of a){let l=n.match(new RegExp(c,"g"));l&&(o+=l.length)}return o>2&&(e-=15,r.push("Multiple features/capabilities mentioned - may not be atomic")),t.description.length>500&&(e-=10,r.push("Description length suggests requirement may not be atomic")),{name:"Atomicity",score:Math.max(0,e),weight:this.config.weights.atomicity,issues:r}}scoreFeasibility(t){let e=100,r=[],n=`${t.description} ${t.acceptanceCriteria.join(" ")}`.toLowerCase(),s=[/100%\s*(availability|uptime|coverage)/i,/zero\s*(defects?|bugs?|errors?)/i,/never\s+(fail|crash|error)/i,/always\s+work/i,/infinite/i,/unlimited/i];for(let o of s)if(o.test(n)){e-=20,r.push("Contains unrealistic or impossible to verify conditions");break}let a=["third-party","external service","external api","hardware","physical","manual"];for(let o of a)n.includes(o)&&(e-=10,r.push(`Testing complicated by external dependency: ${o}`));return/real-time|real time/i.test(n)&&(e-=5,r.push("Real-time requirements require specialized testing")),/compliance|regulation|legal|gdpr|hipaa/i.test(n)&&(e-=5,r.push("Compliance testing may require specialized expertise")),{name:"Feasibility",score:Math.max(0,e),weight:this.config.weights.feasibility,issues:r}}scoreTraceability(t){let e=100,r=[];return(!t.id||t.id.trim()==="")&&(e-=30,r.push("Requirement lacks a unique identifier")),t.title.length<10&&(e-=15,r.push("Title is too short for effective traceability")),t.type||(e-=15,r.push("Requirement type not specified")),t.priority||(e-=10,r.push("Requirement priority not specified")),t.acceptanceCriteria.filter(n=>/\[AC[-\d]+\]|#\d+|AC\d+/i.test(n)).length===0&&t.acceptanceCriteria.length>0&&(e-=10,r.push("Acceptance criteria lack identifiers for test traceability")),{name:"Traceability",score:Math.max(0,e),weight:this.config.weights.traceability,issues:r}}scoreIndependency(t){let e=100,r=[],i=`${t.description} ${t.acceptanceCriteria.join(" ")}`,n=i.toLowerCase(),s=[/depends on/i,/requires\s+(that|the)/i,/after\s+(the|completing)/i,/following\s+completion/i,/prerequisite/i,/blocked by/i];for(let c of s)if(c.test(n)){e-=15,r.push("Has explicit dependencies that complicate isolated testing");break}let a=[/REQ[-_]?\d+/gi,/requirement\s+\d+/gi,/see\s+(also|requirement)/i,/as described in/i];for(let c of a)if(c.test(i)){e-=10,r.push("References other requirements");break}let o=["global state","shared","common data","same session","across all","system-wide"];for(let c of o)if(n.includes(c)){e-=10,r.push(`Involves shared state: "${c}"`);break}return{name:"Independency",score:Math.max(0,e),weight:this.config.weights.independency,issues:r}}categorizeScore(t){return t>=80?"excellent":t>=60?"good":t>=40?"fair":"poor"}getSuggestionsForFactor(t,e){let r=[];switch(t.name){case"Specificity":r.push("Replace ambiguous terms with specific, measurable values"),r.push("Define clear actors (user, system, admin) for each action"),r.push("Add concrete examples or scenarios");break;case"Measurability":r.push("Add quantifiable acceptance criteria (time limits, percentages)"),r.push("Use Given-When-Then format for each acceptance criterion"),r.push("Define success/failure conditions explicitly");break;case"Atomicity":r.push("Split compound requirements into separate, focused items"),r.push("Each requirement should describe one testable behavior"),r.push('Remove "and" chains by creating separate requirements');break;case"Feasibility":r.push("Replace absolute terms (100%, never, always) with realistic thresholds"),r.push("Document test environment requirements for external dependencies"),r.push("Consider mock/stub strategies for third-party integrations");break;case"Traceability":r.push("Ensure requirement has a unique, persistent identifier"),r.push("Add identifiers to each acceptance criterion (e.g., AC-1, AC-2)"),r.push("Link to related design documents or user stories");break;case"Independency":r.push("Document dependencies explicitly for test planning"),r.push("Consider if the requirement can be broken down to reduce dependencies"),r.push("Design tests that can run in isolation with proper setup/teardown");break}return r}async storeScore(t,e){await this.memory.set(`requirements-validation:testability:${t}`,{requirementId:t,score:e,scoredAt:new Date().toISOString()},{namespace:"requirements-validation",ttl:86400*30});let r=`requirements-validation:testability-trend:${t}`,n=await this.memory.get(r)||{scores:[]};n.scores.push({score:e.value,date:new Date().toISOString()}),n.scores.length>10&&(n.scores=n.scores.slice(-10)),await this.memory.set(r,n,{namespace:"requirements-validation",persist:!0})}};se();var Gh={stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],clipEpsilon:.2,lambdaGAE:.95,epochs:4,miniBatchSize:64,entropyCoeff:.01},Ds=class extends ae{actor;critic;oldActor;ppoConfig;actions=[];constructor(t={}){super("ppo","actor-critic"),this.ppoConfig={...Gh,...t},this.initializeActions(),this.actor=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.actorHiddenLayers,this.ppoConfig.actionSize],activations:Array(this.ppoConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.criticHiddenLayers,1],activations:Array(this.ppoConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.oldActor=this.actor.clone()}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.actor.forward(e),i=pe.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:`PPO: ${s.type}`}}async trainCore(t){this.oldActor=this.actor.clone();let e=this.calculateAdvantages(t),r=0;for(let i=0;i<this.ppoConfig.epochs;i++)for(let n=0;n<t.length;n+=this.ppoConfig.miniBatchSize){let s=Math.min(n+this.ppoConfig.miniBatchSize,t.length);for(let a=n;a<s;a++){let o=t[a],c=this.prepareState(o.state),l=this.actionToIndex(o.action),d=e[a]||0,m=this.actor.forward(c),g=pe.forward(m),h=this.oldActor.forward(c),b=pe.forward(h),w=(g[l]+1e-10)/(b[l]+1e-10),C=Math.max(1-this.ppoConfig.clipEpsilon,Math.min(1+this.ppoConfig.clipEpsilon,w)),S=w*d,k=C*d,P=-Math.min(S,k),O=this.critic.forward(c)[0],z=o.reward+this.config.discountFactor*(this.critic.forward(this.prepareState(o.nextState))[0]||0),K=(O-z)**2,Ce=this.calculateEntropy(g),Y=-this.ppoConfig.entropyCoeff*Ce;r+=Math.abs(P+.5*K+Y);let G=new Float32Array(g.length);for(let X=0;X<G.length;X++)G[X]=X===l?-d:0;this.actor.backward(G);for(let X of this.actor.layers)X.update(this.config.learningRate*.1);let ne=new Float32Array([z]);this.critic.train(c,ne,new fe)}}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/(t.length*this.ppoConfig.epochs),explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural PPO for Adaptive Retry Strategies",capabilities:["Clipped surrogate objective","GAE advantage estimation","Multiple epochs per batch"],hyperparameters:{stateSize:this.ppoConfig.stateSize,actionSize:this.ppoConfig.actionSize,clipEpsilon:this.ppoConfig.clipEpsilon,epochs:this.ppoConfig.epochs},stats:this.stats}}calculateAdvantages(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--){let n=t[i],s=this.prepareState(n.state),a=this.prepareState(n.nextState),o=this.critic.forward(s)[0],c=n.done?0:this.critic.forward(a)[0];r=n.reward+this.config.discountFactor*c-o+this.config.discountFactor*this.ppoConfig.lambdaGAE*r,e.unshift(r)}return e}prepareState(t){let e=t.features.slice(0,this.ppoConfig.stateSize);for(;e.length<this.ppoConfig.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:"retry",value:1},{type:"retry",value:2},{type:"retry",value:3},{type:"skip-retry",value:0},{type:"adjust-timeout",value:1.5}],this.ppoConfig.actionSize=this.actions.length,this.actor=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.actorHiddenLayers,this.ppoConfig.actionSize],activations:Array(this.ppoConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.criticHiddenLayers,1],activations:Array(this.ppoConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.oldActor=this.actor.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}sampleAction(t){if(L()<this.config.explorationRate)return le(0,this.actions.length);let e=L(),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(),ppoConfig:this.ppoConfig}}async importCustomData(t){t.actor&&this.actor.setParameters(t.actor),t.critic&&this.critic.setParameters(t.critic),t.ppoConfig&&(this.ppoConfig={...this.ppoConfig,...t.ppoConfig}),this.initialized=!0}async resetAlgorithm(){this.actor=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.actorHiddenLayers,this.ppoConfig.actionSize],activations:Array(this.ppoConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.ppoConfig.stateSize,...this.ppoConfig.criticHiddenLayers,1],activations:Array(this.ppoConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.oldActor=this.actor.clone()}};var Ms={RequirementAnalyzed:"requirements-validation.RequirementAnalyzed",BDDScenariosGenerated:"requirements-validation.BDDScenariosGenerated",RequirementValidated:"requirements-validation.RequirementValidated",SprintValidated:"requirements-validation.SprintValidated",ValidationFailed:"requirements-validation.ValidationFailed"},Hh={maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,minTestabilityThreshold:60,enablePPO:!0,enableSONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},pc=class{constructor(t){this.memory=t}memory;requirements=new Map;async findById(t){if(this.requirements.has(t))return this.requirements.get(t)||null;let e=await this.memory.get(`requirement:${t}`);return e?(this.requirements.set(t,e),e):null}async findByStatus(t){return Array.from(this.requirements.values()).filter(e=>e.status===t)}async findByPriority(t){return Array.from(this.requirements.values()).filter(e=>e.priority===t)}async save(t){this.requirements.set(t.id,t),await this.memory.set(`requirement:${t.id}`,t,{namespace:"requirements-validation",persist:!0})}async delete(t){this.requirements.delete(t),await this.memory.delete(`requirement:${t}`)}},Se=R.create("requirements-validation"),Fs=class extends Q{constructor(e,r,i,n={}){let s={...Hh,...n};super(e,"requirements-validation",s,{verifyFindingTypes:["requirement-conflict","testability-assessment","ambiguous-requirement"]});this.memory=r;this.agentCoordinator=i;this.validator=new gr(r),this.bddWriter=new hr(r),this.testabilityScorer=new fr(r),this.repository=new pc(r)}memory;agentCoordinator;validator;bddWriter;testabilityScorer;repository;ppoAlgorithm;sonaEngine;rlInitialized=!1;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enablePPO||this.config.enableSONA)&&await this.initializeRLIntegrations()}async initializeRLIntegrations(){try{if(this.config.enablePPO&&(this.ppoAlgorithm=new Ds({stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],clipEpsilon:.2,lambdaGAE:.95,epochs:10,miniBatchSize:32,entropyCoeff:.01})),this.config.enableSONA)try{this.sonaEngine=await me({domain:"requirements-validation",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),Se.info("PersistentSONAEngine initialized for pattern learning")}catch(e){Se.error("Failed to initialize PersistentSONAEngine",e instanceof Error?e:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(e){throw Se.error("Failed to initialize RL integrations",e instanceof Error?e:void 0),e}}async onDispose(){if(await this.saveWorkflowState(),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(e){Se.error("Error closing SONA engine",e instanceof Error?e:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async analyzeRequirement(e){let r=v();try{if(this.startWorkflow(r,"analyze"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Se.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Operation paused: topology is in critical state"));let i=await this.repository.findById(e);if(!i)return p(new Error(`Requirement not found: ${e}`));if(this.config.enableSONA&&this.sonaEngine){let d=await this.adaptRequirementPattern(i);d.success&&d.pattern&&Se.info(`[SONA] Adapted pattern with ${d.similarity.toFixed(3)} similarity`)}let n=await this.spawnAnalysisAgent(r,i);if(!n.success)return this.failWorkflow(r,n.error.message),p(n.error);this.addAgentToWorkflow(r,n.value),this.updateWorkflowProgress(r,10);let s=await this.validator.validate(i);if(!s.success)return this.failWorkflow(r,s.error.message),p(s.error);this.updateWorkflowProgress(r,30);let a=await this.testabilityScorer.scoreRequirement(i);if(!a.success)return this.failWorkflow(r,a.error.message),p(a.error);this.updateWorkflowProgress(r,50);let o=await this.validator.detectAmbiguity(i);if(!o.success)return this.failWorkflow(r,o.error.message),p(o.error);this.updateWorkflowProgress(r,70);let c=await this.testabilityScorer.suggestImprovements(i,a.value);this.updateWorkflowProgress(r,90);let l={requirement:i,testabilityScore:a.value,validationErrors:s.value,ambiguityReport:o.value,suggestedImprovements:c.success?c.value:[]};return this.config.enableSONA&&this.sonaEngine&&await this.storeRequirementPattern(i,a.value.value,l),await this.agentCoordinator.stop(n.value),this.completeWorkflow(r),this.config.publishEvents&&await this.publishRequirementAnalyzed(l),f(l)}catch(i){let n=y(i);return this.failWorkflow(r,n.message),this.config.publishEvents&&await this.publishValidationFailed(n,"analyzeRequirement"),{success:!1,error:n}}}async generateTestArtifacts(e){let r=v();try{this.startWorkflow(r,"generate-artifacts");let i=await this.repository.findById(e);if(!i)return p(new Error(`Requirement not found: ${e}`));let n=await this.spawnBDDAgent(r,i);if(!n.success)return this.failWorkflow(r,n.error.message),p(n.error);this.addAgentToWorkflow(r,n.value),this.updateWorkflowProgress(r,20);let s=3;if(this.config.enablePPO&&this.ppoAlgorithm){let g=await this.optimizeScenarioGeneration(i);g.success&&g.value&&(s=this.extractScenarioCount(g.value),Se.info(`[PPO] Optimized scenario count to ${s}`))}let a=await this.bddWriter.generateScenariosWithExamples(i,s);if(!a.success)return this.failWorkflow(r,a.error.message),p(a.error);this.updateWorkflowProgress(r,50);let o=a.value;this.config.enablePPO&&this.ppoAlgorithm&&(o=await this.optimizeScenarioOrdering(i,o));let c=this.bddWriter.toGherkin(o),l={path:`features/${this.sanitizeFilename(i.title)}.feature`,content:c,scenarioCount:o.length};this.updateWorkflowProgress(r,70);let d=this.generateTestCaseOutlines(i,o);this.updateWorkflowProgress(r,90);let m={requirementId:e,bddScenarios:o,gherkinFiles:[l],testCaseOutlines:d};return this.config.enablePPO&&this.ppoAlgorithm&&await this.trainPPOWithScenarioFeedback(i,o,m),await this.agentCoordinator.stop(n.value),this.completeWorkflow(r),this.config.publishEvents&&await this.publishBDDScenariosGenerated(e,o),f(m)}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async validateSprintRequirements(e){let r=v();try{this.startWorkflow(r,"validate-sprint");let i=[];for(let g of e){let h=await this.repository.findById(g);h&&i.push(h)}if(i.length===0)return p(new Error("No requirements found for the specified IDs"));this.updateWorkflowProgress(r,10);let n=await this.testabilityScorer.scoreRequirements(i);if(!n.success)return this.failWorkflow(r,n.error.message),p(n.error);this.updateWorkflowProgress(r,40);let s=new Map;for(let g of i){let h=await this.validator.validate(g);h.success&&s.set(g.id,h.value)}this.updateWorkflowProgress(r,70);let a=await this.validator.analyzeDependencies(i);this.updateWorkflowProgress(r,80);let o=[],c=0,l=0;for(let g of i){let h=n.value.get(g.id),b=s.get(g.id)||[];h&&(l+=h.value,h.value<this.config.minTestabilityThreshold&&o.push({requirementId:g.id,reason:`Testability score (${h.value}) below threshold (${this.config.minTestabilityThreshold})`,severity:h.value<30?"critical":"high"}));let w=b.filter(C=>C.severity==="error");w.length===0?c++:o.push({requirementId:g.id,reason:`Has ${w.length} validation error(s)`,severity:w.length>2?"critical":"high"})}let d=this.generateSprintRecommendations(i,n.value,o,a.success?a.value:void 0),m={totalRequirements:i.length,validRequirements:c,averageTestability:Math.round(l/i.length),blockers:o,recommendations:d};return this.completeWorkflow(r),this.config.publishEvents&&await this.publishSprintValidated(m),f(m)}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async optimizeScenarioGeneration(e){if(!this.ppoAlgorithm||!this.rlInitialized)return p(new Error("PPO not initialized"));try{let r={id:`req-${e.id}`,features:this.extractRequirementFeatures(e)},i=await this.ppoAlgorithm.predict(r);return f(i)}catch(r){return p(y(r))}}async optimizeScenarioOrdering(e,r){if(!this.ppoAlgorithm||!this.rlInitialized)return r;try{let i=await Promise.all(r.map(async n=>{let s=n.given.length+n.when.length+n.then.length,a={id:`scenario-${n.scenario}`,features:[...this.extractRequirementFeatures(e),s,n.examples?.rows.length||0]},o=await this.ppoAlgorithm.predict(a);return{scenario:n,score:o.value||0}}));return i.sort((n,s)=>s.score-n.score),i.map(n=>n.scenario)}catch(i){return Se.error("Failed to optimize scenario ordering",i instanceof Error?i:void 0),r}}async trainPPOWithScenarioFeedback(e,r,i){if(!(!this.ppoAlgorithm||!this.rlInitialized))try{let n={id:`req-${e.id}`,features:this.extractRequirementFeatures(e)},s={type:"generate-scenarios",value:r.length},a=this.calculateScenarioReward(r,i),o={state:n,action:s,reward:a,nextState:n,done:!0};await this.ppoAlgorithm.train(o),Se.info(`[PPO] Trained with reward: ${a.toFixed(3)}`)}catch(n){Se.error("Failed to train PPO",n instanceof Error?n:void 0)}}calculateScenarioReward(e,r){let i=.5,n=e.length;n>=3&&n<=5?i+=.2:n>5&&(i-=.1);let s=r.testCaseOutlines.length;i+=Math.min(.3,s*.05);let a=e.filter(o=>o.examples&&o.examples.rows.length>0).length;return i+=a/e.length*.2,Math.max(0,Math.min(1,i))}extractScenarioCount(e){return e.action.type==="generate-scenarios"&&typeof e.action.value=="number"?Math.max(1,Math.min(10,Math.round(e.action.value))):3}extractRequirementFeatures(e){return[e.title.length,e.description.length,e.acceptanceCriteria.length,e.priority==="critical"?1:e.priority==="high"?.5:0,e.type==="functional"?1:0,e.type==="non-functional"?1:0,e.dependencies?.length||0,(e.tags??[]).length,e.estimatedComplexity||.5,e.status==="approved"?1:0]}async adaptRequirementPattern(e){if(!this.sonaEngine||!this.rlInitialized)return{success:!1,pattern:null,similarity:0};try{let r={id:`req-${e.id}`,features:this.extractRequirementFeatures(e)},i=await this.sonaEngine.adaptPattern(r,"test-generation","requirements-validation");return{success:i.success,pattern:i.pattern,similarity:i.similarity}}catch(r){return Se.error("Failed to adapt requirement pattern",r instanceof Error?r:void 0),{success:!1,pattern:null,similarity:0}}}async storeRequirementPattern(e,r,i){if(!(!this.sonaEngine||!this.rlInitialized))try{let n={id:`req-${e.id}`,features:this.extractRequirementFeatures(e)},s={type:"validate",value:r},a={reward:r/100,success:r>=this.config.minTestabilityThreshold,quality:r/100},o=this.sonaEngine.createPattern(n,s,a,"test-generation","requirements-validation",{requirementId:e.id,requirementType:e.type,validationErrorCount:i.validationErrors.length,ambiguityScore:i.ambiguityReport.overallScore});Se.info(`[SONA] Stored pattern ${o.id} for requirement ${e.id}`)}catch(n){Se.error("Failed to store requirement pattern",n instanceof Error?n:void 0)}}async spawnAnalysisAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`req-analyzer-${e.slice(0,8)}`,domain:"requirements-validation",type:"analyzer",capabilities:["requirements-analysis","testability-scoring","ambiguity-detection"],config:{workflowId:e,requirementId:r.id,requirementType:r.type}};return this.agentCoordinator.spawn(i)}async spawnBDDAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`bdd-generator-${e.slice(0,8)}`,domain:"requirements-validation",type:"generator",capabilities:["bdd-generation","gherkin","scenario-writing"],config:{workflowId:e,requirementId:r.id}};return this.agentCoordinator.spawn(i)}async publishRequirementAnalyzed(e){let r=D(Ms.RequirementAnalyzed,"requirements-validation",{requirementId:e.requirement.id,testabilityScore:e.testabilityScore.value,testabilityCategory:e.testabilityScore.category,validationErrorCount:e.validationErrors.length,ambiguityScore:e.ambiguityReport.overallScore,suggestedImprovementsCount:e.suggestedImprovements.length});await this.eventBus.publish(r)}async publishBDDScenariosGenerated(e,r){let i=D(Ms.BDDScenariosGenerated,"requirements-validation",{requirementId:e,scenarioCount:r.length,tags:[...new Set(r.flatMap(n=>n.tags))]});await this.eventBus.publish(i)}async publishSprintValidated(e){let r=D(Ms.SprintValidated,"requirements-validation",{totalRequirements:e.totalRequirements,validRequirements:e.validRequirements,averageTestability:e.averageTestability,blockerCount:e.blockers.length,criticalBlockers:e.blockers.filter(i=>i.severity==="critical").length});await this.eventBus.publish(r)}async publishValidationFailed(e,r){let i=D(Ms.ValidationFailed,"requirements-validation",{error:e.message,context:r,timestamp:new Date().toISOString()});await this.eventBus.publish(i)}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this))}async handleImpactAnalysis(e){}async handleTestGenerated(e){}generateTestCaseOutlines(e,r){return r.map((i,n)=>({id:`TC-${e.id}-${n+1}`,title:i.scenario,steps:[...i.given.map(s=>`Setup: ${s}`),...i.when.map(s=>`Action: ${s}`),...i.then.map(s=>`Verify: ${s}`)],expectedResults:i.then,testData:i.examples?this.extractTestDataFromExamples(i.examples):{}}))}extractTestDataFromExamples(e){let r={};for(let i=0;i<e.headers.length;i++){let n=e.headers[i];r[n]=e.rows.map(s=>s[i])}return r}generateSprintRecommendations(e,r,i,n){let s=[],a=i.filter(d=>d.severity==="critical");a.length>0&&s.push(`Address ${a.length} critical blocker(s) before sprint planning`);let o=Array.from(r.entries()).filter(([,d])=>d.value<this.config.minTestabilityThreshold);if(o.length>0&&s.push(`Improve testability for ${o.length} requirement(s) scoring below ${this.config.minTestabilityThreshold}`),n){let d=this.findHeavilyDependedRequirements(e,n.edges);d.length>0&&s.push(`Prioritize ${d.length} requirement(s) that block others`)}let c=e.filter(d=>d.priority==="critical");c.length>0&&s.push(`Ensure ${c.length} critical priority requirement(s) are addressed first`);let l=Array.from(r.values()).reduce((d,m)=>d+m.value,0)/r.size;return l<70&&s.push(`Overall testability average (${Math.round(l)}) is below recommended level of 70`),s.length===0&&s.push("Sprint requirements are well-defined and ready for development"),s}findHeavilyDependedRequirements(e,r){let i=new Map;for(let n of r)if(n.type==="depends-on"){let s=i.get(n.to)||0;i.set(n.to,s+1)}return Array.from(i.entries()).filter(([,n])=>n>=2).map(([n])=>n)}sanitizeFilename(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}async loadWorkflowState(){let e=await this.memory.get("requirements-validation: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("requirements-validation:coordinator:workflows",e,{namespace:"requirements-validation",persist:!0})}requiresConsensus(e){return this.consensusMixin.requiresConsensus(e)}async verifyFinding(e){return this.consensusMixin.verifyFinding(e)}async verifyRequirementConflict(e,r){let i=V({id:v(),type:"requirement-conflict",confidence:r,description:`Requirement conflict detected: ${e.description}`,payload:e,detectedBy:"requirements-validation-coordinator",severity:e.severity==="high"?"high":e.severity==="medium"?"medium":"low"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return!!(n.success&&n.value.verdict==="verified")}return!0}async verifyTestabilityAssessment(e,r){let i=V({id:v(),type:"testability-assessment",confidence:r,description:`Testability assessment for ${e.requirementId}: score ${e.score} (${e.category})`,payload:e,detectedBy:"requirements-validation-coordinator",severity:e.score<30?"critical":e.score<60?"high":"medium"});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)}};A();se();var gc=class{initialized=!1;memory;constructor(t){this.memory=t}async initialize(){this.initialized||(this.initialized=!0)}async dispose(){this.initialized=!1}registerWorkflowActions(t){if(!this.initialized)throw new Error("QCSDIdeationPlugin must be initialized before registering workflow actions");t.registerAction("requirements-validation","analyzeQualityCriteria",this.analyzeQualityCriteria.bind(this)),t.registerAction("requirements-validation","assessTestability",this.assessTestability.bind(this)),t.registerAction("requirements-validation","assessRisks",this.assessRisks.bind(this)),t.registerAction("requirements-validation","validateRequirements",this.validateRequirements.bind(this)),t.registerAction("security-compliance","modelSecurityThreats",this.modelSecurityThreats.bind(this)),t.registerAction("requirements-validation","generateIdeationReport",this.generateIdeationReport.bind(this)),t.registerAction("learning-optimization","storeIdeationLearnings",this.storeIdeationLearnings.bind(this)),t.registerAction("requirements-validation","extractWebsiteContent",this.extractWebsiteContent.bind(this)),t.registerAction("visual-accessibility","auditAccessibility",this.auditAccessibility.bind(this)),t.registerAction("coordination","analyzeQualityExperience",this.analyzeQualityExperience.bind(this))}async extractWebsiteContent(t,e){try{let r=t.url||e.input.url;if(!r)return f({url:"",isWebsite:!1,extractedDescription:e.input.description||"",extractedFeatures:[],extractedAcceptanceCriteria:e.input.acceptanceCriteria||[],detectedFlags:{hasUI:!1,hasSecurity:!1,hasUX:!1}});let i;try{i=new URL(r)}catch{return p(new Error(`Invalid URL: ${r}`))}let n=await this.fetchWebsiteContent(i.toString());if(!n.success)return p(n.error);let s=n.value,a=this.parseWebsiteContent(s,i),o=this.buildEpicDescription(a,i),c=this.generateAcceptanceCriteria(a),l=this.detectContentFlags(s,a);return f({url:i.toString(),isWebsite:!0,extractedDescription:o,extractedFeatures:a.features,extractedAcceptanceCriteria:c,detectedFlags:l,metadata:{title:a.title,pageCount:1,extractedAt:new Date().toISOString()}})}catch(r){return p(new Error(`Website extraction failed: ${T(r)}`))}}async fetchWebsiteContent(t){try{let e=await fetch(t,{headers:{"User-Agent":"AQE-QCSD-Ideation-Swarm/1.0 (Quality Assessment Bot)",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language":"en-US,en;q=0.5"},signal:AbortSignal.timeout(3e4)});if(!e.ok)return p(new Error(`HTTP ${e.status}: ${e.statusText}`));let r=await e.text();return f(r)}catch(e){return p(new Error(`Fetch failed: ${T(e)}`))}}parseWebsiteContent(t,e){let r=[],i=[],n=[],s=t.match(/<title[^>]*>([^<]+)<\/title>/i),a=s?s[1].trim():e.hostname,o=[{pattern:/type\s*=\s*["']search["']/i,feature:"Search functionality",ui:"Search input"},{pattern:/shopping[-_]?cart|cart[-_]?icon|add[-_]?to[-_]?cart/i,feature:"Shopping cart",ui:"Cart component"},{pattern:/login|sign[-_]?in|log[-_]?in/i,feature:"User authentication",ui:"Login form"},{pattern:/register|sign[-_]?up|create[-_]?account/i,feature:"User registration",ui:"Registration form"},{pattern:/checkout|payment|pay[-_]?now/i,feature:"Checkout process",ui:"Checkout flow"},{pattern:/product[-_]?list|product[-_]?grid|catalog/i,feature:"Product catalog",ui:"Product grid"},{pattern:/filter|sort[-_]?by|refine/i,feature:"Filtering and sorting",ui:"Filter controls"},{pattern:/wishlist|favorites|save[-_]?for[-_]?later/i,feature:"Wishlist functionality",ui:"Wishlist button"},{pattern:/review|rating|stars/i,feature:"Reviews and ratings",ui:"Rating component"},{pattern:/newsletter|subscribe|email[-_]?signup/i,feature:"Newsletter subscription",ui:"Subscription form"},{pattern:/navigation|nav[-_]?menu|main[-_]?menu/i,feature:"Site navigation",ui:"Navigation menu"},{pattern:/footer|site[-_]?map/i,feature:"Footer navigation",ui:"Footer component"},{pattern:/modal|popup|dialog/i,feature:"Modal dialogs",ui:"Modal component"},{pattern:/carousel|slider|slideshow/i,feature:"Image carousel",ui:"Carousel component"},{pattern:/accordion|collapsible|expandable/i,feature:"Accordion sections",ui:"Accordion component"},{pattern:/tab|tabbed[-_]?content/i,feature:"Tabbed content",ui:"Tab component"},{pattern:/form|input|textarea|select/i,feature:"Form interactions",ui:"Form elements"},{pattern:/video|player|embed/i,feature:"Video content",ui:"Video player"},{pattern:/chat|support|help[-_]?desk/i,feature:"Customer support",ui:"Chat widget"},{pattern:/cookie|consent|gdpr|privacy/i,feature:"Privacy compliance",ui:"Consent banner"}];for(let{pattern:b,feature:w,ui:C}of o)b.test(t)&&(r.push(w),C&&i.push(C));let c=[{pattern:/password|passwd/i,feature:"Password handling"},{pattern:/https|ssl|secure/i,feature:"Secure connection"},{pattern:/oauth|sso|single[-_]?sign[-_]?on/i,feature:"OAuth/SSO authentication"},{pattern:/2fa|two[-_]?factor|mfa/i,feature:"Multi-factor authentication"},{pattern:/captcha|recaptcha/i,feature:"Bot protection"},{pattern:/csrf|token/i,feature:"CSRF protection"},{pattern:/encrypt|crypto/i,feature:"Data encryption"}];for(let{pattern:b,feature:w}of c)b.test(t)&&n.push(w);let l=(t.match(/<form/gi)||[]).length,d=(t.match(/<button/gi)||[]).length,m=(t.match(/<input/gi)||[]).length,g=(t.match(/<a\s+[^>]*href/gi)||[]).length,h=(t.match(/<img/gi)||[]).length;return{title:a,features:[...new Set(r)],uiComponents:[...new Set(i)],securityFeatures:[...new Set(n)],metrics:{formCount:l,buttonCount:d,inputCount:m,linkCount:g,imageCount:h}}}buildEpicDescription(t,e){let r=[`## Website Analysis: ${t.title}`,`**URL**: ${e.toString()}`,`**Domain**: ${e.hostname}`,"","### Detected Features"];if(t.features.length>0)for(let i of t.features)r.push(`- ${i}`);else r.push("- Basic web content");if(r.push("","### UI Components"),t.uiComponents.length>0)for(let i of t.uiComponents)r.push(`- ${i}`);else r.push("- Standard HTML elements");if(t.securityFeatures.length>0){r.push("","### Security Features");for(let i of t.securityFeatures)r.push(`- ${i}`)}return r.push("","### Page Metrics"),r.push(`- Forms: ${t.metrics.formCount}`),r.push(`- Buttons: ${t.metrics.buttonCount}`),r.push(`- Input fields: ${t.metrics.inputCount}`),r.push(`- Links: ${t.metrics.linkCount}`),r.push(`- Images: ${t.metrics.imageCount}`),r.join(`
2849
+ `)}generateAcceptanceCriteria(t){let e=[],r={"Search functionality":"User can search for content and receive relevant results","Shopping cart":"User can add items to cart and view cart contents","User authentication":"User can log in with valid credentials","User registration":"New user can create an account","Checkout process":"User can complete purchase with valid payment","Product catalog":"User can browse and view product listings","Filtering and sorting":"User can filter and sort content by various criteria","Wishlist functionality":"User can save items for later","Reviews and ratings":"User can view and submit reviews","Newsletter subscription":"User can subscribe to email updates","Site navigation":"User can navigate between all main sections","Modal dialogs":"Modal dialogs are accessible and dismissible","Form interactions":"All forms validate input and show clear error messages","Video content":"Video content is playable and accessible","Customer support":"User can access help and support resources","Privacy compliance":"Cookie consent is properly implemented"};for(let i of t.features)r[i]&&e.push(r[i]);return e.length===0&&e.push("Page loads within acceptable time","Content is readable and well-structured","Navigation is intuitive"),e}detectContentFlags(t,e){let r=e.uiComponents.length>0||e.metrics.formCount>0||e.metrics.buttonCount>0||/<(button|input|select|form|img|video|canvas)/i.test(t),i=e.securityFeatures.length>0||/login|password|auth|token|session|credential/i.test(t),n=e.features.length>=3||e.metrics.formCount>=2||/user[-_]?experience|ux|journey|onboarding|tutorial/i.test(t);return{hasUI:r,hasSecurity:i,hasUX:n}}async analyzeQualityCriteria(t,e){try{let r=t.targetId||e.input.targetId,i=t.targetType||e.input.targetType,n=t.description||e.input.description||"",s=t.acceptanceCriteria||e.input.acceptanceCriteria||[],a=this.analyzeHTSMCategories(r,i,n,s),o=this.calculateQualityScore(a);return await this.memory.set(`qcsd-ideation:quality-criteria:${r}`,{criteria:a,qualityScore:o,timestamp:new Date().toISOString()},{namespace:"qcsd-ideation",ttl:3600}),f({qualityCriteria:a,qualityScore:o})}catch(r){return p(y(r))}}async assessTestability(t,e){try{let r=t.targetId||e.input.targetId,i=t.description||e.input.description||"",n=t.acceptanceCriteria||e.input.acceptanceCriteria||[],s=this.assessTestabilityPrinciples(i,n),a=Math.round(Object.values(s).reduce((d,m)=>d+m,0)/10),{blockers:o,recommendations:c}=this.identifyTestabilityIssues(s),l={id:v(),targetId:r,overallScore:a,principles:s,blockers:o,recommendations:c};return await this.memory.set(`qcsd-ideation:testability:${r}`,l,{namespace:"qcsd-ideation",ttl:3600}),f(l)}catch(r){return p(y(r))}}async assessRisks(t,e){try{let r=t.targetId||e.input.targetId,i=t.targetType||e.input.targetType,n=t.description||e.input.description||"",s=this.analyzeRiskFactors(i,n),a=Math.round(s.reduce((d,m)=>d+m.score,0)/s.length*4),o=this.determineRiskLevel(a),c=this.generateMitigations(s),l={id:v(),targetId:r,overallRisk:o,riskScore:a,factors:s,mitigations:c};return await this.memory.set(`qcsd-ideation:risk:${r}`,l,{namespace:"qcsd-ideation",ttl:3600}),f(l)}catch(r){return p(y(r))}}async validateRequirements(t,e){try{let r=t.targetId||e.input.targetId,i=t.description||e.input.description||"",n=t.acceptanceCriteria||e.input.acceptanceCriteria||[],s=[],a=[];i.length<50&&(s.push("Description is too short (< 50 characters)"),a.push("Add more context about the business value and user need"));let o=["should","could","might","maybe","possibly","etc","and so on"];for(let d of o)i.toLowerCase().includes(d)&&(s.push(`Ambiguous term detected: "${d}"`),a.push(`Replace "${d}" with specific, measurable criteria`));n.length===0?(s.push("No acceptance criteria defined"),a.push("Add Given/When/Then acceptance criteria")):n.length<3&&(s.push("Too few acceptance criteria (< 3)"),a.push("Consider adding criteria for happy path, error cases, and edge cases")),!n.some(d=>d.toLowerCase().includes("given")||d.toLowerCase().includes("when")||d.toLowerCase().includes("then"))&&n.length>0&&a.push("Consider using Given/When/Then format for clearer test scenarios");let l=s.length===0;return f({valid:l,issues:s,suggestions:a})}catch(r){return p(y(r))}}async modelSecurityThreats(t,e){try{let r=t.targetId||e.input.targetId,i=t.description||e.input.description||"",n=t.securityCritical||e.input.securityCritical||!1,s=this.analyzeSTRIDEThreats(i,n),a=Math.max(...s.map(d=>d.likelihood*d.impact),0),o=this.determineRiskLevel(a*4),c=this.generateSecurityRecommendations(s),l={id:v(),targetId:r,threats:s,overallRisk:o,recommendations:c};return await this.memory.set(`qcsd-ideation:threat-model:${r}`,l,{namespace:"qcsd-ideation",ttl:3600}),f(l)}catch(r){return p(y(r))}}async generateIdeationReport(t,e){try{let r=t.targetId||e.input.targetId,i=t.targetType||e.input.targetType||"requirement",n=await this.memory.get(`qcsd-ideation:quality-criteria:${r}`),s=await this.memory.get(`qcsd-ideation:testability:${r}`),a=await this.memory.get(`qcsd-ideation:risk:${r}`),o=await this.memory.get(`qcsd-ideation:threat-model:${r}`),c=e.results,l=n?.criteria||c["quality-criteria-analysis"]?.qualityCriteria||[],d=n?.qualityScore||c["quality-criteria-analysis"]?.qualityScore||0,m=s||c["testability-assessment"],g=a||c["risk-assessment"],h=o||c["security-threat-modeling"],b=this.generateSWOTInsights(l,m,g),w=this.generateRecommendations(l,m,g,h),C=this.generateTestStrategy(l,m,g),S=this.identifyBlockers(m,g,h),k=S.length===0,P={id:v(),timestamp:new Date().toISOString(),targetId:r,targetType:i,qualityCriteria:l,qualityScore:d,testability:m,risk:g,threatModel:h,insights:b,recommendations:w,testStrategy:C,readyForDevelopment:k,blockers:S};return await this.memory.set(`qcsd-ideation:report:${r}`,P,{namespace:"qcsd-ideation",persist:!0}),f(P)}catch(r){return p(y(r))}}async storeIdeationLearnings(t,e){try{let r=t.targetId||e.input.targetId,i=t.report||e.results["aggregate-ideation-report"];if(!i)return p(new Error("No ideation report found to store"));let n=`ideation-pattern-${Date.now()}`,s={id:n,timestamp:new Date().toISOString(),targetType:i.targetType,qualityScore:i.qualityScore,testabilityScore:i.testability.overallScore,riskLevel:i.risk.overallRisk,blockerCount:i.blockers.length,readyForDevelopment:i.readyForDevelopment,features:{hasSecurityThreats:!!i.threatModel&&i.threatModel.threats.length>0,avgPrincipleScore:i.testability.overallScore,riskFactorCount:i.risk.factors.length,qualityCriteriaCount:i.qualityCriteria.length}};await this.memory.set(`qcsd-patterns:${n}`,s,{namespace:"learning",persist:!0});let a=await this.memory.get("qcsd-patterns:index")||[];return a.push(n),await this.memory.set("qcsd-patterns:index",a,{namespace:"learning",persist:!0}),f({stored:!0,patternId:n})}catch(r){return p(y(r))}}analyzeHTSMCategories(t,e,r,i){let n=["capability","reliability","usability","charisma","security","scalability","compatibility","performance","installability","supportability"],s=r.toLowerCase(),a=i.join(" ").toLowerCase();return n.map(o=>{let{weight:c,testabilityScore:l,risks:d,testIdeas:m}=this.analyzeCategory(o,s,a);return{id:`${t}-${o}`,category:o,name:o.charAt(0).toUpperCase()+o.slice(1),description:this.getCategoryDescription(o),weight:c,testabilityScore:l,risks:d,testIdeas:m}})}analyzeCategory(t,e,r){let n={capability:["function","feature","ability","can","must","shall"],reliability:["reliable","consistent","stable","fault","error","recover"],usability:["user","easy","intuitive","accessible","ux","interface"],charisma:["design","look","feel","brand","aesthetic","appeal"],security:["secure","auth","encrypt","protect","permission","role"],scalability:["scale","load","concurrent","throughput","capacity"],compatibility:["integrate","api","browser","device","version","legacy"],performance:["fast","response","latency","speed","efficient","optimize"],installability:["install","deploy","setup","configure","provision"],supportability:["log","monitor","debug","maintain","document","support"]}[t],s=n.filter(m=>e.includes(m)||r.includes(m)).length,a=Math.min(10,3+s*2),c=n.some(m=>r.includes(m))?70+L()*20:40+L()*30,l=this.generateCategoryRisks(t,s===0),d=this.generateCategoryTestIdeas(t);return{weight:a,testabilityScore:Math.round(c),risks:l,testIdeas:d}}getCategoryDescription(t){return{capability:"Core functionality and features the system must provide",reliability:"Consistency and stability under various conditions",usability:"Ease of use and user experience quality",charisma:"Visual appeal and brand alignment",security:"Protection against threats and unauthorized access",scalability:"Ability to handle growth and increased load",compatibility:"Integration with other systems and environments",performance:"Speed, responsiveness, and resource efficiency",installability:"Ease of deployment and configuration",supportability:"Maintainability and operational support"}[t]}generateCategoryRisks(t,e){let r=[];e&&r.push(`${t.charAt(0).toUpperCase()+t.slice(1)} requirements not explicitly defined`);let i={capability:["Feature gaps may emerge late","Edge cases not covered"],reliability:["System may fail under load","Error handling unclear"],usability:["User confusion possible","Accessibility gaps"],charisma:["Brand inconsistency risk","Visual regression possible"],security:["Vulnerability exposure","Data breach risk"],scalability:["Performance degradation at scale","Resource exhaustion"],compatibility:["Integration failures","Version conflicts"],performance:["Slow response times","Resource bottlenecks"],installability:["Deployment complexity","Configuration errors"],supportability:["Debugging difficulty","Maintenance burden"]};return r.push(...i[t].slice(0,e?2:1)),r}generateCategoryTestIdeas(t){return{capability:["Happy path scenarios","Boundary value analysis","State transition tests"],reliability:["Stress testing","Recovery testing","Long-running tests"],usability:["User journey tests","Accessibility audits","Heuristic evaluation"],charisma:["Visual regression tests","Brand guideline validation","A/B testing"],security:["Penetration testing","Auth flow tests","Input validation"],scalability:["Load testing","Capacity testing","Horizontal scaling tests"],compatibility:["Cross-browser tests","API contract tests","Migration tests"],performance:["Response time tests","Throughput tests","Resource monitoring"],installability:["Deployment verification","Configuration tests","Rollback tests"],supportability:["Log validation","Monitoring checks","Runbook validation"]}[t]}calculateQualityScore(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n.weight,0),r=t.reduce((i,n)=>i+n.testabilityScore*n.weight/e,0);return Math.round(r)}assessTestabilityPrinciples(t,e){let r=e.length,i=t.length,n=e.some(s=>s.toLowerCase().includes("given")||s.toLowerCase().includes("when"));return{controllability:Math.min(100,40+r*10),observability:n?80:50,isolability:Math.min(100,50+L()*30),separationOfConcerns:Math.min(100,40+L()*40),simplicity:Math.max(30,100-i/20),stability:Math.min(100,60+L()*20),informationCapture:n?85:45,automationSupport:n?90:40,selfDocumenting:Math.min(100,30+i/10),independence:Math.min(100,50+L()*30)}}identifyTestabilityIssues(t){let e=[],r=[];return t.controllability<50&&e.push("Low controllability - test setup may be difficult"),t.observability<50&&e.push("Low observability - verifying outcomes may be challenging"),t.automationSupport<50&&r.push("Add explicit acceptance criteria in Given/When/Then format"),t.isolability<60&&r.push("Consider breaking into smaller, isolated components"),t.simplicity<40&&r.push("Simplify requirements - current description is complex"),{blockers:e,recommendations:r}}analyzeRiskFactors(t,e){let r=[],i=e.toLowerCase();return e.length>500&&r.push({category:"Complexity",description:"High description complexity increases misunderstanding risk",likelihood:4,impact:3,score:12}),(i.includes("api")||i.includes("integrate"))&&r.push({category:"Integration",description:"External dependencies may cause integration issues",likelihood:3,impact:4,score:12}),(i.includes("user")||i.includes("data")||i.includes("auth"))&&r.push({category:"Security",description:"User data handling requires security considerations",likelihood:3,impact:5,score:15}),(i.includes("real-time")||i.includes("fast")||i.includes("scale"))&&r.push({category:"Performance",description:"Performance requirements may be challenging to meet",likelihood:3,impact:3,score:9}),r.length===0&&r.push({category:"General",description:"Standard development risks apply",likelihood:2,impact:2,score:4}),r}determineRiskLevel(t){return t>=80?"critical":t>=60?"high":t>=40?"medium":"low"}generateMitigations(t){let e=[];for(let r of t)switch(r.category){case"Complexity":e.push("Break down into smaller, more manageable stories");break;case"Integration":e.push("Define API contracts early with contract testing");break;case"Security":e.push("Conduct threat modeling and security review");break;case"Performance":e.push("Establish performance baselines and monitoring");break;default:e.push("Apply standard QE practices")}return e}analyzeSTRIDEThreats(t,e){let r=[],i=t.toLowerCase();return(i.includes("auth")||i.includes("login")||i.includes("user"))&&r.push({category:"spoofing",name:"Identity Spoofing",description:"Attacker may impersonate legitimate users",likelihood:e?4:2,impact:4,mitigations:["Implement MFA","Use strong session management"]}),(i.includes("data")||i.includes("update")||i.includes("edit"))&&r.push({category:"tampering",name:"Data Tampering",description:"Data may be modified maliciously",likelihood:e?3:2,impact:4,mitigations:["Implement input validation","Use integrity checks"]}),(i.includes("personal")||i.includes("sensitive")||i.includes("private"))&&r.push({category:"informationDisclosure",name:"Information Disclosure",description:"Sensitive information may be exposed",likelihood:e?4:3,impact:5,mitigations:["Encrypt data at rest and in transit","Implement access controls"]}),r.length===0&&!e&&r.push({category:"denial",name:"Service Denial",description:"Service availability may be impacted",likelihood:2,impact:3,mitigations:["Implement rate limiting","Add monitoring and alerts"]}),r}generateSecurityRecommendations(t){let e=new Set;for(let r of t)for(let i of r.mitigations)e.add(i);return Array.from(e)}generateSWOTInsights(t,e,r){let i=[],n=[],s=[],a=[],o=t.filter(l=>l.testabilityScore>=70);o.length>5&&i.push(`${o.length}/10 quality categories have high testability`),e.overallScore>=70&&i.push("Overall testability score is good"),r.overallRisk==="low"&&i.push("Risk profile is manageable");let c=t.filter(l=>l.testabilityScore<50);return c.length>0&&n.push(`${c.length} quality categories need more definition`),e.blockers.length>0&&n.push(...e.blockers.slice(0,2)),e.principles.automationSupport>=70&&s.push("High automation potential for test coverage"),s.push("Early quality assessment enables shift-left testing"),r.factors.some(l=>l.score>=15)&&a.push("High-severity risks require immediate attention"),a.push(...r.factors.filter(l=>l.score>=10).map(l=>l.description).slice(0,2)),{strengths:i,weaknesses:n,opportunities:s,threats:a}}generateRecommendations(t,e,r,i){let n=[];e.overallScore<60&&n.push({priority:"high",category:"Testability",description:"Improve acceptance criteria with specific, measurable outcomes",effort:"low"});for(let a of r.factors.filter(o=>o.score>=12))n.push({priority:a.score>=15?"critical":"high",category:"Risk Mitigation",description:r.mitigations[0]||`Address ${a.category} risk`,effort:"medium"});i&&i.threats.length>0&&n.push({priority:i.overallRisk==="critical"?"critical":"high",category:"Security",description:i.recommendations[0]||"Implement security controls",effort:"high"});let s=t.filter(a=>a.testabilityScore<50);return s.length>0&&n.push({priority:"medium",category:"Quality Definition",description:`Define clearer criteria for: ${s.map(a=>a.category).join(", ")}`,effort:"low"}),n.sort((a,o)=>{let c={critical:0,high:1,medium:2,low:3};return c[a.priority]-c[o.priority]})}generateTestStrategy(t,e,r){let i="Standard test pyramid with unit, integration, and E2E tests";(r.overallRisk==="high"||r.overallRisk==="critical")&&(i="Risk-based testing with enhanced coverage for high-risk areas"),e.overallScore>=80&&(i+=" with high automation potential");let n=t.filter(c=>c.weight>=5).flatMap(c=>c.testIdeas.slice(0,2)),s=r.factors.filter(c=>c.score>=9).map(c=>`${c.category}: ${c.description}`),a=t.reduce((c,l)=>c+l.weight,0),o="Medium (3-5 days)";return a>60?o="High (1-2 weeks)":a<40&&(o="Low (1-2 days)"),{approach:i,coverage:[...new Set(n)].slice(0,8),riskAreas:s.slice(0,4),estimatedEffort:o}}async auditAccessibility(t,e){try{let r=t.targetId||e.input.targetId,i=t.url||e.input.url,n=t.description||e.input.description||"",s=t.features||e.input.features||[],a=[],o=[],c={"Image carousel":{issue:"Carousels may lack pause controls and keyboard navigation",rec:"Ensure carousel has pause button, keyboard controls, and ARIA labels"},"Form interactions":{issue:"Forms may lack proper labels and error announcements",rec:"Add aria-describedby for errors, ensure all inputs have associated labels"},"Modal dialogs":{issue:"Modals may trap focus or lack escape key handling",rec:"Implement focus trap, escape key closure, and return focus on close"},"Video content":{issue:"Videos may lack captions and audio descriptions",rec:"Add WebVTT captions and audio description track for video content"},"Site navigation":{issue:"Navigation may lack skip links and landmark roles",rec:"Add skip-to-main link, use proper landmark roles (nav, main, aside)"},"Newsletter subscription":{issue:"Signup forms may lack clear success/error feedback",rec:"Use aria-live regions for form submission feedback"}};for(let d of s){let m=c[d];m&&(a.push(m.issue),o.push(m.rec))}o.push("Verify color contrast meets WCAG 2.2 AA (4.5:1 for text)","Test with screen reader (NVDA/VoiceOver)","Verify keyboard navigation for all interactive elements","Check focus indicators are visible");let l=a.length>5?"Likely fails AA":a.length>2?"Partial AA compliance":"Potential AA compliance";return await this.memory.set(`qcsd-ideation:accessibility:${r}`,{wcagLevel:l,violations:a,recommendations:o,url:i,timestamp:new Date().toISOString()},{namespace:"qcsd-ideation",ttl:3600}),f({wcagLevel:l,violations:a,recommendations:o})}catch(r){return p(y(r))}}async analyzeQualityExperience(t,e){try{let r=t.targetId||e.input.targetId,i=t.url||e.input.url,n=t.description||e.input.description||"",s=t.features||e.input.features||[],a=[],o=[],c=[],l={"Newsletter subscription":{journey:"Content subscription flow: Landing -> Email signup -> Confirmation",friction:"Multi-step signup may cause abandonment",rec:"Implement single-field inline signup with immediate feedback"},"Search functionality":{journey:"Content discovery flow: Search -> Filter -> Select -> Read",friction:"Poor search results relevance frustrates users",rec:'Add search suggestions, filters, and "no results" helpful messaging'},"User authentication":{journey:"Account access flow: Login page -> Auth -> Dashboard",friction:"Password requirements and recovery flow complexity",rec:"Add social login options, clear password requirements, easy recovery"},"Shopping cart":{journey:"Purchase flow: Browse -> Add to cart -> Checkout -> Payment",friction:"Cart abandonment at checkout due to complexity",rec:"Guest checkout, progress indicator, saved cart, multiple payment options"},"Comment system":{journey:"Engagement flow: Read article -> Scroll to comments -> Write comment",friction:"Login requirement for commenting reduces engagement",rec:"Allow guest comments with moderation, or social login for quick auth"},"PDF downloads":{journey:"Content access flow: Browse catalog -> Select issue -> Download PDF",friction:"Large file sizes and unclear progress",rec:"Show file size before download, progress indicator, resume support"}};for(let d of s){let m=l[d];m&&(a.push(m.journey),o.push(m.friction),c.push(m.rec))}return c.push("Map complete user journeys with entry/exit points","Identify drop-off points using analytics","Test critical paths with real users","Monitor Core Web Vitals for performance impact on UX"),await this.memory.set(`qcsd-ideation:qx:${r}`,{journeys:a,frictionPoints:o,recommendations:c,url:i,timestamp:new Date().toISOString()},{namespace:"qcsd-ideation",ttl:3600}),f({journeys:a,frictionPoints:o,recommendations:c})}catch(r){return p(y(r))}}identifyBlockers(t,e,r){let i=[];return t.overallScore<40&&i.push("Testability score too low - cannot verify acceptance criteria"),i.push(...t.blockers),e.overallRisk==="critical"&&i.push("Critical risk level requires risk mitigation before development"),r&&r.overallRisk==="critical"&&i.push("Critical security threats must be addressed before development"),i}};function vd(u){return new gc(u)}A();var hc=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;validator=null;bddWriter=null;testabilityScorer=null;qcsdIdeationPlugin=null;pluginConfig;get name(){return"requirements-validation"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{validate:this.validate.bind(this),validateAgainstCriteria:this.validateAgainstCriteria.bind(this),detectAmbiguity:this.detectAmbiguity.bind(this),analyzeDependencies:this.analyzeDependencies.bind(this),scoreRequirement:this.scoreRequirement.bind(this),scoreRequirements:this.scoreRequirements.bind(this),suggestImprovements:this.suggestImprovements.bind(this),meetsThreshold:this.meetsThreshold.bind(this),generateScenarios:this.generateScenarios.bind(this),generateScenariosWithExamples:this.generateScenariosWithExamples.bind(this),toGherkin:this.toGherkin.bind(this),parseGherkin:this.parseGherkin.bind(this),analyzeRequirement:this.analyzeRequirement.bind(this),generateTestArtifacts:this.generateTestArtifacts.bind(this),validateSprintRequirements:this.validateSprintRequirements.bind(this),getCoordinator:()=>this.coordinator,getValidator:()=>this.validator,getBDDWriter:()=>this.bddWriter,getTestabilityScorer:()=>this.testabilityScorer,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[],registerWorkflowActions:this.registerWorkflowActions.bind(this)}}registerWorkflowActions(e){if(this.ensureInitialized(),!this.qcsdIdeationPlugin)throw new Error("QCSD Ideation Plugin not initialized");this.qcsdIdeationPlugin.registerWorkflowActions(e)}getTaskHandlers(){return new Map([["validate",async e=>{if(!this.validator)return p(new Error("Validator not initialized"));let r=e.requirement;return r?this.validator.validate(r):p(new Error("Invalid validate payload: missing requirement"))}],["generate-scenarios",async e=>{if(!this.bddWriter)return p(new Error("BDD writer not initialized"));let r=e.requirement,i=e.requirementId;if(r)return this.bddWriter.generateScenarios(r);if(i){let n={id:i,title:`Requirement ${i}`,description:"",acceptanceCriteria:[],type:"functional",priority:"medium",status:"draft"};return this.bddWriter.generateScenarios(n)}return p(new Error("Invalid generate-scenarios payload: missing requirementId"))}],["score-testability",async e=>{if(!this.testabilityScorer)return p(new Error("Testability scorer not initialized"));let r=e.requirement;return r?this.testabilityScorer.scoreRequirement(r):p(new Error("Invalid score-testability payload: missing requirement"))}],["detect-ambiguity",async e=>{if(!this.validator)return p(new Error("Validator not initialized"));let r=e.requirement;return r?this.validator.detectAmbiguity(r):p(new Error("Invalid detect-ambiguity payload: missing requirement"))}],["analyze-dependencies",async e=>{if(!this.validator)return p(new Error("Validator not initialized"));let r=e.requirements;return!r||r.length===0?p(new Error("Invalid analyze-dependencies payload: missing requirements")):this.validator.analyzeDependencies(r)}]])}async onInitialize(){this.validator=new gr(this.memory,this.pluginConfig.validator),this.bddWriter=new hr(this.memory,this.pluginConfig.bddWriter),this.testabilityScorer=new fr(this.memory,this.pluginConfig.testabilityScorer),this.coordinator=new Fs(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.qcsdIdeationPlugin=vd(this.memory),await this.qcsdIdeationPlugin.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.qcsdIdeationPlugin&&await this.qcsdIdeationPlugin.dispose(),this.coordinator=null,this.validator=null,this.bddWriter=null,this.testabilityScorer=null,this.qcsdIdeationPlugin=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.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"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;default:break}}async validate(e){this.ensureInitialized();try{return await this.validator.validate(e)}catch(r){return this.handleError(r)}}async validateAgainstCriteria(e,r){this.ensureInitialized();try{return await this.validator.validateAgainstCriteria(e,r)}catch(i){return this.handleError(i)}}async detectAmbiguity(e){this.ensureInitialized();try{return await this.validator.detectAmbiguity(e)}catch(r){return this.handleError(r)}}async analyzeDependencies(e){this.ensureInitialized();try{return await this.validator.analyzeDependencies(e)}catch(r){return this.handleError(r)}}async scoreRequirement(e){this.ensureInitialized();try{return await this.testabilityScorer.scoreRequirement(e)}catch(r){return this.handleError(r)}}async scoreRequirements(e){this.ensureInitialized();try{return await this.testabilityScorer.scoreRequirements(e)}catch(r){return this.handleError(r)}}async suggestImprovements(e,r){this.ensureInitialized();try{return await this.testabilityScorer.suggestImprovements(e,r)}catch(i){return this.handleError(i)}}meetsThreshold(e,r){return this.ensureInitialized(),this.testabilityScorer.meetsThreshold(e,r)}async generateScenarios(e){this.ensureInitialized();try{return await this.bddWriter.generateScenarios(e)}catch(r){return this.handleError(r)}}async generateScenariosWithExamples(e,r){this.ensureInitialized();try{return await this.bddWriter.generateScenariosWithExamples(e,r)}catch(i){return this.handleError(i)}}toGherkin(e){return this.ensureInitialized(),this.bddWriter.toGherkin(e)}parseGherkin(e){return this.ensureInitialized(),this.bddWriter.parseGherkin(e)}async analyzeRequirement(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeRequirement(e);return r.success?this.trackSuccessfulOperation("analyze"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async generateTestArtifacts(e){this.ensureInitialized();try{let r=await this.coordinator.generateTestArtifacts(e);return r.success?this.trackSuccessfulOperation("generate-artifacts"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async validateSprintRequirements(e){this.ensureInitialized();try{let r=await this.coordinator.validateSprintRequirements(e);return r.success?this.trackSuccessfulOperation("validate-sprint"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async handleTestGenerated(e){let r=e.payload;await this.memory.set(`requirements-validation:test-link:${r.testId}`,{testId:r.testId,sourceFile:r.sourceFile,linkedAt:new Date().toISOString()},{namespace:"requirements-validation",ttl:86400*30})}async handleImpactAnalysis(e){let r=e.payload;await this.memory.set(`requirements-validation:impact:${r.analysisId}`,r,{namespace:"requirements-validation",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("RequirementsValidationPlugin is not initialized");if(!this.coordinator||!this.validator||!this.bddWriter||!this.testabilityScorer)throw new Error("RequirementsValidationPlugin 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 bd(u,t,e,r){return new hc(u,t,e,r)}M();A();M();import*as Xe from"path";import*as Ne from"fs/promises";A();function wd(u){return Date.now()-u.cachedAt.getTime()<u.ttlMs}function Cd(u){let t=u.toLowerCase();return t.includes("controller")?"controller":t.includes("service")?"service":t.includes("repository")?"repository":t.includes("facade")?"facade":t.includes("factory")?"factory":t.includes("adapter")?"adapter":t.includes("gateway")?"gateway":t.includes("handler")?"handler":t.includes("validator")?"validator":t.includes("transformer")?"transformer":t.includes("util")||t.includes("helper")?"utility":t.includes("domain")?"feature":t.includes("infra")?"layer":t.includes("package")||t.includes("pkg")?"package":"module"}function Ls(u){return u.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase()}H();var Wh={cacheTtlMs:36e5,publishEvents:!0,excludePatterns:["**/node_modules/**","**/.git/**","**/dist/**","**/build/**","**/coverage/**"],maxFiles:1e3},jh={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"}},$t=R.create("code-intelligence/product-factors-bridge"),$s=class{constructor(t,e,r={}){this.eventBus=t;this.memory=e;this.config={...Wh,...r}}eventBus;memory;config;initialized=!1;eventSubscriptions=[];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(tt.KnowledgeGraphUpdated,this.handleKnowledgeGraphUpdated.bind(this));this.eventSubscriptions.push(t);let e=this.eventBus.subscribe(tt.ImpactAnalysisCompleted,this.handleImpactAnalysisCompleted.bind(this));this.eventSubscriptions.push(e)}async handleKnowledgeGraphUpdated(t){$t.info("[ProductFactorsBridge] Knowledge graph updated, considering cache invalidation")}async handleImpactAnalysisCompleted(t){let e=t.payload;e.changedFiles&&e.changedFiles.length>0&&$t.info(`[ProductFactorsBridge] Impact analysis detected ${e.changedFiles.length} changed files`)}async requestC4Diagrams(t){let e=Date.now(),r=v();try{let i=await this.getCachedDiagrams(t.projectPath);if(i)return $t.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 p(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 l=await this.analyzeComponents(t.projectPath);n=l.components,s=l.relationships}let a;t.analyzeCoupling&&n.length>1&&(a=this.analyzeCoupling(n,s));let o={};t.includeContext!==!1&&(o.context=this.generateContextDiagram(r,i)),t.includeContainer!==!1&&(o.container=this.generateContainerDiagram(r,i)),t.includeComponent!==!1&&n.length>0&&(o.component=this.generateComponentDiagram(r.name,n,s)),t.includeDependency&&n.length>0&&(o.dependency=this.generateDependencyGraph(n,s));let c={projectName:r.name,projectDescription:r.description,generatedAt:new Date,source:"codebase-analysis",analysisMetadata:{filesAnalyzed:n.reduce((l,d)=>l+d.files.length,0),componentsDetected:n.length,externalSystemsDetected:i.length,analysisTimeMs:Date.now()-e}};return f({diagrams:o,metadata:c,externalSystems:i,components:n,relationships:s,couplingAnalysis:a})}catch(r){let i=y(r);return p(i)}}generateContextDiagram(t,e){let r=`C4Context
2849
2850
  title System Context diagram for ${t.name}
2850
2851
 
2851
2852
  Person(user, "User", "A user of the system")
@@ -2876,8 +2877,8 @@ Please analyze these requirements for:
2876
2877
  `;return i}generateDependencyGraph(t,e){let r=`graph TD
2877
2878
  `;for(let i of t)r+=` ${i.id}["${i.name}"]
2878
2879
  `;for(let i of e){let n=i.type==="depends_on"?"-->|depends|":"-->";r+=` ${i.sourceId} ${n} ${i.targetId}
2879
- `}return r}async getProjectMetadata(t){try{let e=Xe.join(t,"package.json"),r=await Ne.readFile(e,"utf-8"),i=E(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=Xe.join(t,"package.json");try{await Ne.access(r)}catch{return e}let i=await Ne.readFile(r,"utf-8"),n=E(i),s={...n.dependencies,...n.devDependencies};for(let[a]of Object.entries(s)){let o=jh[a];o&&e.push({id:Ls(a),name:o.technology,type:o.type,technology:o.technology,detectedFrom:"package.json",relationship:this.inferRelationship(o.type)})}}catch(r){$t.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=Xe.join(t,"src"),n=t;try{await Ne.access(i),n=i}catch{}let s=await Ne.readdir(n,{withFileTypes:!0});for(let a of s)if(a.isDirectory()&&!this.shouldExclude(a.name)){let o=Xe.join(n,a.name),c=await this.getFilesInDirectory(o,t);c.length>0&&e.push({id:Ls(a.name),name:this.formatComponentName(a.name),type:Cd(a.name),boundary:this.inferBoundary(a.name),technology:"TypeScript",files:c,responsibilities:[this.inferResponsibility(a.name)]})}for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){let c=e[a],l=e[o];this.likelyHasRelationship(c.id,l.id)&&r.push({sourceId:c.id,targetId:l.id,type:"uses",weight:1})}}catch(i){$t.error("Component analysis failed:",i instanceof Error?i:void 0)}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 Ne.readdir(s,{withFileTypes:!0});for(let c of o){if(this.shouldExclude(c.name))continue;let l=Xe.join(s,c.name),d=Xe.relative(e,l);c.isDirectory()?await n(l,a+1):c.isFile()&&this.isSourceFile(c.name)&&i.push(d)}}catch{$t.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],c=e.filter(l=>l.sourceId===a.id&&l.targetId===o.id||l.sourceId===o.id&&l.targetId===a.id);if(c.length>0){let l=c.reduce((h,b)=>h+(b.weight||1),0),d=Math.min(1,l/10),m=[a.id,o.id].sort().join("::"),g=i.has(m);r.push({moduleA:a.name,moduleB:o.name,couplingStrength:d,isCircular:g,recommendation:this.getCouplingRecommendation(d,g)})}}}catch(i){$t.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&&wd(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})}getCacheKey(t){return`c4-diagrams:${Ls(t)}`}async computeProjectHash(t){try{let e=Xe.join(t,"package.json"),r=await Ne.readFile(e,"utf-8");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 p(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 p(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=D(tt.C4DiagramsGenerated,"code-intelligence",n);await this.eventBus.publish(s)}};A();var Uh={embeddingDimension:Ct.DIMENSIONS,minScore:.5,maxResults:100,namespace:"code-intelligence:semantic",enableCaching:!0,cacheSize:1e3,useNomicEmbeddings:!0},Ot=class{constructor(t,e={}){this.memory=t;this.config={...Uh,...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 St({enableFallback:!0,...this.config.nomicConfig});await t.healthCheck()&&(this.embedder=t,this.config.embeddingDimension=Ct.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 p(new Error(`Unknown search type: ${i}`))}let c=Date.now()-e;return f({results:o,total:o.length,searchTime:c})}catch(r){return p(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},{namespace:this.config.namespace}),f(void 0)}catch(r){return p(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)}`,c=await this.memory.get(o);c&&n.push({file:c.file,snippet:this.extractSnippet(c.content,200),score:s.score,highlights:this.findHighlights(c.content,t),metadata:c.metadata})}return f(n)}catch(r){return p(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 p(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 St}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 c=o.metadata;if(!c?.file||r&&r.length>0&&!r.some(g=>c.file.includes(g)))continue;let l=`${this.config.namespace}:content:${this.fileToKey(c.file)}`,d=await this.memory.get(l);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 c=await this.memory.get(o);if(!c||r&&r.length>0&&!r.some(m=>c.file.includes(m))||i&&!this.matchesFilters(c.metadata,i))continue;let l=c.content.indexOf(t);if(l>=0){let d=this.getLineNumber(c.content,l);if(n.push({file:c.file,line:d,snippet:this.extractSnippetAround(c.content,l,100),score:1,highlights:[t],metadata:c.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 c of a){let l=await this.memory.get(c);if(!l||r&&r.length>0&&!r.some(h=>l.file.includes(h))||i&&!this.matchesFilters(l.metadata,i))continue;let d=this.tokenize(l.content.toLowerCase()),m=this.calculateFuzzyScore(o,d);if(m>=this.config.minScore){let g=o.filter(h=>d.some(b=>b.includes(h)||h.includes(b)));n.push({file:l.file,snippet:this.extractSnippet(l.content,200),score:m,highlights:g,metadata:l.metadata})}}return n.sort((c,l)=>l.score-c.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 k of e){let O=t.match(k);r+=O?O.length:0}let i=0,n=t.split(`
2880
- `),s=0;for(let k of n)/{/.test(k)&&s++,/}/.test(k)&&(s=Math.max(0,s-1)),/\bif\b|\bfor\b|\bwhile\b/.test(k)&&(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)||[],c=new Set(a).size,l=new Set(o).size,d=a.length,m=o.length,g=c+l,h=d+m,b=l>0?c/2*(m/l):0,w=h>0?h*Math.log2(g||1):0,C=b*w,S=C/18,P=w/3e3;return{cyclomatic:r,cognitive:i,halstead:{vocabulary:g,length:h,difficulty:Math.round(b*100)/100,effort:Math.round(C),time:Math.round(S),bugs:Math.round(P*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(`
2880
+ `}return r}async getProjectMetadata(t){try{let e=Xe.join(t,"package.json"),r=await Ne.readFile(e,"utf-8"),i=E(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=Xe.join(t,"package.json");try{await Ne.access(r)}catch{return e}let i=await Ne.readFile(r,"utf-8"),n=E(i),s={...n.dependencies,...n.devDependencies};for(let[a]of Object.entries(s)){let o=jh[a];o&&e.push({id:Ls(a),name:o.technology,type:o.type,technology:o.technology,detectedFrom:"package.json",relationship:this.inferRelationship(o.type)})}}catch(r){$t.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=Xe.join(t,"src"),n=t;try{await Ne.access(i),n=i}catch{}let s=await Ne.readdir(n,{withFileTypes:!0});for(let a of s)if(a.isDirectory()&&!this.shouldExclude(a.name)){let o=Xe.join(n,a.name),c=await this.getFilesInDirectory(o,t);c.length>0&&e.push({id:Ls(a.name),name:this.formatComponentName(a.name),type:Cd(a.name),boundary:this.inferBoundary(a.name),technology:"TypeScript",files:c,responsibilities:[this.inferResponsibility(a.name)]})}for(let a=0;a<e.length;a++)for(let o=a+1;o<e.length;o++){let c=e[a],l=e[o];this.likelyHasRelationship(c.id,l.id)&&r.push({sourceId:c.id,targetId:l.id,type:"uses",weight:1})}}catch(i){$t.error("Component analysis failed:",i instanceof Error?i:void 0)}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 Ne.readdir(s,{withFileTypes:!0});for(let c of o){if(this.shouldExclude(c.name))continue;let l=Xe.join(s,c.name),d=Xe.relative(e,l);c.isDirectory()?await n(l,a+1):c.isFile()&&this.isSourceFile(c.name)&&i.push(d)}}catch{$t.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],c=e.filter(l=>l.sourceId===a.id&&l.targetId===o.id||l.sourceId===o.id&&l.targetId===a.id);if(c.length>0){let l=c.reduce((h,b)=>h+(b.weight||1),0),d=Math.min(1,l/10),m=[a.id,o.id].sort().join("::"),g=i.has(m);r.push({moduleA:a.name,moduleB:o.name,couplingStrength:d,isCircular:g,recommendation:this.getCouplingRecommendation(d,g)})}}}catch(i){$t.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&&wd(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})}getCacheKey(t){return`c4-diagrams:${Ls(t)}`}async computeProjectHash(t){try{let e=Xe.join(t,"package.json"),r=await Ne.readFile(e,"utf-8");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 p(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 p(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=D(tt.C4DiagramsGenerated,"code-intelligence",n);await this.eventBus.publish(s)}};A();var Uh={embeddingDimension:Ct.DIMENSIONS,minScore:.5,maxResults:100,namespace:"code-intelligence:semantic",enableCaching:!0,cacheSize:1e3,useNomicEmbeddings:!0},Ot=class{constructor(t,e={}){this.memory=t;this.config={...Uh,...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 St({enableFallback:!0,...this.config.nomicConfig});await t.healthCheck()&&(this.embedder=t,this.config.embeddingDimension=Ct.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 p(new Error(`Unknown search type: ${i}`))}let c=Date.now()-e;return f({results:o,total:o.length,searchTime:c})}catch(r){return p(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},{namespace:this.config.namespace}),f(void 0)}catch(r){return p(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)}`,c=await this.memory.get(o);c&&n.push({file:c.file,snippet:this.extractSnippet(c.content,200),score:s.score,highlights:this.findHighlights(c.content,t),metadata:c.metadata})}return f(n)}catch(r){return p(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 p(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 St}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 c=o.metadata;if(!c?.file||r&&r.length>0&&!r.some(g=>c.file.includes(g)))continue;let l=`${this.config.namespace}:content:${this.fileToKey(c.file)}`,d=await this.memory.get(l);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 c=await this.memory.get(o);if(!c||r&&r.length>0&&!r.some(m=>c.file.includes(m))||i&&!this.matchesFilters(c.metadata,i))continue;let l=c.content.indexOf(t);if(l>=0){let d=this.getLineNumber(c.content,l);if(n.push({file:c.file,line:d,snippet:this.extractSnippetAround(c.content,l,100),score:1,highlights:[t],metadata:c.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 c of a){let l=await this.memory.get(c);if(!l||r&&r.length>0&&!r.some(h=>l.file.includes(h))||i&&!this.matchesFilters(l.metadata,i))continue;let d=this.tokenize(l.content.toLowerCase()),m=this.calculateFuzzyScore(o,d);if(m>=this.config.minScore){let g=o.filter(h=>d.some(b=>b.includes(h)||h.includes(b)));n.push({file:l.file,snippet:this.extractSnippet(l.content,200),score:m,highlights:g,metadata:l.metadata})}}return n.sort((c,l)=>l.score-c.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 P of e){let O=t.match(P);r+=O?O.length:0}let i=0,n=t.split(`
2881
+ `),s=0;for(let P of n)/{/.test(P)&&s++,/}/.test(P)&&(s=Math.max(0,s-1)),/\bif\b|\bfor\b|\bwhile\b/.test(P)&&(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)||[],c=new Set(a).size,l=new Set(o).size,d=a.length,m=o.length,g=c+l,h=d+m,b=l>0?c/2*(m/l):0,w=h>0?h*Math.log2(g||1):0,C=b*w,S=C/18,k=w/3e3;return{cyclomatic:r,cognitive:i,halstead:{vocabulary:g,length:h,difficulty:Math.round(b*100)/100,effort:Math.round(C),time:Math.round(S),bugs:Math.round(k*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(`
2881
2882
  `).length>200&&i.push("Consider splitting this file into smaller modules"),t.split(`
2882
2883
  `).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 c=0;c<o.length&&c<e.length;c++)e[(a+c)%e.length]+=o.charCodeAt(c)/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(`
2883
2884
  `).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(`
@@ -2888,7 +2889,7 @@ Please analyze these requirements for:
2888
2889
  `).map(i=>i.trim()).filter(i=>i.length>0&&ge(i));if(r.length>0){let i=0;for(let n of r)i+=Td(n);return Ns(i,"jest",u)}return Mi(u,t)}catch{return Mi(u,t)}}function hf(u,t){try{let r=Fi("cargo test --list",{cwd:u,encoding:"utf-8",timeout:t.timeout}).split(`
2889
2890
  `).filter(o=>o.endsWith(": test")),i=r.length,n=r.filter(o=>!o.includes("integration")&&!o.includes("e2e")).length,s=r.filter(o=>o.includes("integration")).length,a=r.filter(o=>o.includes("e2e")).length;return{total:i,unit:n,integration:s,e2e:a,source:"cargo"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"cargo"}}}function ff(u,t){try{let r=Fi("pytest --collect-only -q",{cwd:u,encoding:"utf-8",timeout:t.timeout}).split(`
2890
2891
  `).filter(o=>o.includes("::test_")||o.includes("::Test")),i=r.length,n=r.filter(o=>o.includes("unit")||!o.includes("integration")&&!o.includes("e2e")).length,s=r.filter(o=>o.includes("integration")||o.includes("_integration")).length,a=r.filter(o=>o.includes("e2e")||o.includes("end_to_end")).length;return{total:i,unit:n-s-a,integration:s,e2e:a,source:"pytest"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"pytest"}}}function yf(u,t){try{let r=Fi('go test -list ".*" ./...',{cwd:u,encoding:"utf-8",timeout:t.timeout}).split(`
2891
- `).filter(o=>o.startsWith("Test")||o.startsWith("Example")||o.startsWith("Benchmark")),i=r.filter(o=>o.startsWith("Test")).length,n=r.filter(o=>o.startsWith("Test")&&!o.includes("Integration")&&!o.includes("E2E")).length,s=r.filter(o=>o.includes("Integration")).length,a=r.filter(o=>o.includes("E2E")).length;return{total:i,unit:n,integration:s,e2e:a,source:"go"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"go"}}}function Mi(u,t){let e=0,r=0,i=0,n=0;function s(a){if(!ge(a))return;let o=df(a,{withFileTypes:!0});for(let c of o){let l=ve(a,c.name);if(c.isDirectory()){if(t.excludeDirs.includes(c.name))continue;s(l)}else if(c.isFile()&&vf(c.name)){let d=mf(c.name).toLowerCase(),m=0;[".ts",".tsx",".js",".jsx",".mjs"].includes(d)?m=Td(l):d===".py"?m=bf(l):d===".rs"?m=wf(l):d===".go"&&(m=Cf(l)),e+=m;let g=l.toLowerCase();g.includes("e2e")||g.includes("end-to-end")?n+=m:g.includes("integration")?i+=m:r+=m}}}return s(u),{total:e,unit:r,integration:i,e2e:n,source:"fallback"}}function vf(u){let t=u.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 Td(u){try{let t=Li(u,"utf-8"),e=t.match(/\bit\s*\(/g)||[],r=t.match(/\btest\s*\(/g)||[];return e.length+r.length}catch{return 0}}function bf(u){try{let t=Li(u,"utf-8"),e=t.match(/\bdef\s+test_\w+\s*\(/g)||[],r=t.match(/\basync\s+def\s+test_\w+\s*\(/g)||[];return e.length+r.length}catch{return 0}}function wf(u){try{let t=Li(u,"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 Cf(u){try{return(Li(u,"utf-8").match(/\bfunc\s+Test\w+\s*\(/g)||[]).length}catch{return 0}}function Ns(u,t,e){let r=u,i=0,n=0;return(ge(ve(e,"tests","integration"))||ge(ve(e,"test","integration"))||ge(ve(e,"__tests__","integration")))&&(i=Math.floor(u*.2),r-=i),(ge(ve(e,"tests","e2e"))||ge(ve(e,"test","e2e"))||ge(ve(e,"e2e"))||ge(ve(e,"cypress")))&&(n=Math.floor(u*.1),r-=n),{total:u,unit:Math.max(0,r),integration:i,e2e:n,source:t}}var Cc=class{config;cache=new Map;cacheHits=0;cacheMisses=0;constructor(t={}){this.config={...Nt,...t}}async collectAll(t){let e=`all:${t}`;if(this.config.enableCache){let l=this.getFromCache(e);if(l)return l}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",c={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,c),c}async countLOC(t){let e=`loc:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await fc(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 bc(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}checkTools(){let t=yc(),e=wc(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 Vt(_t(t,"Cargo.toml"))?"rust":Vt(_t(t,"go.mod"))?"go":Vt(_t(t,"pyproject.toml"))||Vt(_t(t,"requirements.txt"))?"python":Vt(_t(t,"package.json"))?Vt(_t(t,"tsconfig.json"))?"typescript":"javascript":"unknown"}countPatternsInternal(t,e){let r={},i=0,n=0,s=0,a=0,o=this.getPatternsForLanguage(e);function c(l){if(!Vt(l))return;let d=Rf(l,{withFileTypes:!0});for(let m of d){let g=_t(l,m.name);if(m.isDirectory()){if(["node_modules","dist","coverage","build",".git","vendor","target"].includes(m.name))continue;c(g)}else if(m.isFile()){let h=Tf(m.name).toLowerCase();if(Af(h,e)){let b=Ef(g,o);(b.unwraps>0||b.unsafeBlocks>0||b.todoComments>0||b.consoleStatements>0)&&(r[g]=b,i+=b.unwraps,n+=b.unsafeBlocks,s+=b.todoComments,a+=b.consoleStatements)}}}}return c(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 Af(u,t){switch(t){case"rust":return u===".rs";case"python":return[".py",".pyw"].includes(u);case"go":return u===".go";case"typescript":return[".ts",".tsx"].includes(u);case"javascript":return[".js",".jsx",".mjs",".cjs"].includes(u);default:return[".ts",".tsx",".js",".jsx",".py",".rs",".go"].includes(u)}}function Ef(u,t){try{let e=Sf(u,"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 Ad(u={}){return new Cc(u)}M();A();se();Yt();A();Yt();A();Yt();A();Yt();A();se();Yt();A();var NO=300*1e3;qe();qe();M();qe();var YO=R.create("temporal-compression");A();M();var t1=R.create("ruvector-server-client");qm();import{Buffer as _f}from"buffer";var c1=_f.from("COGCNTNR","ascii");qe();qe();var Bf={capacity:1e4,minCoherenceThreshold:.3,highTierThreshold:.8,mediumTierThreshold:.5,highTierWeight:3,mediumTierWeight:1.5,lowTierWeight:1},Sc=class{config;cusumDetector;buffer;totalSeen=0;totalAdmitted=0;totalRejected=0;totalEvicted=0;totalSampled=0;constructor(t){this.config={...Bf,...t},this.cusumDetector=new _a({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),c=Math.floor(a/o);if(c<this.config.capacity){let l=this.selectEvictionTarget(c);return this.buffer[l]=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 l=0;l<r.length;l++)s.has(l)||(a+=i[l]);if(a<=0)break;let o=Math.random()*a,c=-1;for(let l=0;l<r.length;l++)if(!s.has(l)&&(o-=i[l],o<=0)){c=l;break}if(c===-1){for(let l=0;l<r.length;l++)if(!s.has(l)){c=l;break}}c>=0&&(s.add(c),r[c].replayCount++,n.push(r[c]))}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}};se();var yr=R.create("code-intelligence/gnn");async function Ed(u,t,e){try{for(let r of e)try{let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Rc(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}};u.addEmbedding(s)}}catch(i){yr.error(`Failed to index ${r}:`,i instanceof Error?i:void 0)}yr.info(`Indexed ${e.length} code embeddings`)}catch(r){yr.error("Failed to index code embeddings:",r instanceof Error?r:void 0)}}async function Rc(u,t){let e=[],r=u.split(".").pop(),i=_s(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)||[],c=t.match(/if\s*\(/g)||[];e.push(Math.min(1,(o.length+c.length)/30));let l=t.match(/\/\/.*|\/\*[\s\S]*?\*\//g)||[];e.push(Math.min(1,l.length/50));let d=_s(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 xd(u,t){try{let r={vector:await Rc("query",t),dimension:384,namespace:"code",text:t,timestamp:Date.now(),quantization:"none"};return u.search(r,{limit:10,namespace:"code"}).map(n=>({file:n.metadata?.path??`file-${n.id}`,similarity:1-n.distance}))}catch(e){return yr.error("Failed to search with GNN:",e instanceof Error?e:void 0),[]}}async function Pd(u,t,e){try{for(let r of e.changedFiles){let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Rc(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}},a=u.search(s,{limit:5,namespace:"code"});yr.info(`Found ${a.length} semantically similar files to ${r}`)}}}catch(r){yr.error("Failed to enhance impact analysis:",r instanceof Error?r:void 0)}}function kd(u,t){let e=new Map,r=new Map;for(let i of u)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 _s(u){let t=0;for(let e=0;e<u.length;e++)t=(t<<5)-t+u.charCodeAt(e),t=t|0;return Math.abs(t)}M();A();var Ve=R.create("code-intelligence/hypergraph");async function Id(u,t,e){try{let r=await u.findUntestedFunctions();if(Ve.info(`[CodeIntelligence] Found ${r.length} untested functions via hypergraph`),e){let i=D("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 Ve.error("Failed to find untested functions:"),p(i)}}async function Dd(u,t,e,r){if(t.length===0)return{success:!0,value:[]};try{let i=await u.findImpactedTests(t);if(Ve.info(`[CodeIntelligence] Found ${i.length} impacted tests for ${t.length} changed files via hypergraph`),r){let n=D("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 Ve.error("Failed to find impacted tests:"),p(n)}}async function Md(u,t,e,r){try{let i=await u.findCoverageGaps(t);if(Ve.info(`[CodeIntelligence] Found ${i.length} coverage gaps (functions with <=${t}% coverage) via hypergraph`),r){let n=D("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 Ve.error("Failed to find coverage gaps:"),p(n)}}async function Fd(u,t,e,r,i){try{Ve.info(`[CodeIntelligence] Building hypergraph from ${t.files.length} indexed files`);let n=await u.buildFromIndexResult(t);if(Ve.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=D("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 Ve.error("Failed to build hypergraph:"),p(s)}}async function Ld(u,t,e){try{let r=await u.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 Ve.error("Failed to enhance impact with hypergraph:",r instanceof Error?r:void 0),e}}M();var vr=R.create("code-intelligence/consensus");async function $d(u,t,e,r){let i=V({id:v(),type:"code-pattern-detection",confidence:t,description:`Verify code pattern: ${u.name} (${u.type}) at ${u.location}`,payload:u,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"?(vr.info(`Code pattern '${u.name}' verified by consensus`),!0):(vr.warn(`Code pattern '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Od(u,t,e,r){let i=V({id:v(),type:"impact-analysis",confidence:t,description:`Verify impact analysis: ${u.changedFiles.length} files, risk=${u.riskLevel}, ${u.impactedTests.length} tests`,payload:u,detectedBy:"code-intelligence-coordinator",severity:u.riskLevel==="critical"||u.riskLevel==="high"?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(vr.info(`Impact analysis verified by consensus (risk=${u.riskLevel})`),!0):(vr.warn(`Impact analysis NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Nd(u,t,e,r){let i=V({id:v(),type:"dependency-mapping",confidence:t,description:`Verify dependency: ${u.source} -> ${u.targets.length} targets (${u.type})`,payload:u,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"?(vr.info("Dependency mapping verified by consensus"),!0):(vr.warn(`Dependency mapping NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var ny={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},ie=R.create("code-intelligence"),Oi=class extends Q{constructor(e,r,i,n={}){let s={...ny,...n};super(e,"code-intelligence",s,{verifyFindingTypes:["code-pattern-detection","impact-analysis","dependency-mapping"]});this.memory=r;this.agentCoordinator=i;this.knowledgeGraph=new Rt(r),this.semanticAnalyzer=new Ot(r),this.impactAnalyzer=new Br(r,this.knowledgeGraph),this.fileReader=new De,this.productFactorsBridge=new $s(e,r,{publishEvents:this.config.publishEvents})}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=Ad({enableCache:!0,cacheTTL:3e5}),ie.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-NNF5DE5T.js"),r=await import("fs"),i=await import("path"),{findProjectRoot:n}=await import("./unified-memory-O7GFUSD3.js"),s=n(),a=this.config.hypergraphDbPath||i.join(s,".agentic-qe","memory.db"),o=i.dirname(a);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),this.hypergraphDb=e(a),this.hypergraph=await nn({db:this.hypergraphDb,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:this.config.enableGNN}),ie.info(`Hypergraph Engine initialized at ${a}`)}catch(e){let r=e instanceof Error?e.message:String(e);if(ie.warn(`Hypergraph Engine initialization failed (feature degraded): ${r}`),this.hypergraph=void 0,this.hypergraphDb=void 0,this.config.publishEvents){let i=D("code-intelligence.HypergraphDegraded","code-intelligence",{reason:r});this.eventBus.publish(i).catch(()=>{})}}}async initializeRLIntegrations(){try{if(this.config.enableGNN&&(Va(),this.gnnIndex=rn.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 me({domain:"code-intelligence",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.6}),ie.info("PersistentSONAEngine initialized for code pattern learning")}catch(e){ie.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(e){throw ie.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){if(await this.saveWorkflowState(),this.gnnIndex&&rn.closeInstance("code-intelligence"),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(e){ie.error("Error closing SONA engine:",e instanceof Error?e:void 0)}if(this.hypergraphDb){try{this.hypergraphDb.close()}catch(e){ie.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=v();try{if(this.startWorkflow(r,"index"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Indexing paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn indexing agents"));let i=await this.spawnIndexerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,10);let n=await this.knowledgeGraph.index(e);if(n.success){if(this.updateWorkflowProgress(r,40),this.config.enableGNN&&this.gnnIndex&&e.paths.length>0&&await this.indexCodeEmbeddings(e.paths),this.updateWorkflowProgress(r,60),this.config.enableMetricCollector&&this.metricCollector&&e.paths.length>0){let s=this.getProjectRootFromPaths(e.paths);s&&await this.collectProjectMetrics(s)}if(this.updateWorkflowProgress(r,70),e.paths.length>0&&await this.indexForSemanticSearch(e.paths),this.updateWorkflowProgress(r,85),this.config.enableHypergraph&&this.hypergraph&&e.paths.length>0)try{let s=await this.buildCodeIndexResultFromPaths(e.paths);s.files.length>0&&(await this.hypergraph.buildFromIndexResult(s),ie.info(`Hypergraph rebuilt from ${s.files.length} indexed files`))}catch(s){ie.warn(`Hypergraph rebuild skipped: ${s instanceof Error?s.message:s}`)}this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.publishEvents&&await this.publishKnowledgeGraphUpdated(n.value)}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),p(n)}}async search(e){let r=v();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&&ie.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),p(n)}}async analyzeImpact(e){let r=v();try{if(this.startWorkflow(r,"impact"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative impact analysis"),this.minCutMixin.shouldPauseOperations())return p(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),p(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),p(n)}}async mapDependencies(e){let r=v();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),p(n)}}async queryKG(e){let r=v();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),p(n)}}async indexCodeEmbeddings(e){!this.gnnIndex||!this.rlInitialized||await Ed(this.gnnIndex,this.fileReader,e)}async searchCodeWithGNN(e){return!this.gnnIndex||!this.rlInitialized?[]:xd(this.gnnIndex,e.query)}async enhanceImpactAnalysisWithGNN(e){!this.gnnIndex||!this.rlInitialized||await Pd(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 ie.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});ie.info(`Stored impact pattern ${a.id}`)}catch(i){ie.error("Failed to store impact pattern:",i instanceof Error?i:void 0)}}mergeSearchResults(e,r){return kd(e,r)}hashCode(e){return _s(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=D(tt.KnowledgeGraphUpdated,"code-intelligence",r);await this.eventBus.publish(i)}async publishImpactAnalysisCompleted(e,r){let i={analysisId:v(),changedFiles:e.changedFiles,impactedFiles:[...r.directImpact.map(s=>s.file),...r.transitiveImpact.map(s=>s.file)],impactedTests:r.impactedTests,riskLevel:r.riskLevel},n=D(tt.ImpactAnalysisCompleted,"code-intelligence",i);await this.eventBus.publish(n)}async publishSemanticSearchCompleted(e,r){let i=D(tt.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=v();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),ie.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),p(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:36e5}),await this.memory.set(`c4-components:${this.hashCode(e)}`,r.components,{namespace:"code-intelligence",ttl:36e5}),await this.memory.set(`c4-external-systems:${this.hashCode(e)}`,r.externalSystems,{namespace:"code-intelligence",ttl:36e5})}async collectProjectMetrics(e){if(!this.config.enableMetricCollector||!this.metricCollector)return p(new Error("MetricCollector is not enabled"));try{ie.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(ie.info(`[CodeIntelligence] Real metrics collected: ${r.loc.total} LOC, ${r.tests.total} tests, tools: ${i}`),r.loc.source==="node-native"&&ie.info("[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)"),await this.storeProjectMetricsInMemory(e,r),this.config.publishEvents){let n=D("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 ie.error("Failed to collect metrics:"),p(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:3e5}),await this.memory.set(`loc-metrics:${this.hashCode(e)}`,r.loc,{namespace:"code-intelligence",ttl:3e5}),await this.memory.set(`test-metrics:${this.hashCode(e)}`,r.tests,{namespace:"code-intelligence",ttl:3e5})}getMetricCollector(){return this.metricCollector}getProjectRootFromPaths(e){if(e.length===0)return null;let r=e[0],i=r.split("/"),n="";for(let a of i){n=n?`${n}/${a}`:a;let o=["package.json","Cargo.toml","go.mod","pyproject.toml",".git"];for(let c of o)try{let l=`${n}/${c}`;if(Pa("fs").existsSync(l))return n}catch{}}let s=r.lastIndexOf("/");return s>0?r.substring(0,s):r}isHypergraphEnabled(){return this.config.enableHypergraph&&this.hypergraph!==void 0}async findUntestedFunctions(){return this.hypergraph?Id(this.hypergraph,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findImpactedTestsFromHypergraph(e){return this.hypergraph?Dd(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findCoverageGapsFromHypergraph(e=50){return this.hypergraph?Md(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async buildHypergraphFromIndex(e){return this.hypergraph?Fd(this.hypergraph,e,this.memory,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}getHypergraph(){return this.hypergraph}async enhanceImpactWithHypergraph(e,r){return this.hypergraph?Ld(this.hypergraph,e,r):r}async buildCodeIndexResultFromPaths(e){let{extractCodeIndex:r}=await import("./code-index-extractor-C6DHOOWA.js");return r(e)}async verifyCodePatternDetection(e,r){return $d(e,r,this.consensusMixin,this.domainName)}async verifyImpactAnalysis(e,r){return Od(e,r,this.consensusMixin,this.domainName)}async verifyDependencyMapping(e,r){return Nd(e,r,this.consensusMixin,this.domainName)}};A();var zs=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;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(){return new Map([["index",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.paths;if(!r||r.length===0)return p(new Error("Invalid index payload: missing paths"));let i=e.language?[e.language]:e.languages;return this.coordinator.index({paths:r,languages:i})}],["search",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.query;return r?this.coordinator.search({query:r,type:e.type??"semantic",limit:e.limit}):p(new Error("Invalid search payload: missing query"))}],["analyze-impact",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.changedFiles;return!r||r.length===0?p(new Error("Invalid analyze-impact payload: missing changedFiles")):this.coordinator.analyzeImpact({changedFiles:r})}],["query-dependencies",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.file,n=e.files??(r?[r]:void 0);return!n||n.length===0?p(new Error("Invalid query-dependencies payload: missing file or files")):this.coordinator.mapDependencies({files:n,direction:e.direction??"both",depth:e.depth})}]])}async onInitialize(){this.knowledgeGraph=new Rt(this.memory,this.pluginConfig.knowledgeGraph),this.semanticAnalyzer=new Ot(this.memory,this.pluginConfig.semanticAnalyzer),this.impactAnalyzer=new Br(this.memory,this.knowledgeGraph,this.pluginConfig.impactAnalyzer),this.coordinator=new Oi(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,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){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 Tc(u,t,e,r){return new zs(u,t,e,r)}M();A();var he=class u{constructor(t){this._value=t;if(!t||t.trim()==="")throw new Error("FilePath cannot be empty")}_value;get value(){return this._value}get extension(){let t=this._value.split(".");return t.length>1?t[t.length-1]:""}get directory(){let t=this._value.lastIndexOf("/");return t>0?this._value.substring(0,t):""}get filename(){let t=this._value.lastIndexOf("/");return t>=0?this._value.substring(t+1):this._value}equals(t){return this._value===t._value}static create(t){return new u(t)}};var br=class u{constructor(t){this._value=t;if(t<0||t>1)throw new Error("RiskScore must be between 0 and 1")}_value;get value(){return this._value}get percentage(){return this._value*100}get level(){return this._value>=.8?"critical":this._value>=.6?"high":this._value>=.3?"medium":"low"}isHigherThan(t){return this._value>t._value}equals(t){return this._value===t._value}static create(t){return new u(t)}static fromPercentage(t){return new u(t/100)}},_e=class u{constructor(t,e){this._start=t;this._end=e;if(t>e)throw new Error("Start date cannot be after end date")}_start;_end;get start(){return this._start}get end(){return this._end}get durationMs(){return this._end.getTime()-this._start.getTime()}get durationSeconds(){return this.durationMs/1e3}contains(t){return t>=this._start&&t<=this._end}overlaps(t){return this._start<=t._end&&t._start<=this._end}equals(t){return this._start.getTime()===t._start.getTime()&&this._end.getTime()===t._end.getTime()}static create(t,e){return new u(t,e)}static lastNDays(t){let e=new Date,r=new Date(e.getTime()-t*24*60*60*1e3);return new u(r,e)}},zt=class u{constructor(t,e,r,i){this._major=t;this._minor=e;this._patch=r;this._prerelease=i}_major;_minor;_patch;_prerelease;get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let t=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${t}-${this._prerelease}`:t}isNewerThan(t){return this._major!==t._major?this._major>t._major:this._minor!==t._minor?this._minor>t._minor:this._patch>t._patch}equals(t){return this._major===t._major&&this._minor===t._minor&&this._patch===t._patch&&this._prerelease===t._prerelease}static create(t,e,r,i){return new u(t,e,r,i)}static parse(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!e)throw new Error(`Invalid version format: ${t}`);return new u(parseInt(e[1]),parseInt(e[2]),parseInt(e[3]),e[4])}};var Bs={defaultRuleSets:["owasp-top-10","cwe-sans-25"],maxConcurrentScans:4,timeout:3e5,enableFalsePositiveDetection:!0,dastMaxDepth:5,dastActiveScanning:!1,enableLLMAnalysis:!0,llmModelTier:4,enableSemgrep:!0};M();var Ac=[{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"}],Ec=[{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"}],xc=[{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"}],Pc=[{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"}],kc=[{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"}],Ic=[{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())"}],Dc=[{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"}],Mc=[{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"] })'}],qs=[...Ac,...Ec,...xc,...Pc,...kc,...Ic,...Dc,...Mc],Ni=[{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"]}];A();H();A();H();import{execFile as sy}from"child_process";import{promisify as ay}from"util";import*as zd from"path";var Fc=ay(sy);async function Vi(){try{return await Fc("semgrep",["--version"],{timeout:5e3}),!0}catch{return!1}}async function Vd(){try{let{stdout:u}=await Fc("semgrep",["--version"],{timeout:5e3});return u.trim()}catch{return null}}async function oy(u){let t={target:u.target||".",config:u.config||"auto",exclude:u.exclude||["node_modules",".git","dist","build","coverage"],maxFileSize:u.maxFileSize||5e6,timeout:u.timeout||300,verbose:u.verbose||!1};if(!await Vi())return{success:!1,findings:[],errors:["Semgrep is not installed. Install with: pip install semgrep"]};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 Fc("semgrep",r,{timeout:i,maxBuffer:50*1024*1024,cwd:zd.isAbsolute(t.target)?void 0:process.cwd()}),a=_d(n);return s&&t.verbose&&a.errors.push(s),a.version=await Vd()||void 0,a}catch(r){let i=r;if(i.stdout)try{let n=_d(i.stdout);return n.version=await Vd()||void 0,n}catch{}return{success:!1,findings:[],errors:[i.message??String(r)]}}}function _d(u){try{let t=E(u),e=t.results||t.findings||[],r=t.errors?.map(i=>i.message||String(i))||[];return{success:!0,findings:e.map(i=>({check_id:i.check_id||i.rule_id||"unknown",path:i.path,start:{line:i.start?.line||1,col:i.start?.col||1},end:{line:i.end?.line||i.start?.line||1,col:i.end?.col||1},extra:{message:i.extra?.message||i.message||"Security issue detected",severity:i.extra?.severity||i.severity||"WARNING",lines:i.extra?.lines||"",metadata:{cwe:i.extra?.metadata?.cwe||i.metadata?.cwe,owasp:i.extra?.metadata?.owasp||i.metadata?.owasp,category:i.extra?.metadata?.category||i.metadata?.category,description:i.extra?.metadata?.description||i.metadata?.description,fix:i.extra?.metadata?.fix||i.extra?.fix,references:i.extra?.metadata?.references||i.metadata?.references,confidence:i.extra?.metadata?.confidence||i.metadata?.confidence}}})),errors:r}}catch(t){return{success:!1,findings:[],errors:[`Failed to parse semgrep output: ${T(t)}`]}}}async function Gs(u,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 oy({...e,target:u,config:i||"auto"})}function cy(u){return{ERROR:"high",WARNING:"medium",INFO:"low"}[u]||"medium"}function Hs(u){return u.map(t=>({id:t.check_id,title:t.check_id.split(".").pop()||t.check_id,description:t.extra.message,severity:cy(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 ly=R.create("security-compliance/sast-scanner"),wr=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=v();try{if(t.length===0)return p(new Error("No files provided for scanning"));this.activeScans.set(r,"running");let i=Date.now(),n=Ni.filter(h=>e.includes(h.id));if(n.length===0)return p(new Error(`No valid rule sets found: ${e.join(", ")}`));let[s,a]=await Promise.all([this.runPatternScanning(t,n),this.runSemgrepScanning(t,e)]),o=this.mergeVulnerabilities(s.vulnerabilities,a),c=s.linesScanned,l=Date.now()-i,d=this.calculateSummary(o,t.length,l),m=n.reduce((h,b)=>h+b.ruleCount,0),g={filesScanned:t.length,linesScanned:c,rulesApplied:m+(a.length>0?a.length:0)};return await this.storeScanResults(r,"sast",o,d),this.activeScans.set(r,"completed"),f({scanId:r,vulnerabilities:o,summary:d,coverage:g})}catch(i){return this.activeScans.set(r,"failed"),p(y(i))}}async runPatternScanning(t,e){let r=[],i=0;for(let n of t){let s=await this.analyzeFile(n,e);r.push(...s.vulnerabilities),i+=s.linesScanned}return{vulnerabilities:r,linesScanned:i}}async runSemgrepScanning(t,e){if(!this.config.enableSemgrep)return[];try{if(!await Vi())return[];let i=this.resolveTargetDirectory(t),n=await Gs(i,e);return!n.success||n.findings.length===0?[]:Hs(n.findings).map(a=>({id:v(),cveId:void 0,title:a.title,description:`[semgrep] ${a.description}`,severity:a.severity,category:this.mapSemgrepCategory(a.owaspCategory),location:{file:a.file,line:a.line,column:a.column,snippet:a.snippet},remediation:{description:a.remediation,estimatedEffort:"moderate",automatable:!1},references:a.references}))}catch{return[]}}resolveTargetDirectory(t){if(t.length===0)return".";if(t.length===1)return t[0].directory||".";let e=t.map(a=>a.directory||"."),r=e[0],i=r.length;for(let a=1;a<e.length;a++){let o=e[a],c=Math.min(i,o.length),l=0;for(;l<c&&r[l]===o[l];)l++;i=l}let n=r.substring(0,i),s=n.lastIndexOf("/");return s>0?n.substring(0,s):n||"."}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[...Ni,...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 p(y(e))}}async analyzeFile(t,e){let r=[],i=t.value,n=t.extension,s,a;try{s=await(await import("fs/promises")).readFile(i,"utf-8"),a=s.split(`
2892
+ `).filter(o=>o.startsWith("Test")||o.startsWith("Example")||o.startsWith("Benchmark")),i=r.filter(o=>o.startsWith("Test")).length,n=r.filter(o=>o.startsWith("Test")&&!o.includes("Integration")&&!o.includes("E2E")).length,s=r.filter(o=>o.includes("Integration")).length,a=r.filter(o=>o.includes("E2E")).length;return{total:i,unit:n,integration:s,e2e:a,source:"go"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"go"}}}function Mi(u,t){let e=0,r=0,i=0,n=0;function s(a){if(!ge(a))return;let o=df(a,{withFileTypes:!0});for(let c of o){let l=ve(a,c.name);if(c.isDirectory()){if(t.excludeDirs.includes(c.name))continue;s(l)}else if(c.isFile()&&vf(c.name)){let d=mf(c.name).toLowerCase(),m=0;[".ts",".tsx",".js",".jsx",".mjs"].includes(d)?m=Td(l):d===".py"?m=bf(l):d===".rs"?m=wf(l):d===".go"&&(m=Cf(l)),e+=m;let g=l.toLowerCase();g.includes("e2e")||g.includes("end-to-end")?n+=m:g.includes("integration")?i+=m:r+=m}}}return s(u),{total:e,unit:r,integration:i,e2e:n,source:"fallback"}}function vf(u){let t=u.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 Td(u){try{let t=Li(u,"utf-8"),e=t.match(/\bit\s*\(/g)||[],r=t.match(/\btest\s*\(/g)||[];return e.length+r.length}catch{return 0}}function bf(u){try{let t=Li(u,"utf-8"),e=t.match(/\bdef\s+test_\w+\s*\(/g)||[],r=t.match(/\basync\s+def\s+test_\w+\s*\(/g)||[];return e.length+r.length}catch{return 0}}function wf(u){try{let t=Li(u,"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 Cf(u){try{return(Li(u,"utf-8").match(/\bfunc\s+Test\w+\s*\(/g)||[]).length}catch{return 0}}function Ns(u,t,e){let r=u,i=0,n=0;return(ge(ve(e,"tests","integration"))||ge(ve(e,"test","integration"))||ge(ve(e,"__tests__","integration")))&&(i=Math.floor(u*.2),r-=i),(ge(ve(e,"tests","e2e"))||ge(ve(e,"test","e2e"))||ge(ve(e,"e2e"))||ge(ve(e,"cypress")))&&(n=Math.floor(u*.1),r-=n),{total:u,unit:Math.max(0,r),integration:i,e2e:n,source:t}}var Cc=class{config;cache=new Map;cacheHits=0;cacheMisses=0;constructor(t={}){this.config={...Nt,...t}}async collectAll(t){let e=`all:${t}`;if(this.config.enableCache){let l=this.getFromCache(e);if(l)return l}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",c={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,c),c}async countLOC(t){let e=`loc:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await fc(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 bc(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}checkTools(){let t=yc(),e=wc(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 Vt(_t(t,"Cargo.toml"))?"rust":Vt(_t(t,"go.mod"))?"go":Vt(_t(t,"pyproject.toml"))||Vt(_t(t,"requirements.txt"))?"python":Vt(_t(t,"package.json"))?Vt(_t(t,"tsconfig.json"))?"typescript":"javascript":"unknown"}countPatternsInternal(t,e){let r={},i=0,n=0,s=0,a=0,o=this.getPatternsForLanguage(e);function c(l){if(!Vt(l))return;let d=Rf(l,{withFileTypes:!0});for(let m of d){let g=_t(l,m.name);if(m.isDirectory()){if(["node_modules","dist","coverage","build",".git","vendor","target"].includes(m.name))continue;c(g)}else if(m.isFile()){let h=Tf(m.name).toLowerCase();if(Af(h,e)){let b=Ef(g,o);(b.unwraps>0||b.unsafeBlocks>0||b.todoComments>0||b.consoleStatements>0)&&(r[g]=b,i+=b.unwraps,n+=b.unsafeBlocks,s+=b.todoComments,a+=b.consoleStatements)}}}}return c(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 Af(u,t){switch(t){case"rust":return u===".rs";case"python":return[".py",".pyw"].includes(u);case"go":return u===".go";case"typescript":return[".ts",".tsx"].includes(u);case"javascript":return[".js",".jsx",".mjs",".cjs"].includes(u);default:return[".ts",".tsx",".js",".jsx",".py",".rs",".go"].includes(u)}}function Ef(u,t){try{let e=Sf(u,"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 Ad(u={}){return new Cc(u)}M();A();se();Yt();A();Yt();A();Yt();A();Yt();A();se();Yt();A();var NO=300*1e3;qe();qe();M();qe();var YO=R.create("temporal-compression");A();M();var t1=R.create("ruvector-server-client");qm();import{Buffer as _f}from"buffer";var c1=_f.from("COGCNTNR","ascii");qe();qe();var Bf={capacity:1e4,minCoherenceThreshold:.3,highTierThreshold:.8,mediumTierThreshold:.5,highTierWeight:3,mediumTierWeight:1.5,lowTierWeight:1},Sc=class{config;cusumDetector;buffer;totalSeen=0;totalAdmitted=0;totalRejected=0;totalEvicted=0;totalSampled=0;constructor(t){this.config={...Bf,...t},this.cusumDetector=new _a({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),c=Math.floor(a/o);if(c<this.config.capacity){let l=this.selectEvictionTarget(c);return this.buffer[l]=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 l=0;l<r.length;l++)s.has(l)||(a+=i[l]);if(a<=0)break;let o=Math.random()*a,c=-1;for(let l=0;l<r.length;l++)if(!s.has(l)&&(o-=i[l],o<=0)){c=l;break}if(c===-1){for(let l=0;l<r.length;l++)if(!s.has(l)){c=l;break}}c>=0&&(s.add(c),r[c].replayCount++,n.push(r[c]))}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}};se();var yr=R.create("code-intelligence/gnn");async function Ed(u,t,e){try{for(let r of e)try{let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Rc(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}};u.addEmbedding(s)}}catch(i){yr.error(`Failed to index ${r}:`,i instanceof Error?i:void 0)}yr.info(`Indexed ${e.length} code embeddings`)}catch(r){yr.error("Failed to index code embeddings:",r instanceof Error?r:void 0)}}async function Rc(u,t){let e=[],r=u.split(".").pop(),i=_s(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)||[],c=t.match(/if\s*\(/g)||[];e.push(Math.min(1,(o.length+c.length)/30));let l=t.match(/\/\/.*|\/\*[\s\S]*?\*\//g)||[];e.push(Math.min(1,l.length/50));let d=_s(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 xd(u,t){try{let r={vector:await Rc("query",t),dimension:384,namespace:"code",text:t,timestamp:Date.now(),quantization:"none"};return u.search(r,{limit:10,namespace:"code"}).map(n=>({file:n.metadata?.path??`file-${n.id}`,similarity:1-n.distance}))}catch(e){return yr.error("Failed to search with GNN:",e instanceof Error?e:void 0),[]}}async function Pd(u,t,e){try{for(let r of e.changedFiles){let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Rc(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}},a=u.search(s,{limit:5,namespace:"code"});yr.info(`Found ${a.length} semantically similar files to ${r}`)}}}catch(r){yr.error("Failed to enhance impact analysis:",r instanceof Error?r:void 0)}}function kd(u,t){let e=new Map,r=new Map;for(let i of u)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 _s(u){let t=0;for(let e=0;e<u.length;e++)t=(t<<5)-t+u.charCodeAt(e),t=t|0;return Math.abs(t)}M();A();var Ve=R.create("code-intelligence/hypergraph");async function Id(u,t,e){try{let r=await u.findUntestedFunctions();if(Ve.info(`[CodeIntelligence] Found ${r.length} untested functions via hypergraph`),e){let i=D("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 Ve.error("Failed to find untested functions:"),p(i)}}async function Dd(u,t,e,r){if(t.length===0)return{success:!0,value:[]};try{let i=await u.findImpactedTests(t);if(Ve.info(`[CodeIntelligence] Found ${i.length} impacted tests for ${t.length} changed files via hypergraph`),r){let n=D("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 Ve.error("Failed to find impacted tests:"),p(n)}}async function Md(u,t,e,r){try{let i=await u.findCoverageGaps(t);if(Ve.info(`[CodeIntelligence] Found ${i.length} coverage gaps (functions with <=${t}% coverage) via hypergraph`),r){let n=D("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 Ve.error("Failed to find coverage gaps:"),p(n)}}async function Fd(u,t,e,r,i){try{Ve.info(`[CodeIntelligence] Building hypergraph from ${t.files.length} indexed files`);let n=await u.buildFromIndexResult(t);if(Ve.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=D("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 Ve.error("Failed to build hypergraph:"),p(s)}}async function Ld(u,t,e){try{let r=await u.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 Ve.error("Failed to enhance impact with hypergraph:",r instanceof Error?r:void 0),e}}M();var vr=R.create("code-intelligence/consensus");async function $d(u,t,e,r){let i=V({id:v(),type:"code-pattern-detection",confidence:t,description:`Verify code pattern: ${u.name} (${u.type}) at ${u.location}`,payload:u,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"?(vr.info(`Code pattern '${u.name}' verified by consensus`),!0):(vr.warn(`Code pattern '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Od(u,t,e,r){let i=V({id:v(),type:"impact-analysis",confidence:t,description:`Verify impact analysis: ${u.changedFiles.length} files, risk=${u.riskLevel}, ${u.impactedTests.length} tests`,payload:u,detectedBy:"code-intelligence-coordinator",severity:u.riskLevel==="critical"||u.riskLevel==="high"?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(vr.info(`Impact analysis verified by consensus (risk=${u.riskLevel})`),!0):(vr.warn(`Impact analysis NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Nd(u,t,e,r){let i=V({id:v(),type:"dependency-mapping",confidence:t,description:`Verify dependency: ${u.source} -> ${u.targets.length} targets (${u.type})`,payload:u,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"?(vr.info("Dependency mapping verified by consensus"),!0):(vr.warn(`Dependency mapping NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var ny={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},ie=R.create("code-intelligence"),Oi=class extends Q{constructor(e,r,i,n={}){let s={...ny,...n};super(e,"code-intelligence",s,{verifyFindingTypes:["code-pattern-detection","impact-analysis","dependency-mapping"]});this.memory=r;this.agentCoordinator=i;this.knowledgeGraph=new Rt(r),this.semanticAnalyzer=new Ot(r),this.impactAnalyzer=new Br(r,this.knowledgeGraph),this.fileReader=new De,this.productFactorsBridge=new $s(e,r,{publishEvents:this.config.publishEvents})}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=Ad({enableCache:!0,cacheTTL:3e5}),ie.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-3JQP4EPU.js"),r=await import("fs"),i=await import("path"),{findProjectRoot:n}=await import("./unified-memory-2ETCY22B.js"),s=n(),a=this.config.hypergraphDbPath||i.join(s,".agentic-qe","memory.db"),o=i.dirname(a);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),this.hypergraphDb=e(a),this.hypergraph=await nn({db:this.hypergraphDb,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:this.config.enableGNN}),ie.info(`Hypergraph Engine initialized at ${a}`)}catch(e){let r=e instanceof Error?e.message:String(e);if(ie.warn(`Hypergraph Engine initialization failed (feature degraded): ${r}`),this.hypergraph=void 0,this.hypergraphDb=void 0,this.config.publishEvents){let i=D("code-intelligence.HypergraphDegraded","code-intelligence",{reason:r});this.eventBus.publish(i).catch(()=>{})}}}async initializeRLIntegrations(){try{if(this.config.enableGNN&&(Va(),this.gnnIndex=rn.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 me({domain:"code-intelligence",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.6}),ie.info("PersistentSONAEngine initialized for code pattern learning")}catch(e){ie.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(e){throw ie.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){if(await this.saveWorkflowState(),this.gnnIndex&&rn.closeInstance("code-intelligence"),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(e){ie.error("Error closing SONA engine:",e instanceof Error?e:void 0)}if(this.hypergraphDb){try{this.hypergraphDb.close()}catch(e){ie.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=v();try{if(this.startWorkflow(r,"index"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Indexing paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn indexing agents"));let i=await this.spawnIndexerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,10);let n=await this.knowledgeGraph.index(e);if(n.success){if(this.updateWorkflowProgress(r,40),this.config.enableGNN&&this.gnnIndex&&e.paths.length>0&&await this.indexCodeEmbeddings(e.paths),this.updateWorkflowProgress(r,60),this.config.enableMetricCollector&&this.metricCollector&&e.paths.length>0){let s=this.getProjectRootFromPaths(e.paths);s&&await this.collectProjectMetrics(s)}if(this.updateWorkflowProgress(r,70),e.paths.length>0&&await this.indexForSemanticSearch(e.paths),this.updateWorkflowProgress(r,85),this.config.enableHypergraph&&this.hypergraph&&e.paths.length>0)try{let s=await this.buildCodeIndexResultFromPaths(e.paths);s.files.length>0&&(await this.hypergraph.buildFromIndexResult(s),ie.info(`Hypergraph rebuilt from ${s.files.length} indexed files`))}catch(s){ie.warn(`Hypergraph rebuild skipped: ${s instanceof Error?s.message:s}`)}this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.publishEvents&&await this.publishKnowledgeGraphUpdated(n.value)}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),p(n)}}async search(e){let r=v();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&&ie.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),p(n)}}async analyzeImpact(e){let r=v();try{if(this.startWorkflow(r,"impact"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative impact analysis"),this.minCutMixin.shouldPauseOperations())return p(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),p(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),p(n)}}async mapDependencies(e){let r=v();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),p(n)}}async queryKG(e){let r=v();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),p(n)}}async indexCodeEmbeddings(e){!this.gnnIndex||!this.rlInitialized||await Ed(this.gnnIndex,this.fileReader,e)}async searchCodeWithGNN(e){return!this.gnnIndex||!this.rlInitialized?[]:xd(this.gnnIndex,e.query)}async enhanceImpactAnalysisWithGNN(e){!this.gnnIndex||!this.rlInitialized||await Pd(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 ie.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});ie.info(`Stored impact pattern ${a.id}`)}catch(i){ie.error("Failed to store impact pattern:",i instanceof Error?i:void 0)}}mergeSearchResults(e,r){return kd(e,r)}hashCode(e){return _s(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=D(tt.KnowledgeGraphUpdated,"code-intelligence",r);await this.eventBus.publish(i)}async publishImpactAnalysisCompleted(e,r){let i={analysisId:v(),changedFiles:e.changedFiles,impactedFiles:[...r.directImpact.map(s=>s.file),...r.transitiveImpact.map(s=>s.file)],impactedTests:r.impactedTests,riskLevel:r.riskLevel},n=D(tt.ImpactAnalysisCompleted,"code-intelligence",i);await this.eventBus.publish(n)}async publishSemanticSearchCompleted(e,r){let i=D(tt.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=v();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),ie.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),p(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:36e5}),await this.memory.set(`c4-components:${this.hashCode(e)}`,r.components,{namespace:"code-intelligence",ttl:36e5}),await this.memory.set(`c4-external-systems:${this.hashCode(e)}`,r.externalSystems,{namespace:"code-intelligence",ttl:36e5})}async collectProjectMetrics(e){if(!this.config.enableMetricCollector||!this.metricCollector)return p(new Error("MetricCollector is not enabled"));try{ie.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(ie.info(`[CodeIntelligence] Real metrics collected: ${r.loc.total} LOC, ${r.tests.total} tests, tools: ${i}`),r.loc.source==="node-native"&&ie.info("[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)"),await this.storeProjectMetricsInMemory(e,r),this.config.publishEvents){let n=D("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 ie.error("Failed to collect metrics:"),p(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:3e5}),await this.memory.set(`loc-metrics:${this.hashCode(e)}`,r.loc,{namespace:"code-intelligence",ttl:3e5}),await this.memory.set(`test-metrics:${this.hashCode(e)}`,r.tests,{namespace:"code-intelligence",ttl:3e5})}getMetricCollector(){return this.metricCollector}getProjectRootFromPaths(e){if(e.length===0)return null;let r=e[0],i=r.split("/"),n="";for(let a of i){n=n?`${n}/${a}`:a;let o=["package.json","Cargo.toml","go.mod","pyproject.toml",".git"];for(let c of o)try{let l=`${n}/${c}`;if(Pa("fs").existsSync(l))return n}catch{}}let s=r.lastIndexOf("/");return s>0?r.substring(0,s):r}isHypergraphEnabled(){return this.config.enableHypergraph&&this.hypergraph!==void 0}async findUntestedFunctions(){return this.hypergraph?Id(this.hypergraph,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findImpactedTestsFromHypergraph(e){return this.hypergraph?Dd(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findCoverageGapsFromHypergraph(e=50){return this.hypergraph?Md(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async buildHypergraphFromIndex(e){return this.hypergraph?Fd(this.hypergraph,e,this.memory,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}getHypergraph(){return this.hypergraph}async enhanceImpactWithHypergraph(e,r){return this.hypergraph?Ld(this.hypergraph,e,r):r}async buildCodeIndexResultFromPaths(e){let{extractCodeIndex:r}=await import("./code-index-extractor-B2KUPAEH.js");return r(e)}async verifyCodePatternDetection(e,r){return $d(e,r,this.consensusMixin,this.domainName)}async verifyImpactAnalysis(e,r){return Od(e,r,this.consensusMixin,this.domainName)}async verifyDependencyMapping(e,r){return Nd(e,r,this.consensusMixin,this.domainName)}};A();var zs=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;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(){return new Map([["index",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.paths;if(!r||r.length===0)return p(new Error("Invalid index payload: missing paths"));let i=e.language?[e.language]:e.languages;return this.coordinator.index({paths:r,languages:i})}],["search",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.query;return r?this.coordinator.search({query:r,type:e.type??"semantic",limit:e.limit}):p(new Error("Invalid search payload: missing query"))}],["analyze-impact",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.changedFiles;return!r||r.length===0?p(new Error("Invalid analyze-impact payload: missing changedFiles")):this.coordinator.analyzeImpact({changedFiles:r})}],["query-dependencies",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.file,n=e.files??(r?[r]:void 0);return!n||n.length===0?p(new Error("Invalid query-dependencies payload: missing file or files")):this.coordinator.mapDependencies({files:n,direction:e.direction??"both",depth:e.depth})}]])}async onInitialize(){this.knowledgeGraph=new Rt(this.memory,this.pluginConfig.knowledgeGraph),this.semanticAnalyzer=new Ot(this.memory,this.pluginConfig.semanticAnalyzer),this.impactAnalyzer=new Br(this.memory,this.knowledgeGraph,this.pluginConfig.impactAnalyzer),this.coordinator=new Oi(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,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){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 Tc(u,t,e,r){return new zs(u,t,e,r)}M();A();var he=class u{constructor(t){this._value=t;if(!t||t.trim()==="")throw new Error("FilePath cannot be empty")}_value;get value(){return this._value}get extension(){let t=this._value.split(".");return t.length>1?t[t.length-1]:""}get directory(){let t=this._value.lastIndexOf("/");return t>0?this._value.substring(0,t):""}get filename(){let t=this._value.lastIndexOf("/");return t>=0?this._value.substring(t+1):this._value}equals(t){return this._value===t._value}static create(t){return new u(t)}};var br=class u{constructor(t){this._value=t;if(t<0||t>1)throw new Error("RiskScore must be between 0 and 1")}_value;get value(){return this._value}get percentage(){return this._value*100}get level(){return this._value>=.8?"critical":this._value>=.6?"high":this._value>=.3?"medium":"low"}isHigherThan(t){return this._value>t._value}equals(t){return this._value===t._value}static create(t){return new u(t)}static fromPercentage(t){return new u(t/100)}},_e=class u{constructor(t,e){this._start=t;this._end=e;if(t>e)throw new Error("Start date cannot be after end date")}_start;_end;get start(){return this._start}get end(){return this._end}get durationMs(){return this._end.getTime()-this._start.getTime()}get durationSeconds(){return this.durationMs/1e3}contains(t){return t>=this._start&&t<=this._end}overlaps(t){return this._start<=t._end&&t._start<=this._end}equals(t){return this._start.getTime()===t._start.getTime()&&this._end.getTime()===t._end.getTime()}static create(t,e){return new u(t,e)}static lastNDays(t){let e=new Date,r=new Date(e.getTime()-t*24*60*60*1e3);return new u(r,e)}},zt=class u{constructor(t,e,r,i){this._major=t;this._minor=e;this._patch=r;this._prerelease=i}_major;_minor;_patch;_prerelease;get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let t=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${t}-${this._prerelease}`:t}isNewerThan(t){return this._major!==t._major?this._major>t._major:this._minor!==t._minor?this._minor>t._minor:this._patch>t._patch}equals(t){return this._major===t._major&&this._minor===t._minor&&this._patch===t._patch&&this._prerelease===t._prerelease}static create(t,e,r,i){return new u(t,e,r,i)}static parse(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!e)throw new Error(`Invalid version format: ${t}`);return new u(parseInt(e[1]),parseInt(e[2]),parseInt(e[3]),e[4])}};var Bs={defaultRuleSets:["owasp-top-10","cwe-sans-25"],maxConcurrentScans:4,timeout:3e5,enableFalsePositiveDetection:!0,dastMaxDepth:5,dastActiveScanning:!1,enableLLMAnalysis:!0,llmModelTier:4,enableSemgrep:!0};M();var Ac=[{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"}],Ec=[{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"}],xc=[{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"}],Pc=[{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"}],kc=[{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"}],Ic=[{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())"}],Dc=[{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"}],Mc=[{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"] })'}],qs=[...Ac,...Ec,...xc,...Pc,...kc,...Ic,...Dc,...Mc],Ni=[{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"]}];A();H();A();H();import{execFile as sy}from"child_process";import{promisify as ay}from"util";import*as zd from"path";var Fc=ay(sy);async function Vi(){try{return await Fc("semgrep",["--version"],{timeout:5e3}),!0}catch{return!1}}async function Vd(){try{let{stdout:u}=await Fc("semgrep",["--version"],{timeout:5e3});return u.trim()}catch{return null}}async function oy(u){let t={target:u.target||".",config:u.config||"auto",exclude:u.exclude||["node_modules",".git","dist","build","coverage"],maxFileSize:u.maxFileSize||5e6,timeout:u.timeout||300,verbose:u.verbose||!1};if(!await Vi())return{success:!1,findings:[],errors:["Semgrep is not installed. Install with: pip install semgrep"]};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 Fc("semgrep",r,{timeout:i,maxBuffer:50*1024*1024,cwd:zd.isAbsolute(t.target)?void 0:process.cwd()}),a=_d(n);return s&&t.verbose&&a.errors.push(s),a.version=await Vd()||void 0,a}catch(r){let i=r;if(i.stdout)try{let n=_d(i.stdout);return n.version=await Vd()||void 0,n}catch{}return{success:!1,findings:[],errors:[i.message??String(r)]}}}function _d(u){try{let t=E(u),e=t.results||t.findings||[],r=t.errors?.map(i=>i.message||String(i))||[];return{success:!0,findings:e.map(i=>({check_id:i.check_id||i.rule_id||"unknown",path:i.path,start:{line:i.start?.line||1,col:i.start?.col||1},end:{line:i.end?.line||i.start?.line||1,col:i.end?.col||1},extra:{message:i.extra?.message||i.message||"Security issue detected",severity:i.extra?.severity||i.severity||"WARNING",lines:i.extra?.lines||"",metadata:{cwe:i.extra?.metadata?.cwe||i.metadata?.cwe,owasp:i.extra?.metadata?.owasp||i.metadata?.owasp,category:i.extra?.metadata?.category||i.metadata?.category,description:i.extra?.metadata?.description||i.metadata?.description,fix:i.extra?.metadata?.fix||i.extra?.fix,references:i.extra?.metadata?.references||i.metadata?.references,confidence:i.extra?.metadata?.confidence||i.metadata?.confidence}}})),errors:r}}catch(t){return{success:!1,findings:[],errors:[`Failed to parse semgrep output: ${T(t)}`]}}}async function Gs(u,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 oy({...e,target:u,config:i||"auto"})}function cy(u){return{ERROR:"high",WARNING:"medium",INFO:"low"}[u]||"medium"}function Hs(u){return u.map(t=>({id:t.check_id,title:t.check_id.split(".").pop()||t.check_id,description:t.extra.message,severity:cy(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 ly=R.create("security-compliance/sast-scanner"),wr=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=v();try{if(t.length===0)return p(new Error("No files provided for scanning"));this.activeScans.set(r,"running");let i=Date.now(),n=Ni.filter(h=>e.includes(h.id));if(n.length===0)return p(new Error(`No valid rule sets found: ${e.join(", ")}`));let[s,a]=await Promise.all([this.runPatternScanning(t,n),this.runSemgrepScanning(t,e)]),o=this.mergeVulnerabilities(s.vulnerabilities,a),c=s.linesScanned,l=Date.now()-i,d=this.calculateSummary(o,t.length,l),m=n.reduce((h,b)=>h+b.ruleCount,0),g={filesScanned:t.length,linesScanned:c,rulesApplied:m+(a.length>0?a.length:0)};return await this.storeScanResults(r,"sast",o,d),this.activeScans.set(r,"completed"),f({scanId:r,vulnerabilities:o,summary:d,coverage:g})}catch(i){return this.activeScans.set(r,"failed"),p(y(i))}}async runPatternScanning(t,e){let r=[],i=0;for(let n of t){let s=await this.analyzeFile(n,e);r.push(...s.vulnerabilities),i+=s.linesScanned}return{vulnerabilities:r,linesScanned:i}}async runSemgrepScanning(t,e){if(!this.config.enableSemgrep)return[];try{if(!await Vi())return[];let i=this.resolveTargetDirectory(t),n=await Gs(i,e);return!n.success||n.findings.length===0?[]:Hs(n.findings).map(a=>({id:v(),cveId:void 0,title:a.title,description:`[semgrep] ${a.description}`,severity:a.severity,category:this.mapSemgrepCategory(a.owaspCategory),location:{file:a.file,line:a.line,column:a.column,snippet:a.snippet},remediation:{description:a.remediation,estimatedEffort:"moderate",automatable:!1},references:a.references}))}catch{return[]}}resolveTargetDirectory(t){if(t.length===0)return".";if(t.length===1)return t[0].directory||".";let e=t.map(a=>a.directory||"."),r=e[0],i=r.length;for(let a=1;a<e.length;a++){let o=e[a],c=Math.min(i,o.length),l=0;for(;l<c&&r[l]===o[l];)l++;i=l}let n=r.substring(0,i),s=n.lastIndexOf("/");return s>0?n.substring(0,s):n||"."}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[...Ni,...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 p(y(e))}}async analyzeFile(t,e){let r=[],i=t.value,n=t.extension,s,a;try{s=await(await import("fs/promises")).readFile(i,"utf-8"),a=s.split(`
2892
2893
  `)}catch{return{vulnerabilities:[],linesScanned:0}}let o=a.length;if(!["ts","tsx","js","jsx","mjs","cjs"].includes(n))return{vulnerabilities:[],linesScanned:o};let l=new Set(e.flatMap(m=>m.categories)),d=qs.filter(m=>l.has(m.category));for(let m of d){let g=this.findPatternMatches(s,a,m);for(let h of g)this.isInComment(s,h.index)||this.isInDocumentation(h.snippet)||this.hasNosecAnnotation(a,h.line)||r.push(this.createVulnerabilityFromPattern(m,i,h))}return{vulnerabilities:r,linesScanned:o}}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:c}=this.getLineAndColumn(t,a),l=[],d=Math.max(0,o-2),m=Math.min(e.length-1,o+1);for(let h=d;h<=m;h++)l.push(e[h]);let g=l.join(`
2893
2894
  `);i.push({index:a,line:o+1,column:c+1,snippet:g})}return i}getLineAndColumn(t,e){let i=t.substring(0,e).split(`
2894
2895
  `),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(`
@@ -2916,9 +2917,9 @@ Provide detailed remediation advice specific to this code.`}],model:r,maxTokens:
2916
2917
  `),c=na.validation.some(d=>d.test(a)),l=na.masking.some(d=>d.test(a));for(let d=0;d<o.length;d++){let m=o[d];for(let g of na.piiFields)if(g.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(`
2917
2918
  `);!na.masking.some(w=>w.test(h))&&!l&&r.push({file:n,line:d+1,snippet:m.trim().substring(0,100),pattern:"unmasked-pii",severity:"warning"})}}e.length>0&&!c&&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 c=await this.fileReader.readFile(o);if(!c.success)continue;let l=c.value;sa.rateLimiting.some(d=>d.test(l))&&(i=!0),sa.csrf.some(d=>d.test(l))&&(n=!0),sa.cors.some(d=>d.test(l))&&(s=!0),sa.sanitization.some(d=>d.test(l))&&(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(`
2918
2919
  `);for(let o=0;o<a.length;o++){let c=a[o];for(let l of e){let d=i[l]||[];for(let m of d)if(m.test(c)){let g=r.get(l)||[];g.push({file:n,line:o+1,snippet:c.trim().substring(0,100),pattern:l,severity:"info"}),r.set(l,g);break}}}}return r}},zc=null;function Bc(){return zc||(zc=new aa),zc}var Gd=["ls","cat","echo","grep","find","head","tail","wc","npm","node","yarn","pnpm","git","jest","vitest","playwright"],Hd=[/;/,/&&/,/\|\|/,/\|/,/`[^`]*`/,/\$\([^)]*\)/,/>\s*\/dev\/sd/i,/>\s*\/etc\//i],fy=/[|;&$`<>{}[\]!#*?~]/g,qi=class{name="command-injection";defaultAllowedCommands;constructor(t=Gd){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 Hd)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(fy,"")).join(" "),blockedPatterns:[],riskLevel:"none"}:{valid:!1,error:`Command '${n}' is not in the allowed list`,blockedPatterns:[],riskLevel:"high"}}escapeShellArg(t){return`'${t.replace(/'/g,"'\\''")}'`}},qd=new qi,oa=(u,t)=>t?qd.validateCommand(u,t):qd.validate(u);var Wd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;","`":"&#x60;","=":"&#x3D;"},jd=[/('|")\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],Ud=/[|;&$`<>{}[\]!#*?~]/g,Qd=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,ca=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:c=!0}=e,l=t;if(c&&(l=l.replace(Qd,"")),o&&(l=l.trim()),l.length>r&&(l=l.substring(0,r)),n&&(l=this.stripHtmlTags(l)),s)for(let d of jd)l=l.replace(d,"");return a&&(l=l.replace(Ud,"")),i&&(l=l.split("").filter(d=>i.test(d)).join("")),l}escapeHtml(t){return t.replace(/[&<>"'`=/]/g,e=>Wd[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}},kq=new ca;import{createHash as Kd,timingSafeEqual as yy,randomBytes as vy}from"crypto";var la=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 yy(Buffer.from(i),Buffer.from(n))}catch{return!1}}timingSafeHashCompare(t,e){let r=Kd("sha256").update(t).digest("hex");return this.timingSafeCompare(r,e)}generateSecureToken(t=32){return vy(t).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}secureHash(t,e){let r=e?`${e}:${t}`:t;return Kd("sha256").update(r).digest("hex")}},Mq=new la;A();H();var Sr=class{config;memory;osvClient;activeScans;constructor(t,e,r){this.config=t,this.memory=e,this.osvClient=new zi({enableCache:!0}),this.activeScans=r||new Map}async scanDependencies(t){let e=v(),r=Date.now();try{if(Object.keys(t).length===0)return p(new Error("No dependencies provided for scanning"));this.activeScans.set(e,"running");let i=await this.osvClient.scanNpmDependencies(t),n=this.convertOSVVulnerabilities(i),s=Date.now()-r,a=new Set(i.map(c=>c.affectedPackage)),o=this.calculateSummary(n,Object.keys(t).length,s);return await this.storeScanResults(e,"dependency",n,o),this.activeScans.set(e,"completed"),f({scanId:e,vulnerabilities:n,packagesScanned:Object.keys(t).length,vulnerablePackages:a.size,summary:o,scanDurationMs:s})}catch(i){return this.activeScans.set(e,"failed"),p(y(i))}}async scanPackageJson(t){try{let r=await(await import("fs/promises")).readFile(t,"utf-8"),i=E(r),n={...i.dependencies||{},...i.devDependencies||{},...i.peerDependencies||{},...i.optionalDependencies||{}};return Object.keys(n).length===0?p(new Error("No dependencies found in package.json")):this.scanDependencies(n)}catch(e){return e instanceof SyntaxError?p(new Error(`Invalid JSON in package.json: ${e.message}`)):p(y(e))}}async getScanStatus(t){return this.activeScans.get(t)??"pending"}convertOSVVulnerabilities(t){return t.map(e=>{let r={file:"package.json",line:1,column:1,snippet:`"${e.affectedPackage}": "..."`},i={description:e.fixedVersions.length>0?`Update to version ${e.fixedVersions[0]} or later`:"No fixed version available; consider alternative packages",fixExample:e.fixedVersions.length>0?`npm install ${e.affectedPackage}@${e.fixedVersions[0]}`:void 0,estimatedEffort:"minor",automatable:!0};return{id:v(),cveId:e.cveIds[0],title:`${e.affectedPackage}: ${e.summary.substring(0,80)}`,description:e.details||e.summary,severity:this.mapOSVSeverity(e.severity),category:"vulnerable-components",location:r,remediation:i,references:e.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,e,r,i){await this.memory.set(`security:scan:${t}`,{scanId:t,scanType:e,vulnerabilities:r,summary:i,timestamp:new Date().toISOString()},{namespace:"security-compliance",ttl:86400*7})}};A();var $e=class{config;memory;llmRouter;activeScans=new Map;sastScanner;dastScanner;dependencyScanner;constructor(t,e={}){this.config={...Bs,...e},"memory"in t?(this.memory=t.memory,this.llmRouter=t.llmRouter):this.memory=t,this.sastScanner=new wr(this.config,this.memory,this.llmRouter,this.activeScans),this.dastScanner=new Cr(this.config,this.memory,this.activeScans),this.dependencyScanner=new Sr(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 p(i.error);let n;if(e){let a=await this.scanUrl(e,r);a.success&&(n=a.value)}let s=this.combineSummaries(i.value.summary,n?.summary);return f({sastResult:i.value,dastResult:n,combinedSummary:s})}catch(i){return p(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}};M();import*as Hi from"fs/promises";import*as Wi from"path";A();H();async function qc(u,t){let e=await fetch(u,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await e.json();return{ok:e.ok,status:e.status,data:r}}async function Gi(u){let t=await fetch(u,{method:"GET",headers:{Accept:"application/json"}}),e=await t.json();return{ok:t.ok,status:t.status,data:e}}var Gc={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};M();import*as Jd from"fs/promises";import*as Yd from"path";var Cy=R.create("security-compliance/security-auditor-sast");function Sy(){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 Xd(u,t){let e=v(),r=Date.now(),i=[],n=0,s=0;try{let g=await u(process.cwd()),h=Sy();for(let b of g){if(t(b))continue;let w=Yd.extname(b).toLowerCase();if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(w))try{let C=await Jd.readFile(b,"utf-8"),S=C.split(`
2919
- `);n++,s+=S.length;for(let P of h){P.pattern.lastIndex=0;let k;for(;(k=P.pattern.exec(C))!==null;){let z=C.substring(0,k.index).split(`
2920
+ `);n++,s+=S.length;for(let k of h){k.pattern.lastIndex=0;let P;for(;(P=k.pattern.exec(C))!==null;){let z=C.substring(0,P.index).split(`
2920
2921
  `),K=z.length,Ce=z[z.length-1].length+1,Y=S[K-1]||"";if(Y.trimStart().startsWith("//")||Y.trimStart().startsWith("*")||Y.includes("// nosec")||Y.includes("// security-ignore"))continue;let G=Math.max(0,K-2),ne=Math.min(S.length,K+1),X=S.slice(G,ne).join(`
2921
- `),zm={file:b,line:K,column:Ce,snippet:X},Bm={description:P.remediation,fixExample:P.fixExample,estimatedEffort:P.severity==="critical"?"moderate":"minor",automatable:P.severity==="low"||P.severity==="medium"};i.push({id:v(),cveId:void 0,title:P.title,description:`${P.description} [${P.cweId}]`,severity:P.severity,category:P.category,location:zm,remediation:Bm,references:[`https://cwe.mitre.org/data/definitions/${P.cweId.replace("CWE-","")}.html`]})}}}catch{}}}catch(g){Cy.error("SAST scan failed:",g instanceof Error?g:void 0)}let a=Date.now()-r,o=0,c=0,l=0,d=0,m=0;for(let g of i)switch(g.severity){case"critical":o++;break;case"high":c++;break;case"medium":l++;break;case"low":d++;break;case"informational":m++;break}return{scanId:e,vulnerabilities:i,summary:{critical:o,high:c,medium:l,low:d,informational:m,totalFiles:n,scanDurationMs:a},coverage:{filesScanned:n,linesScanned:s,rulesApplied:12}}}M();A();var Ry=R.create("security-compliance/security-auditor-dast");async function Zd(u){let t=v(),e=Date.now(),r=[],i=0;try{let d;try{d=new URL(u)}catch{return{scanId:t,targetUrl:u,vulnerabilities:[{id:v(),title:"Invalid Target URL",description:"The provided target URL is not valid",severity:"informational",category:"security-misconfiguration",location:{file:u},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,g=setTimeout(()=>m.abort(),3e4);try{let h=await fetch(u,{method:"GET",headers:{"User-Agent":"AgenticQE-SecurityScanner/3.0",Accept:"text/html,application/json,*/*"},signal:m.signal,redirect:"follow"});clearTimeout(g),i=1;let b=h.headers,w=[{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 k of w)b.get(k.header)||r.push({id:v(),title:k.title,description:k.description,severity:k.severity,category:"security-misconfiguration",location:{file:u,snippet:`Response Headers: ${k.header} not present`},remediation:{description:k.remediation,estimatedEffort:"minor",automatable:!0},references:["https://owasp.org/www-project-secure-headers/"]});let C=b.get("set-cookie");C&&(C.toLowerCase().includes("secure")||r.push({id:v(),title:"Cookie Without Secure Flag",description:"Session cookie is set without the Secure flag",severity:"medium",category:"sensitive-data",location:{file:u,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:v(),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:u,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:v(),title:"Cookie Without SameSite Attribute",description:"Cookie is set without the SameSite attribute, potentially vulnerable to CSRF",severity:"low",category:"broken-auth",location:{file:u,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=b.get("server");S&&/[0-9]+\.[0-9]+/.test(S)&&r.push({id:v(),title:"Server Version Disclosure",description:`Server header reveals version information: ${S}`,severity:"low",category:"security-misconfiguration",location:{file:u,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:v(),title:"Insecure HTTP Protocol",description:"Target is using HTTP instead of HTTPS, exposing data in transit",severity:"high",category:"sensitive-data",location:{file:u},remediation:{description:"Use HTTPS with valid TLS certificate",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]});let P=[{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 k of P)try{let O=new URL(k.path,d.origin).toString(),z=await fetch(O,{method:"GET",signal:AbortSignal.timeout(5e3)});if(z.ok&&z.status===200){let K=await z.text();K.length>10&&!K.toLowerCase().includes("not found")&&(i++,r.push({id:v(),title:k.vuln,description:`Sensitive file found at ${k.path}`,severity:k.severity,category:"sensitive-data",location:{file:O},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(g);let b=T(h);(b.includes("certificate")||b.includes("SSL")||b.includes("TLS"))&&r.push({id:v(),title:"TLS/SSL Certificate Issue",description:`Certificate error: ${b}`,severity:"high",category:"security-misconfiguration",location:{file:u},remediation:{description:"Fix TLS certificate configuration",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}catch(d){Ry.error("DAST scan failed:",d instanceof Error?d:void 0)}let n=Date.now()-e,s=0,a=0,o=0,c=0,l=0;for(let d of r)switch(d.severity){case"critical":s++;break;case"high":a++;break;case"medium":o++;break;case"low":c++;break;case"informational":l++;break}return{scanId:t,targetUrl:u,vulnerabilities:r,summary:{critical:s,high:a,medium:o,low:c,informational:l,totalFiles:1,scanDurationMs:n},crawledUrls:i}}M();import*as em from"fs/promises";var Ty=R.create("security-compliance/security-auditor-secrets");function Ay(){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 Ey(u){if(!u||u.length===0)return 0;let t={};for(let i of u)t[i]=(t[i]||0)+1;let e=0,r=u.length;for(let i in t){let n=t[i]/r;e-=n*Math.log2(n)}return e}function xy(u,t,e){let n=Math.max(0,t-20),s=Math.min(u.length,t+e+10),a=u.substring(n,s),o=t-n,c=a.substring(o,o+e);if(c.length>8){let l=c.substring(0,4)+"..."+c.substring(c.length-4);a=a.substring(0,o)+l+a.substring(o+e)}return n>0&&(a="..."+a),s<u.length&&(a=a+"..."),a}function Py(u,t){switch(u){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 Hc(u){let t=[];try{let r=(await em.readFile(u.value,"utf-8")).split(`
2922
+ `),zm={file:b,line:K,column:Ce,snippet:X},Bm={description:k.remediation,fixExample:k.fixExample,estimatedEffort:k.severity==="critical"?"moderate":"minor",automatable:k.severity==="low"||k.severity==="medium"};i.push({id:v(),cveId:void 0,title:k.title,description:`${k.description} [${k.cweId}]`,severity:k.severity,category:k.category,location:zm,remediation:Bm,references:[`https://cwe.mitre.org/data/definitions/${k.cweId.replace("CWE-","")}.html`]})}}}catch{}}}catch(g){Cy.error("SAST scan failed:",g instanceof Error?g:void 0)}let a=Date.now()-r,o=0,c=0,l=0,d=0,m=0;for(let g of i)switch(g.severity){case"critical":o++;break;case"high":c++;break;case"medium":l++;break;case"low":d++;break;case"informational":m++;break}return{scanId:e,vulnerabilities:i,summary:{critical:o,high:c,medium:l,low:d,informational:m,totalFiles:n,scanDurationMs:a},coverage:{filesScanned:n,linesScanned:s,rulesApplied:12}}}M();A();var Ry=R.create("security-compliance/security-auditor-dast");async function Zd(u){let t=v(),e=Date.now(),r=[],i=0;try{let d;try{d=new URL(u)}catch{return{scanId:t,targetUrl:u,vulnerabilities:[{id:v(),title:"Invalid Target URL",description:"The provided target URL is not valid",severity:"informational",category:"security-misconfiguration",location:{file:u},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,g=setTimeout(()=>m.abort(),3e4);try{let h=await fetch(u,{method:"GET",headers:{"User-Agent":"AgenticQE-SecurityScanner/3.0",Accept:"text/html,application/json,*/*"},signal:m.signal,redirect:"follow"});clearTimeout(g),i=1;let b=h.headers,w=[{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 P of w)b.get(P.header)||r.push({id:v(),title:P.title,description:P.description,severity:P.severity,category:"security-misconfiguration",location:{file:u,snippet:`Response Headers: ${P.header} not present`},remediation:{description:P.remediation,estimatedEffort:"minor",automatable:!0},references:["https://owasp.org/www-project-secure-headers/"]});let C=b.get("set-cookie");C&&(C.toLowerCase().includes("secure")||r.push({id:v(),title:"Cookie Without Secure Flag",description:"Session cookie is set without the Secure flag",severity:"medium",category:"sensitive-data",location:{file:u,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:v(),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:u,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:v(),title:"Cookie Without SameSite Attribute",description:"Cookie is set without the SameSite attribute, potentially vulnerable to CSRF",severity:"low",category:"broken-auth",location:{file:u,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=b.get("server");S&&/[0-9]+\.[0-9]+/.test(S)&&r.push({id:v(),title:"Server Version Disclosure",description:`Server header reveals version information: ${S}`,severity:"low",category:"security-misconfiguration",location:{file:u,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:v(),title:"Insecure HTTP Protocol",description:"Target is using HTTP instead of HTTPS, exposing data in transit",severity:"high",category:"sensitive-data",location:{file:u},remediation:{description:"Use HTTPS with valid TLS certificate",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]});let k=[{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 P of k)try{let O=new URL(P.path,d.origin).toString(),z=await fetch(O,{method:"GET",signal:AbortSignal.timeout(5e3)});if(z.ok&&z.status===200){let K=await z.text();K.length>10&&!K.toLowerCase().includes("not found")&&(i++,r.push({id:v(),title:P.vuln,description:`Sensitive file found at ${P.path}`,severity:P.severity,category:"sensitive-data",location:{file:O},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(g);let b=T(h);(b.includes("certificate")||b.includes("SSL")||b.includes("TLS"))&&r.push({id:v(),title:"TLS/SSL Certificate Issue",description:`Certificate error: ${b}`,severity:"high",category:"security-misconfiguration",location:{file:u},remediation:{description:"Fix TLS certificate configuration",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}catch(d){Ry.error("DAST scan failed:",d instanceof Error?d:void 0)}let n=Date.now()-e,s=0,a=0,o=0,c=0,l=0;for(let d of r)switch(d.severity){case"critical":s++;break;case"high":a++;break;case"medium":o++;break;case"low":c++;break;case"informational":l++;break}return{scanId:t,targetUrl:u,vulnerabilities:r,summary:{critical:s,high:a,medium:o,low:c,informational:l,totalFiles:1,scanDurationMs:n},crawledUrls:i}}M();import*as em from"fs/promises";var Ty=R.create("security-compliance/security-auditor-secrets");function Ay(){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 Ey(u){if(!u||u.length===0)return 0;let t={};for(let i of u)t[i]=(t[i]||0)+1;let e=0,r=u.length;for(let i in t){let n=t[i]/r;e-=n*Math.log2(n)}return e}function xy(u,t,e){let n=Math.max(0,t-20),s=Math.min(u.length,t+e+10),a=u.substring(n,s),o=t-n,c=a.substring(o,o+e);if(c.length>8){let l=c.substring(0,4)+"..."+c.substring(c.length-4);a=a.substring(0,o)+l+a.substring(o+e)}return n>0&&(a="..."+a),s<u.length&&(a=a+"..."),a}function Py(u,t){switch(u){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 Hc(u){let t=[];try{let r=(await em.readFile(u.value,"utf-8")).split(`
2922
2923
  `),i=Ay();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 c;for(;(c=o.regex.exec(s))!==null;){let l=c[1]||c[0],d=Ey(l);if(o.entropyThreshold&&d<o.entropyThreshold)continue;let m=xy(s,c.index,l.length),g={file:u.value,line:a,column:c.index+1,snippet:m};t.push({type:o.type,location:g,entropy:d,isValid:Py(o.type,l)})}}}}catch(e){Ty.error(`Failed to scan file for secrets: ${u.value}`,e instanceof Error?e:void 0)}return t}function tm(u,t,e,r){let i=0,n=0;if(u&&(i+=Wc(u.summary)*.35,n+=.35),t&&(i+=Wc(t.summary)*.25,n+=.25),e&&(i+=Wc(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 Wc(u){let t={critical:1,high:.7,medium:.4,low:.1,informational:.02};if(u.critical+u.high+u.medium+u.low+u.informational===0)return 0;let r=u.critical*t.critical+u.high*t.high+u.medium*t.medium+u.low*t.low+u.informational*t.informational;return Math.min(1,r/10)}function rm(u,t,e,r){let i=[];return u&&u.summary.critical>0&&i.push(`Address ${u.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 jc(u,t){if(!u)return 0;let e=0;return u.sastResults&&(e+=u.sastResults.summary[t]),u.dastResults&&(e+=u.dastResults.summary[t]),u.dependencyResults&&(e+=u.dependencyResults.summary[t]),e}function Rr(u){if(!u)return 0;let t=0;return u.sastResults&&(t+=u.sastResults.vulnerabilities.length),u.dastResults&&(t+=u.dastResults.vulnerabilities.length),u.dependencyResults&&(t+=u.dependencyResults.vulnerabilities.length),t}function im(u,t){if(!u||!t)return"stable";let e=Rr(u),r=Rr(t);return e<r*.9?"improving":e>r*1.1?"declining":"stable"}function nm(u,t,e){let r=100;return r-=u*20,r-=t*10,r-=e*2,Math.max(0,Math.min(100,r))}function sm(u,t,e){let r=[];return u>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 am(u){let t=u.remediation.estimatedEffort;return u.severity==="critical"?"immediate":u.severity==="high"?t==="trivial"||t==="minor"?"immediate":"shortTerm":u.severity==="medium"?t==="major"?"longTerm":"mediumTerm":u.severity==="low"||u.severity==="informational"?"longTerm":"accepted"}var Ze=R.create("security-compliance/security-auditor"),Bt=class{constructor(t,e={}){this.memory=t;this.config={...Gc,...e}}memory;config;async scanDependencies(t){try{let e=t.value,r=this.detectEcosystem(e);if(!r)return p(new Error(`Unknown manifest format: ${e}`));let i=[],n=[],s=await this.parseDependencies(e,r);for(let o of s){let c=await this.checkDependencyVulnerabilities(o,r);i.push(...c);let l=await this.checkOutdated(o);l&&n.push(l)}let a=this.createDependencySummary(i,s.length);return await this.memory.set(`security:deps:${t.filename}`,{vulnerabilities:i,outdatedPackages:n,summary:a},{namespace:"security-compliance",ttl:86400}),f({vulnerabilities:i,outdatedPackages:n,summary:a})}catch(e){return p(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 p(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",c=await this.getLatestVersion(a,s),l=n.filter(d=>d.id).map(d=>d.id);e.push({package:a,fromVersion:o,toVersion:c,fixesVulnerabilities:l,breakingChanges:this.hasBreakingChanges(o,c)})}return e.sort((i,n)=>n.fixesVulnerabilities.length-i.fixesVulnerabilities.length),f(e)}catch(e){return p(y(e))}}async runAudit(t){let e=v(),r=new Date;try{let i,n,s,a;t.includeSAST&&(i=await Xd(d=>this.findSourceFiles(d),d=>this.shouldExclude(d))),t.includeDAST&&t.targetUrl&&(n=await Zd(t.targetUrl)),t.includeDependencies&&(s=await this.performDependencyScan()),t.includeSecrets&&(a=await this.performSecretScan());let o=tm(i,n,s,a),c=rm(i,n,s,a),l={auditId:e,timestamp:r,sastResults:i,dastResults:n,dependencyResults:s,secretScanResults:a,overallRiskScore:o,recommendations:c};return await this.memory.set(`security:audit:${e}`,l,{namespace:"security-compliance",persist:!0}),f(l)}catch(i){return p(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 Hc(i);e.push(...n)}return f({secretsFound:e,filesScanned:r})}catch(e){return p(y(e))}}async getSecurityPosture(){try{let t=await this.getRecentAudits(),e=t[0],r=t[1],i=jc(e,"critical"),n=jc(e,"high"),s=Rr(e),a=im(e,r),o=nm(i,n,s),c=sm(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:c})}catch(t){return p(y(t))}}async triageVulnerabilities(t){try{let e={immediate:[],shortTerm:[],mediumTerm:[],longTerm:[],accepted:[]};for(let i of t){let n=am(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 p(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 Hi.readFile(t,"utf-8"),n=E(i),s={...n.dependencies,...n.devDependencies,...n.peerDependencies,...n.optionalDependencies};for(let[a,o]of Object.entries(s)){let c=this.cleanVersionSpec(o);r.push({name:a,version:c,ecosystem:"npm"})}}else if(e==="pip"){let n=(await Hi.readFile(t,"utf-8")).split(`
2923
2924
  `);for(let s of n){let a=s.trim();if(!a||a.startsWith("#"))continue;let o=a.match(/^([a-zA-Z0-9_-]+)(?:[=<>~!]+(.+))?$/);o&&r.push({name:o[1],version:o[2]||"latest",ecosystem:"pip"})}}}catch(i){Ze.error(`Failed to parse dependencies from ${t}:`,i instanceof Error?i:void 0)}return r}cleanVersionSpec(t){return t.replace(/^[\^~>=<]+/,"").trim()}async checkDependencyVulnerabilities(t,e){let r=[];try{let i=this.mapToOSVEcosystem(e),n={package:{name:t.name,ecosystem:i},version:t.version},s=await qc("https://api.osv.dev/v1/query",n);if(s.ok&&s.data.vulns&&s.data.vulns.length>0)for(let a of s.data.vulns){let o=this.mapOSVVulnerability(a,t);r.push(o)}}catch(i){Ze.error(`Failed to check vulnerabilities for ${t.name}@${t.version}:`,i instanceof Error?i:void 0)}return r}mapToOSVEcosystem(t){return{npm:"npm",pip:"PyPI",maven:"Maven",nuget:"NuGet",cargo:"crates.io"}[t]}mapOSVVulnerability(t,e){let r=t.aliases?.find(c=>c.startsWith("CVE-")),i=this.mapOSVSeverity(t.severity),n=this.extractFixedVersion(t),s=t.references?.map(c=>c.url)||[],a={file:"package.json",dependency:e},o={description:n?`Upgrade ${e.name} to version ${n} or higher`:`Review and address vulnerability in ${e.name}`,fixExample:n?`"${e.name}": "^${n}"`:void 0,estimatedEffort:n?"trivial":"moderate",automatable:!!n};return{id:v(),cveId:r,title:t.summary||`Vulnerability in ${e.name}`,description:t.details||t.summary||"No description available",severity:i,category:this.categorizeVulnerability(t),location:a,remediation:o,references:s}}mapOSVSeverity(t){if(!t||t.length===0)return"medium";let e=t.find(r=>r.type==="CVSS_V3"||r.type==="CVSS_V2");if(e){let r=parseFloat(e.score);if(r>=9)return"critical";if(r>=7)return"high";if(r>=4)return"medium";if(r>0)return"low"}return"medium"}extractFixedVersion(t){if(t.affected){for(let e of t.affected)if(e.ranges){for(let r of e.ranges)if(r.events){let i=r.events.find(n=>n.fixed);if(i?.fixed)return i.fixed}}}}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!==t.version?{name:t.name,currentVersion:t.version,latestVersion:e,updateType:this.determineUpdateType(t.version,e)}:null}async queryVulnerabilityDatabase(t,e,r){let i={name:t,version:e,ecosystem:r};return this.checkDependencyVulnerabilities(i,r)}async getLatestVersion(t,e){try{if(e==="npm"){let r=await Gi(`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`);if(r.ok&&r.data.version)return r.data.version}else if(e==="pip"){let r=await Gi(`https://pypi.org/pypi/${encodeURIComponent(t)}/json`);if(r.ok&&r.data.info?.version)return r.data.info.version}}catch(r){Ze.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 Gi(`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`);if(r.ok&&r.data.deprecated)return!0}}catch(r){Ze.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=[];try{let i=Wi.join(process.cwd(),"package.json"),n=await this.parseDependencies(i,"npm");for(let o of n){let c=await this.checkDependencyVulnerabilities(o,o.ecosystem);e.push(...c);let l=await this.checkOutdated(o);l&&r.push(l)}let s=Date.now()-t,a=this.createDependencySummary(e,n.length);return{vulnerabilities:e,outdatedPackages:r,summary:{...a,scanDurationMs:s}}}catch(i){return Ze.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}}}}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 Hc({value:i});t.push(...s)}}catch(r){Ze.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 Hi.readdir(t,{withFileTypes:!0});for(let n of i){let s=Wi.join(t,n.name);if(!this.shouldExclude(s)){if(n.isDirectory())await this.findSourceFiles(s,e);else if(n.isFile()){let a=Wi.extname(n.name).toLowerCase();(r.includes(a)||n.name.startsWith(".env"))&&e.push(s)}}}}catch{Ze.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=Rr(i),a=Rr(n);return Math.max(0,s-a)}catch(t){return Ze.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,c]of e)if(!a.has(o)){let l=(s.timestamp.getTime()-c.getTime())/36e5;r.push(l),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 Ze.error("Failed to calculate average resolution time:",t instanceof Error?t:void 0),72}}};A();var ky={customStandards:[],strictMode:!1,includeRecommended:!0,evidenceRetentionDays:365},Iy={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"}]},Dy={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"}]},My={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"}]},Fy={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"}]},Ly=[Iy,Dy,My,Fy],qt=class{constructor(t,e={}){this.memory=t;this.config={...ky,...e},this.patternAnalyzer=Bc(),this.standards=new Map;for(let r of Ly)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(l=>l.severity==="required");for(let l of s){if(l.checkType==="manual"){n.push(l.id);continue}let d=await this.checkRule(l,e);d.passed?i.push(l.id):r.push(...d.violations)}let a=s.length-n.length,o=a>0?Math.round(i.length/a*100):100,c={standardId:t.id,standardName:t.name,violations:r,passedRules:i,skippedRules:n,complianceScore:o,generatedAt:new Date};return await this.storeReport(c),f(c)}catch(r){return p(y(r))}}async getAvailableStandards(){return Array.from(this.standards.values())}async analyzeGaps(t,e){try{let r=[],i=[],n=new Set(t.violations.map(l=>l.ruleId)),s=new Set(t.passedRules);for(let l of e.rules)n.has(l.id)?r.push({ruleId:l.id,currentStatus:"failed",effort:this.estimateEffort(l),impact:l.severity==="required"?"high":"medium"}):s.has(l.id)||r.push({ruleId:l.id,currentStatus:"not-implemented",effort:this.estimateEffort(l),impact:l.severity==="required"?"high":"low"});let a=[...r].sort((l,d)=>{let m={high:0,medium:1,low:2},g={trivial:0,minor:1,moderate:2,major:3},h=m[l.impact]*10+g[l.effort],b=m[d.impact]*10+g[d.effort];return h-b});for(let l=0;l<a.length;l++){let d=a[l],m=e.rules.find(g=>g.id===d.ruleId);i.push({id:v(),description:`Implement ${m?.title||d.ruleId}`,affectedRules:[d.ruleId],effort:d.effort,priority:l+1})}let o=100,c=t.complianceScore;return f({currentScore:c,targetScore:o,gaps:r,prioritizedActions:i})}catch(r){return p(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 c=`${o.location.file}:${o.location.line}`;n.set(c,(n.get(c)||0)+1)}for(let a of r)for(let o of a.violations){let c=`${o.location.file}:${o.location.line}`;(n.get(c)||0)>1&&(i.some(l=>l.location.file===o.location.file&&l.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 p(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 c=r.get(o.type)||[];c.push(o.location),r.set(o.type,c);let l=this.checkDataTypeViolation(o);l&&i.push(l)}}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 p(y(r))}}async generateEvidence(t,e){try{let r=this.standards.get(t);if(!r)return p(new Error(`Unknown standard: ${t}`));let i=await this.validate(r,e);if(!i.success)return p(i.error);let n=i.value,s=[];for(let o of r.rules){let c=n.passedRules.includes(o.id)?"implemented":n.skippedRules.includes(o.id)?"partial":"not-implemented";s.push({controlId:o.id,status:c,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 p(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},c=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: ${c}`,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 $y={stateSize:10,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0},ua=class extends ae{qNetwork;targetNetwork;replayBufferClass;dqnConfig;updateCount=0;actions=[];constructor(t={}){super("dqn","value-based"),this.dqnConfig={...$y,...t},this.initializeActions(),this.qNetwork=new q({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new Ke(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),c;if(this.dqnConfig.doubleDQN&&!i.done){let d=this.qNetwork.forward(s),m=this.argmax(d),g=this.targetNetwork.forward(s);c=i.reward+this.config.discountFactor*g[m]}else{let d=this.targetNetwork.forward(s);c=i.reward+this.config.discountFactor*Math.max(...d)*(i.done?0:1)}let l=new Float32Array(o.length);for(let d=0;d<l.length;d++)l[d]=d===a?c:o[d];r+=Math.abs(this.qNetwork.train(n,l,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 q({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new B]),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 q({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var Oy={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},te=R.create("security-compliance"),ji=class extends Q{constructor(e,r,i,n={}){let s={...Oy,...n};super(e,"security-compliance",s,{verifyFindingTypes:["security-vulnerability","compliance-violation","credential-exposure"],...s.consensusMixinConfig});this.memory=r;this.agentCoordinator=i;this.securityGovernanceMixin=iu(this.domainName),this.securityScanner=new $e(r),this.securityAuditor=new Bt(r),this.complianceValidator=new qt(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 ua({stateSize:8,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0})),this.config.enableFlashAttention){let e="test-similarity";this.flashAttention=await Ie(e,{dim:384,strategy:"flash",numHeads:8})}if(this.config.enableConsensus){let r=kt(!0).getAll();r.length>0?(this.consensusEngine=ui({strategy:"weighted",models:r,engineConfig:{minModels:Math.min(2,r.length),defaultModelTimeout:6e4,...this.config.consensusEngineConfig}}),te.info(`Multi-Model Consensus initialized with ${r.length} providers`)):te.warn("No model providers available for consensus verification")}this.rlInitialized=!0}catch(e){throw te.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=v();try{if(this.startWorkflow(r,"audit"),this.detectAuthCodeInScope(e)&&this.securityGovernanceMixin.isGovernanceEnabled()&&!(await this.securityGovernanceMixin.validateSecurityScanRequired(r,!0,void 0)).allowed&&this.securityGovernanceMixin.isStrictMode()&&te.info("Security audit for auth code registered with governance"),this.minCutMixin.shouldPauseOperations())return te.warn("Security audit paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Security audit paused: topology is in critical state"));if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&te.warn("Topology degraded, using conservative audit strategy"),!this.agentCoordinator.canSpawn())return p(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),p(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 c=this.extractVulnerabilitiesFromReport(o.value);this.config.enableFlashAttention&&this.flashAttention&&c.length>0&&await this.enhanceVulnerabilityAnalysis(c),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=v();try{if(this.startWorkflow(i,"scan"),this.minCutMixin.shouldPauseOperations())return te.warn("Security scan paused: topology is in critical state"),this.failWorkflow(i,"Topology is in critical state"),p(new Error("Security scan paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&te.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=v();try{if(this.startWorkflow(i,"compliance"),this.minCutMixin.shouldPauseOperations())return te.warn("Compliance validation paused: topology is in critical state"),this.failWorkflow(i,"Topology is in critical state"),p(new Error("Compliance validation paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&te.warn("Topology degraded, proceeding with compliance validation");let s=(await this.complianceValidator.getAvailableStandards()).find(o=>o.id===e);if(!s)return p(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=v();try{if(this.startWorkflow(e,"posture"),this.minCutMixin.shouldPauseOperations())return te.warn("Security posture assessment paused: topology is in critical state"),this.failWorkflow(e,"Topology is in critical state"),p(new Error("Security posture assessment paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&te.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 te.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),te.info(`Trained security audit with reward: ${a.toFixed(3)}`)}catch(i){te.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(l=>this.createVulnerabilityEmbedding(l)),i=r.length,n=r[0].length,s=new Float32Array(i*n),a=new Float32Array(i*n),o=new Float32Array(i*n);for(let l=0;l<i;l++)s.set(r[l],l*n),a.set(r[l],l*n),o.set(r[l],l*n);let c=await this.flashAttention.computeFlashAttention(s,a,o,i,n);for(let l=0;l<e.length;l++){let d=Array.from(c.slice(l*n,(l+1)*n));r[l].reduce((g,h,b)=>g+h*d[b],0)>.7&&te.info(`High self-attention for vulnerability ${e[l].id}`)}}catch(r){te.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 c=r.length;c<384;c++)r.push(o*(c+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=D(Ma.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=V({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 c=await this.consensusMixin.verifyFinding(o);c.success&&c.value.verdict==="verified"?(te.info(`Consensus VERIFIED: ${a.title} (confidence: ${(c.value.confidence*100).toFixed(1)}%)`),r.push(a)):c.success&&c.value.verdict==="disputed"?(te.info(`Consensus DISPUTED: ${a.title} - including with lower confidence`),r.push(a)):te.info(`Consensus REJECTED: ${a.title} - likely false positive`)}catch{te.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&&te.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=D(Ma.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()}};A();var da=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;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),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 p(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}):p(new Error("Invalid security-audit payload: missing target"))}],["compliance-check",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.standardId;return r?this.coordinator.runComplianceCheck(r):p(new Error("Invalid compliance-check payload: missing standardId"))}],["sast-scan",async e=>{if(!this.securityScanner)return p(new Error("Security scanner not initialized"));let r=e.files;return!r||r.length===0?p(new Error("Invalid sast-scan payload: missing files")):this.securityScanner.scanFiles(r)}],["dast-scan",async e=>{if(!this.securityScanner)return p(new Error("Security scanner not initialized"));let r=e.targetUrl;return r?this.securityScanner.scanUrl(r):p(new Error("Invalid dast-scan payload: missing targetUrl"))}],["triage-vulnerabilities",async e=>{if(!this.securityAuditor)return p(new Error("Security auditor not initialized"));let r=e.vulnerabilities;return!r||r.length===0?p(new Error("Invalid triage-vulnerabilities payload: missing vulnerabilities")):this.securityAuditor.triageVulnerabilities(r)}]])}async onInitialize(){this.securityScanner=new $e(this.memory,this.pluginConfig.securityScanner),this.securityAuditor=new Bt(this.memory,this.pluginConfig.securityAuditor),this.complianceValidator=new qt(this.memory,this.pluginConfig.complianceValidator),this.coordinator=new ji(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,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 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 Uc(u,t,e,r){return new da(u,t,e,r)}M();A();M();A();H();var Ny={strictMode:!0,validateExamples:!0,maxSchemaDepth:Nn.MAX_SCHEMA_DEPTH,cacheValidations:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:Vn.MAX_TOKENS},Vy=R.create("contract-testing/contract-validator"),Tr=class{config;memory;llmRouter;validationCache=new Map;MAX_CACHED_VALIDATIONS=Nn.MAX_CACHED_VALIDATIONS;CACHE_TTL_MS=Nn.CACHE_TTL_MS;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...Ny,...e}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}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:
2924
2925
  Provider: ${t.provider.name}
@@ -2996,7 +2997,7 @@ Provide:
2996
2997
  inapplicable: results.inapplicable.map(i => i.id)
2997
2998
  });
2998
2999
  })();
2999
- `,s=await u.evaluate(n);if(!s.success)return p(new Error(`Failed to run axe-core: ${s.error?.message??"Unknown error"}`));try{let a=E(s.value);return f(a)}catch(a){return p(new Error(`Failed to parse axe-core results: ${a}`))}}function ev(u,t){let e=[];for(let r of u){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=Er[n];s?e.push(s):e.push({id:n,level:t,title:`WCAG ${n}`})}}return e}function tv(u,t,e){let r=t.violations.map(l=>({id:l.id,impact:dm(l.impact??"moderate"),wcagCriteria:ev(l.tags??[],e),description:l.description,help:l.help,helpUrl:l.helpUrl??`https://dequeuniversity.com/rules/axe/4.8/${l.id}`,nodes:l.nodes.map(d=>({selector:d.selector,html:d.html,target:d.target,failureSummary:d.failureSummary??""}))})),i=t.passes.map(l=>({id:l,description:`Rule ${l} passed`,nodes:0})),n=t.incomplete.map(l=>({id:l,description:`Rule ${l} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),s=r.length+i.length+n.length,a=r.reduce((l,d)=>l+{critical:4,serious:3,moderate:2,minor:1}[d.impact],0),o=s*4,c=s>0?Math.round((o-a)/o*100):100;return{url:u,timestamp:new Date,violations:r,passes:i,incomplete:n,score:Math.max(0,Math.min(100,c)),wcagLevel:e}}function mm(u,t,e){let r=t.violations.map(l=>({id:l.id,impact:dm(l.impact),wcagCriteria:l.wcagCriterion?[{id:l.wcagCriterion,level:e,title:l.rule}]:[],description:l.description,help:l.help,helpUrl:l.helpUrl??"https://www.w3.org/WAI/WCAG22/Understanding/",nodes:l.nodes.map(d=>({selector:d.selector,html:d.html,target:d.target,failureSummary:d.failureSummary}))})),i=t.passedRules.map(l=>({id:l,description:`Rule ${l} passed`,nodes:0})),n=t.incompleteRules.map(l=>({id:l,description:`Rule ${l} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),s=r.length+i.length+n.length,a=r.reduce((l,d)=>l+{critical:4,serious:3,moderate:2,minor:1}[d.impact],0),o=s*4,c=s>0?Math.round((o-a)/o*100):100;return{url:u,timestamp:new Date,violations:r,passes:i,incomplete:n,score:Math.max(0,Math.min(100,c)),wcagLevel:e}}function rv(u,t){let e=[];for(let r of u.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&&u.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 pm(u,t,e,r,i){try{let n=await u.launch({headless:r.headless});if(!n.success)return p(new Error(`Failed to launch browser: ${n.error?.message??"Unknown error"}`));try{let s=await u.navigate(t);if(!s.success)return p(new Error(`Failed to navigate to ${t}: ${s.error?.message??"Unknown error"}`));if(Yy(u)){let c=await u.getSnapshot({interactive:!0});if(c.success){let l=c.value.interactiveElements.length;Jy.debug(`Found ${l} interactive elements`)}}let a=await Zy(u,e,i);if(!a.success)return p(a.error);let o=tv(t,a.value,e);return f(o)}finally{await u.quit()}}catch(n){return p(y(n))}}async function gm(u,t,e,r,i){try{let n=await u.launch({headless:r.headless});if(!n.success)return p(new Error(`Failed to launch browser: ${ce(n)}`));try{let s=await u.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!s.success)return p(new Error(`Failed to navigate to ${t}: ${ce(s)}`));let a=await u.checkAccessibility({wcagLevel:e,selector:i?.excludeSelectors?.[0]});if(!a.success)return p(new Error(`Accessibility check failed: ${ce(a)}`));let o=mm(t,a.value,e);return f(o)}finally{await u.quit()}}catch(n){return p(y(n))}}async function hm(u,t,e,r,i){try{let n=await u.launch({headless:i.headless});if(!n.success)return p(new Error(`Failed to launch browser: ${ce(n)}`));try{let s=await u.navigate({url:t,waitUntil:"networkidle",timeout:i.timeout});if(!s.success)return p(new Error(`Failed to navigate to ${t}: ${ce(s)}`));let a=await u.checkAccessibility({wcagLevel:r,selector:e});if(!a.success)return p(new Error(`Element accessibility check failed: ${ce(a)}`));let o=mm(t,a.value,r);return f(o)}finally{await u.quit()}}catch(n){return p(y(n))}}async function fm(u,t,e,r){try{let i=await u.launch({headless:r.headless});if(!i.success)return p(new Error(`Failed to launch browser: ${ce(i)}`));try{let n=await u.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!n.success)return p(new Error(`Failed to navigate to ${t}: ${ce(n)}`));let s=await u.checkAccessibility({wcagLevel:e,rules:{include:["color-contrast"]}});if(!s.success)return p(new Error(`Contrast check failed: ${ce(s)}`));let a=rv(s.value,e);return f(a)}finally{await u.quit()}}catch(i){return p(y(i))}}async function ym(u,t,e,r){try{let i=await u.launch({headless:r.headless});if(!i.success)return p(new Error(`Failed to launch browser: ${ce(i)}`));try{let n=await u.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!n.success)return p(new Error(`Failed to navigate to ${t}: ${ce(n)}`));let a=await u.findElements({selector:'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])',visible:!0});if(!a.success)return p(new Error(`Failed to find focusable elements: ${ce(a)}`));let o=a.value.map((g,h)=>({index:h,selector:g.selector,elementType:iv(g.tagName),hasVisibleFocus:!0})),c=await u.checkAccessibility({wcagLevel:e,rules:{include:["keyboard","focus-order","focus-trap","bypass-blocks"]}}),l=[],d=[];if(c.success){for(let g of c.value.violations)if(g.rule.includes("focus")||g.rule.includes("keyboard"))for(let h of g.nodes)g.rule.includes("trap")?d.push({selector:h.selector,description:h.failureSummary,escapePath:"Ensure Escape key or Tab can exit this element"}):l.push({type:nv(g.rule),selector:h.selector,description:h.failureSummary})}let m={url:t,focusableElements:o.length,tabOrder:o,issues:l,traps:d};return f(m)}finally{await u.quit()}}catch(i){return p(y(i))}}function iv(u){return{a:"link",button:"button",input:"input",select:"input",textarea:"input"}[u.toLowerCase()]||"other"}function nv(u){return u.includes("focus-indicator")||u.includes("visible")?"no-focus-indicator":u.includes("skip")||u.includes("bypass")?"skip-link-missing":u.includes("order")||u.includes("sequence")?"incorrect-tab-order":"non-interactive-focusable"}function bm(){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 Jc(u,t){let e={A:1,AA:2,AAA:3},r=e[t];return u.filter(i=>i.wcagCriteria.some(n=>{let s=Er[n];return s&&e[s.level]<=r}))}function wm(u,t,e,r){if(e){let s=Rv(u,t),a=vm(u,t);return{nodes:s,passed:s.length===0,checkedNodes:a}}let i=sv(u,t,r),n=vm(u,t);return{nodes:i,passed:i.length===0,checkedNodes:n}}function sv(u,t,e){let r=[],i=t.url.toLowerCase();switch(u.id){case"image-alt":av(i)&&r.push(...hv());break;case"button-name":ov(i)&&r.push(...fv());break;case"color-contrast":e&&r.push(...yv());break;case"html-lang":cv(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":lv(i)&&r.push(...vv());break;case"focus-visible":uv(i)&&r.push(...bv());break;case"bypass-blocks":dv(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":mv(i)&&r.push(...wv());break;case"keyboard-trap":pv(i)&&r.push(...Cv());break;case"focus-order":gv(i)&&r.push(...Sv());break}return r}function av(u){return u.includes("gallery")||u.includes("photo")||u.includes("image")||u.includes("product")||u.includes("portfolio")||u.includes("media")}function ov(u){return u.includes("app")||u.includes("dashboard")||u.includes("editor")||u.includes("tool")||u.includes("builder")||u.includes("widget")}function cv(u){return u.includes("cdn")||u.includes("static")||u.includes(".html")||u.includes("file://")}function lv(u){return u.includes("nav")||u.includes("menu")||u.includes("header")||u.includes("sidebar")||u.includes("footer")}function uv(u){return u.includes("app")||u.includes("dashboard")||u.includes("#/")||u.includes("react")||u.includes("angular")||u.includes("vue")}function dv(u){return u.includes("gov")||u.includes("edu")||u.includes("a11y")||u.includes("accessible")}function mv(u){return u.includes("form")||u.includes("contact")||u.includes("register")||u.includes("signup")||u.includes("login")||u.includes("checkout")||u.includes("submit")||u.includes("search")}function pv(u){return u.includes("modal")||u.includes("dialog")||u.includes("popup")||u.includes("overlay")||u.includes("lightbox")}function gv(u){return u.includes("dashboard")||u.includes("admin")||u.includes("grid")||u.includes("layout")||u.includes("multi")}function hv(){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 fv(){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 yv(){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 vv(){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 bv(){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 wv(){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 Cv(){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 Sv(){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 Rv(u,t){let e=[],r=ft(t.url),i=parseInt(r,36),n=u.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<u.simulationFailureRate){let c=Tv(u.id,a);e.push({selector:c,html:`<element class="${u.id}-element-${a}">Content</element>`,target:[c],failureSummary:"Element does not meet accessibility requirements",fixSuggestion:"Review and update the element to meet WCAG guidelines"})}return e}function Tv(u,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"]}[u]||["div"],i=r[t%r.length],n=["content","widget","component","item","element"],s=n[t%n.length];return`${i}.${s}`}function vm(u,t){let e=u.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 Cm(u,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}[u.id]??.1,i=u.id.charCodeAt(0)*100,s=(t+i)%100/100>=r;return{passed:s,reason:s?void 0:`Criterion ${u.id} (${u.title}) not fully satisfied`}}function Yc(u){let t=["h1","p","a","button",".card-text",".nav-link"],e=[],r=ft(u),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,l=s==="h1"||s==="button"?3:4.5,d=o>=l,m=20+(i+n*50)%30,g=200+(i+n*30)%55,h=m.toString(16).padStart(2,"0"),b=g.toString(16).padStart(2,"0");e.push({element:s,foreground:`#${h}${h}${h}`,background:`#${b}${b}${b}`,ratio:o,requiredRatio:l,passes:d,wcagLevel:"AA"})}return e}function Xc(u){let t=ft(u),e=Av(u,t),r=Ev(e),i=xv(u,t);return{url:u,focusableElements:e.length,tabOrder:e,issues:r,traps:i}}function Av(u,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 Ev(u){let t=[];for(let r of u)r.hasVisibleFocus||t.push({type:"no-focus-indicator",selector:r.selector,description:`Element ${r.selector} does not have a visible focus indicator`});return u.some(r=>r.selector.includes("skip"))||t.push({type:"skip-link-missing",selector:"body",description:"Page is missing a skip navigation link"}),u.every((r,i)=>{if(i===0)return!0;let n=r.selector.includes("nav")||r.selector.includes("header"),s=u[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 xv(u,t){let e=[],r=parseInt(t,36),i=u.includes("modal")||u.includes("dialog")||u.includes("popup"),n=u.includes("form")||u.includes("checkout")||u.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 ft(u){let t=0;for(let e=0;e<u.length;e++){let r=u.charCodeAt(e);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(36)}var Pv={defaultWCAGLevel:"AA",includeWarnings:!0,auditTimeout:3e4,enableColorContrastCheck:!0,enableKeyboardCheck:!0,simulationMode:!1,useBrowserMode:!0,browserConfig:{headless:!0,timeout:3e4},browserClient:void 0,preferAgentBrowser:!0},xr=R.create("visual-accessibility/accessibility-tester"),Pr=class{constructor(t,e={},r){this.memory=t;this.config={...Pv,...e},this.rules=bm(),this.vibiumClient=r??null,this.browserClient=e.browserClient??null,this.euComplianceService=new va(t)}memory;config;rules;vibiumClient;browserClient;managedBrowserClient=null;euComplianceService;shouldUseBrowserMode(){return this.config.useBrowserMode?this.browserClient||this.config.preferAgentBrowser?!0:!(!sn()||!an()||!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 ns("accessibility");if(await t.isAvailable())return this.managedBrowserClient=t,t}catch{xr.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 pm(i,t,r,this.config.browserConfig,e);if(n.success)return await this.storeReport(n.value),n;let s=ce(n);xr.warn(`Browser client audit failed: ${s}`)}if(this.vibiumClient&&sn()&&an()){let n=await gm(this.vibiumClient,t,r,this.config.browserConfig,e);if(n.success)return await this.storeReport(n.value),n;let s=ce(n);xr.warn(`Vibium audit failed, falling back to heuristic mode: ${s}`)}}return this.auditWithHeuristics(t,r,e)}catch(r){return p(y(r))}}async auditElement(t,e){if(this.shouldUseBrowserMode()&&this.vibiumClient){let r=await hm(this.vibiumClient,t,e,this.config.defaultWCAGLevel,this.config.browserConfig);if(r.success)return await this.storeReport(r.value),r;let i=ce(r);xr.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?Jc(this.rules,e):Jc(this.rules,e).filter(g=>g.impact!=="minor"),s=[],a=[],o=[];for(let g of n){let h=wm(g,{url:t},this.config.simulationMode,this.config.enableColorContrastCheck);h.nodes.length>0?s.push({id:g.id,impact:g.impact,wcagCriteria:g.wcagCriteria.map(b=>Er[b]).filter(Boolean),description:g.description,help:`Fix ${g.description.toLowerCase()}`,helpUrl:`https://www.w3.org/WAI/WCAG22/Understanding/${g.wcagCriteria[0]}`,nodes:h.nodes}):h.passed?a.push({id:g.id,description:g.description,nodes:h.checkedNodes}):o.push({id:g.id,description:g.description,reason:"Could not determine compliance",nodes:h.nodes})}let c=n.length,l=s.length,d=Math.round((c-l)/c*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 p(y(i))}}async checkContrast(t){try{let e=`visual-accessibility:contrast:${ft(t)}`,r=await this.memory.get(e);if(r)return f(r);let i;if(this.shouldUseBrowserMode()&&this.vibiumClient){let n=await fm(this.vibiumClient,t,this.config.defaultWCAGLevel,this.config.browserConfig);if(n.success)i=n.value;else{let s=ce(n);xr.warn(`Browser mode contrast check failed, falling back to heuristic mode: ${s}`),i=Yc(t)}}else i=Yc(t);return await this.memory.set(e,i,{namespace:"visual-accessibility",ttl:3600}),f(i)}catch(e){return p(y(e))}}async validateWCAGLevel(t,e){try{let r={A:1,AA:2,AAA:3},i=r[e],n=Object.values(Er).filter(m=>r[m.level]<=i),s=[],a=[],o=ft(t),c=parseInt(o,36);for(let m of n)Cm(m,c).passed?a.push(m):s.push(m);let l=s.length===0,d=Math.round(a.length/n.length*100);return f({level:e,passed:l,failedCriteria:s,passedCriteria:a,score:d})}catch(r){return p(y(r))}}async checkKeyboardNavigation(t){try{let e=`visual-accessibility:keyboard:${ft(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 ym(this.vibiumClient,t,this.config.defaultWCAGLevel,this.config.browserConfig);if(n.success)i=n.value;else{let s=ce(n);xr.warn(`Browser mode keyboard check failed, falling back to heuristic mode: ${s}`),i=Xc(t)}}else i=Xc(t);return await this.memory.set(e,i,{namespace:"visual-accessibility",ttl:3600}),f(i)}catch(e){return p(y(e))}}async storeReport(t){let e=v();await this.memory.set(`visual-accessibility:report:${e}`,t,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:latest:${ft(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):p(new Error(`WCAG audit failed: ${r.error.message}`))}catch(r){return p(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)}};A();var ba={"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}},kv={viewports:[ba["iphone-14"],ba["ipad-mini"],ba.laptop,ba["desktop-hd"]],breakpoints:[320,480,768,1024,1280,1920],checkTouchTargets:!0,minFontSize:12,minTouchTargetSize:44,simulationMode:!1},kr=class{constructor(t,e={}){this.memory=t;this.config={...kv,...e}}memory;config;async testResponsiveness(t,e){try{let r={...this.config,...e},i=[],n=[];for(let l of r.viewports){let d=await this.testViewport(t,l,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),c={url:t,timestamp:new Date,viewports:i,breakpointIssues:s,layoutScore:a,recommendations:o};return await this.storeResult(c),f(c)}catch(r){return p(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 p(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 p(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 p(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,c=n.filter(l=>l.severity==="critical").length===0;return{viewport:e,screenshot:i,layoutIssues:n,renderTime:o,passed:c}}createScreenshot(t,e){let r=this.hashUrl(t),n=500+(parseInt(r,36)+e.width+e.height)%2e3;return{id:v(),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 c=(s+e.width+200)%100/100;r.checkTouchTargets&&e.isMobile&&c<.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 l=(s+e.width+300)%100/100;return e.isMobile&&l<.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,c)=>o.viewport.width-c.viewport.width);for(let o=0;o<a.length-1;o++){let c=a[o],l=a[o+1],d=r.breakpoints.find(m=>m>c.viewport.width&&m<l.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 c=0;c<n.length;c++){let l=n[c],d=(i+c*100+l)%100,m,g,h;if(s?(m=40,g=[".product-grid",".cart-items",".checkout-form",".filters"],h="Product grid layout adjusts for viewport"):a?(m=50,g=[".sidebar",".dashboard-cards",".data-table",".nav-menu"],h="Dashboard layout reorganizes for smaller screens"):o?(m=60,g=[".article-content",".sidebar-widgets",".comments"],h="Content width and sidebar visibility changes"):(m=55,g=[".container",".grid",".navigation",".footer"],h="Content layout changes significantly"),d<m){let b=Math.min(g.length,1+Math.floor((i+l)%g.length)),w=g.slice(0,b);e.push({width:l,reason:h,affectedElements:w})}}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=v();await this.memory.set(`visual-accessibility:responsive:${e}`,t,{namespace:"visual-accessibility",persist:!0})}};se();var Iv={stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4,nSteps:5,entropyCoeff:.01,valueLossCoeff:.5},wa=class extends ae{actor;critic;a2cConfig;actions=[];constructor(t={}){super("a2c","actor-critic"),this.a2cConfig={...Iv,...t},this.initializeActions(),this.actor=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.actor.forward(e),i=pe.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 c=0;c<s.length;c++){let l=s[c],d=this.prepareState(l.state),m=this.actionToIndex(l.action),g=o[c],h=this.actor.forward(d),b=pe.forward(h),C=-Math.log(b[m]+1e-10)*g,S=this.calculateEntropy(b),P=this.a2cConfig.entropyCoeff*S,k=new Float32Array(b.length);for(let Y=0;Y<k.length;Y++)Y===m?k[Y]=-g*(1-b[Y]):k[Y]=g*b[Y];this.actor.backward(k);for(let Y of this.actor.layers)Y.update(this.config.learningRate*.1);let O=this.critic.forward(d)[0],z=a[c],K=(O-z)**2,Ce=new Float32Array([z]);this.critic.train(d,Ce,new fe),r+=Math.abs(C-P),i+=K}}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 q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new B]),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(L()<this.config.explorationRate)return le(0,this.actions.length);let e=L(),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 q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate})}};var Dv={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},ke=R.create("visual-accessibility"),Ca=class extends Q{constructor(e,r,i,n={},s={},a={},o={}){let c={...Dv,...n};super(e,"visual-accessibility",c,{verifyFindingTypes:["accessibility-violation","visual-regression","wcag-non-compliance"]});this.memory=r;this.agentCoordinator=i;this.visualTester=fa(r,s),this.accessibilityTester=new Pr(r,a),this.responsiveTester=new kr(r,o)}memory;agentCoordinator;visualTester;accessibilityTester;responsiveTester;a2cAlgorithm;flashAttention;async onInitialize(){if(this.config.enableA2C)try{this.a2cAlgorithm=new wa({stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4}),ke.info("A2C algorithm created successfully")}catch(e){throw ke.error("Failed to create A2C:",e instanceof Error?e:void 0),new Error(`A2C creation failed: ${T(e)}`)}if(this.config.enableFlashAttention)try{this.flashAttention=await Ie("test-similarity"),ke.info("QEFlashAttention initialized successfully")}catch(e){throw ke.error("Failed to initialize Flash Attention:",e instanceof Error?e:void 0),new Error(`Flash Attention initialization failed: ${T(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=v();try{if(this.startWorkflow(i,"visual"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ke.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Operation paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(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),p(n.error);this.addAgentToWorkflow(i,n.value);let s=[],a=0,o=0,c=0,l=[];for(let w of e)for(let C of r)l.push({url:w,viewport:C});if(this.config.enableA2C&&l.length>1){let w={urgency:5,availableResources:80,historicalFailureRate:.1},C=await this.prioritizeVisualTests(l.map(S=>({...S,priority:5})),w);C.success&&(l=C.value.orderedTests.map(S=>({url:S.url,viewport:S.viewport})),ke.info(`[visual-accessibility] Using ${C.value.strategy} strategy for visual test order (confidence: ${C.value.confidence.toFixed(2)})`))}let d=l.length,m=0;for(let{url:w,viewport:C}of l){let S=await this.visualTester.captureScreenshot(w,{viewport:C});if(!S.success){o++,s.push({url:w,viewport:C,status:"failed",screenshot:{id:"",url:w,viewport:C,timestamp:new Date,path:he.create("error-placeholder.png"),metadata:{browser:"",os:"",fullPage:!1,loadTime:0}}});continue}let P=S.value,k=await this.visualTester.getBaseline(w,C);if(!k)await this.visualTester.setBaseline(P),c++,s.push({url:w,viewport:C,status:"new",screenshot:P});else{let O=await this.visualTester.compare(P,k.id);if(O.success){let z=O.value,K=z.status==="identical"||z.status==="acceptable"?"passed":"failed";K==="passed"?a++:o++,s.push({url:w,viewport:C,status:K,diff:z,screenshot:P}),K==="failed"&&this.config.publishEvents&&await this.publishVisualRegressionEvent(w,C,z)}else o++,s.push({url:w,viewport:C,status:"failed",screenshot:P})}m++,this.updateWorkflowProgress(i,m/d*100)}let g=this.workflows.get(i)?.startedAt.getTime()??Date.now(),h=Date.now()-g,b={totalTests:s.length,passed:a,failed:o,newBaselines:c,results:s,duration:h};return this.completeWorkflow(i),await this.agentCoordinator.stop(n.value),f(b)}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async runAccessibilityAudit(e,r){let i=v();try{if(this.startWorkflow(i,"accessibility"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ke.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(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),p(n.error);this.addAgentToWorkflow(i,n.value);let s=[],a=0,o=0,c=0;for(let g=0;g<e.length;g++){let h=e[g],b=await this.accessibilityTester.audit(h,{wcagLevel:r});if(b.success){let w=b.value;s.push(w),a+=w.violations.length,o+=w.violations.filter(C=>C.impact==="critical").length,w.violations.length===0&&c++,this.config.publishEvents&&await this.publishAccessibilityAuditEvent(w)}this.updateWorkflowProgress(i,(g+1)/e.length*100)}let l=s.length>0?Math.round(s.reduce((g,h)=>g+h.score,0)/s.length):0,d=this.identifyTopIssues(s),m={totalUrls:e.length,passingUrls:c,totalViolations:a,criticalViolations:o,averageScore:l,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 p(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 p(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 g of i){let h=await this.memory.get(g);h&&(h.status==="changed"||h.status==="failed")&&n++}let a=Array.from(this.workflows.values()).filter(g=>g.type==="visual"&&g.status==="completed").sort((g,h)=>(h.completedAt?.getTime()??0)-(g.completedAt?.getTime()??0))[0]?.completedAt??new Date,o=Array.from(this.workflows.values()).filter(g=>g.type==="visual").length,c=Array.from(this.workflows.values()).filter(g=>g.type==="visual"&&g.status==="failed").length,l=o>0?c/o:0,d=await this.calculateViewportCoverage(e);return f({baselineCount:r,pendingReviews:n,lastTestRun:a,failureRate:l,coverageByViewport:d})}catch(e){return p(y(e))}}async runVisualRegression(e){let r=v();try{if(this.startWorkflow(r,"visual"),!this.agentCoordinator.canSpawn())return this.failWorkflow(r,"Agent limit reached"),p(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),p(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 c of a){let l=await this.visualTester.captureScreenshot(`${e.baselineUrl}${o}`,{viewport:c}),d=await this.visualTester.captureScreenshot(`${e.compareUrl}${o}`,{viewport:c});if(l.success&&d.success){let m=await this.visualTester.compare(d.value,l.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 p(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 p(y(r))}}async analyzeColorContrast(e){try{let r=e.wcagLevel??"AA",i=await this.accessibilityTester.audit(e.url,{wcagLevel:r});if(!i.success)return p(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 p(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 p(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[,c,l]=o,d=parseInt(l,10);i.add(c);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 c=Math.min(100,Math.round(o/n*100));s.set(a,c)}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:v(),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:v(),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:v(),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>
3000
+ `,s=await u.evaluate(n);if(!s.success)return p(new Error(`Failed to run axe-core: ${s.error?.message??"Unknown error"}`));try{let a=E(s.value);return f(a)}catch(a){return p(new Error(`Failed to parse axe-core results: ${a}`))}}function ev(u,t){let e=[];for(let r of u){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=Er[n];s?e.push(s):e.push({id:n,level:t,title:`WCAG ${n}`})}}return e}function tv(u,t,e){let r=t.violations.map(l=>({id:l.id,impact:dm(l.impact??"moderate"),wcagCriteria:ev(l.tags??[],e),description:l.description,help:l.help,helpUrl:l.helpUrl??`https://dequeuniversity.com/rules/axe/4.8/${l.id}`,nodes:l.nodes.map(d=>({selector:d.selector,html:d.html,target:d.target,failureSummary:d.failureSummary??""}))})),i=t.passes.map(l=>({id:l,description:`Rule ${l} passed`,nodes:0})),n=t.incomplete.map(l=>({id:l,description:`Rule ${l} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),s=r.length+i.length+n.length,a=r.reduce((l,d)=>l+{critical:4,serious:3,moderate:2,minor:1}[d.impact],0),o=s*4,c=s>0?Math.round((o-a)/o*100):100;return{url:u,timestamp:new Date,violations:r,passes:i,incomplete:n,score:Math.max(0,Math.min(100,c)),wcagLevel:e}}function mm(u,t,e){let r=t.violations.map(l=>({id:l.id,impact:dm(l.impact),wcagCriteria:l.wcagCriterion?[{id:l.wcagCriterion,level:e,title:l.rule}]:[],description:l.description,help:l.help,helpUrl:l.helpUrl??"https://www.w3.org/WAI/WCAG22/Understanding/",nodes:l.nodes.map(d=>({selector:d.selector,html:d.html,target:d.target,failureSummary:d.failureSummary}))})),i=t.passedRules.map(l=>({id:l,description:`Rule ${l} passed`,nodes:0})),n=t.incompleteRules.map(l=>({id:l,description:`Rule ${l} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),s=r.length+i.length+n.length,a=r.reduce((l,d)=>l+{critical:4,serious:3,moderate:2,minor:1}[d.impact],0),o=s*4,c=s>0?Math.round((o-a)/o*100):100;return{url:u,timestamp:new Date,violations:r,passes:i,incomplete:n,score:Math.max(0,Math.min(100,c)),wcagLevel:e}}function rv(u,t){let e=[];for(let r of u.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&&u.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 pm(u,t,e,r,i){try{let n=await u.launch({headless:r.headless});if(!n.success)return p(new Error(`Failed to launch browser: ${n.error?.message??"Unknown error"}`));try{let s=await u.navigate(t);if(!s.success)return p(new Error(`Failed to navigate to ${t}: ${s.error?.message??"Unknown error"}`));if(Yy(u)){let c=await u.getSnapshot({interactive:!0});if(c.success){let l=c.value.interactiveElements.length;Jy.debug(`Found ${l} interactive elements`)}}let a=await Zy(u,e,i);if(!a.success)return p(a.error);let o=tv(t,a.value,e);return f(o)}finally{await u.quit()}}catch(n){return p(y(n))}}async function gm(u,t,e,r,i){try{let n=await u.launch({headless:r.headless});if(!n.success)return p(new Error(`Failed to launch browser: ${ce(n)}`));try{let s=await u.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!s.success)return p(new Error(`Failed to navigate to ${t}: ${ce(s)}`));let a=await u.checkAccessibility({wcagLevel:e,selector:i?.excludeSelectors?.[0]});if(!a.success)return p(new Error(`Accessibility check failed: ${ce(a)}`));let o=mm(t,a.value,e);return f(o)}finally{await u.quit()}}catch(n){return p(y(n))}}async function hm(u,t,e,r,i){try{let n=await u.launch({headless:i.headless});if(!n.success)return p(new Error(`Failed to launch browser: ${ce(n)}`));try{let s=await u.navigate({url:t,waitUntil:"networkidle",timeout:i.timeout});if(!s.success)return p(new Error(`Failed to navigate to ${t}: ${ce(s)}`));let a=await u.checkAccessibility({wcagLevel:r,selector:e});if(!a.success)return p(new Error(`Element accessibility check failed: ${ce(a)}`));let o=mm(t,a.value,r);return f(o)}finally{await u.quit()}}catch(n){return p(y(n))}}async function fm(u,t,e,r){try{let i=await u.launch({headless:r.headless});if(!i.success)return p(new Error(`Failed to launch browser: ${ce(i)}`));try{let n=await u.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!n.success)return p(new Error(`Failed to navigate to ${t}: ${ce(n)}`));let s=await u.checkAccessibility({wcagLevel:e,rules:{include:["color-contrast"]}});if(!s.success)return p(new Error(`Contrast check failed: ${ce(s)}`));let a=rv(s.value,e);return f(a)}finally{await u.quit()}}catch(i){return p(y(i))}}async function ym(u,t,e,r){try{let i=await u.launch({headless:r.headless});if(!i.success)return p(new Error(`Failed to launch browser: ${ce(i)}`));try{let n=await u.navigate({url:t,waitUntil:"networkidle",timeout:r.timeout});if(!n.success)return p(new Error(`Failed to navigate to ${t}: ${ce(n)}`));let a=await u.findElements({selector:'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])',visible:!0});if(!a.success)return p(new Error(`Failed to find focusable elements: ${ce(a)}`));let o=a.value.map((g,h)=>({index:h,selector:g.selector,elementType:iv(g.tagName),hasVisibleFocus:!0})),c=await u.checkAccessibility({wcagLevel:e,rules:{include:["keyboard","focus-order","focus-trap","bypass-blocks"]}}),l=[],d=[];if(c.success){for(let g of c.value.violations)if(g.rule.includes("focus")||g.rule.includes("keyboard"))for(let h of g.nodes)g.rule.includes("trap")?d.push({selector:h.selector,description:h.failureSummary,escapePath:"Ensure Escape key or Tab can exit this element"}):l.push({type:nv(g.rule),selector:h.selector,description:h.failureSummary})}let m={url:t,focusableElements:o.length,tabOrder:o,issues:l,traps:d};return f(m)}finally{await u.quit()}}catch(i){return p(y(i))}}function iv(u){return{a:"link",button:"button",input:"input",select:"input",textarea:"input"}[u.toLowerCase()]||"other"}function nv(u){return u.includes("focus-indicator")||u.includes("visible")?"no-focus-indicator":u.includes("skip")||u.includes("bypass")?"skip-link-missing":u.includes("order")||u.includes("sequence")?"incorrect-tab-order":"non-interactive-focusable"}function bm(){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 Jc(u,t){let e={A:1,AA:2,AAA:3},r=e[t];return u.filter(i=>i.wcagCriteria.some(n=>{let s=Er[n];return s&&e[s.level]<=r}))}function wm(u,t,e,r){if(e){let s=Rv(u,t),a=vm(u,t);return{nodes:s,passed:s.length===0,checkedNodes:a}}let i=sv(u,t,r),n=vm(u,t);return{nodes:i,passed:i.length===0,checkedNodes:n}}function sv(u,t,e){let r=[],i=t.url.toLowerCase();switch(u.id){case"image-alt":av(i)&&r.push(...hv());break;case"button-name":ov(i)&&r.push(...fv());break;case"color-contrast":e&&r.push(...yv());break;case"html-lang":cv(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":lv(i)&&r.push(...vv());break;case"focus-visible":uv(i)&&r.push(...bv());break;case"bypass-blocks":dv(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":mv(i)&&r.push(...wv());break;case"keyboard-trap":pv(i)&&r.push(...Cv());break;case"focus-order":gv(i)&&r.push(...Sv());break}return r}function av(u){return u.includes("gallery")||u.includes("photo")||u.includes("image")||u.includes("product")||u.includes("portfolio")||u.includes("media")}function ov(u){return u.includes("app")||u.includes("dashboard")||u.includes("editor")||u.includes("tool")||u.includes("builder")||u.includes("widget")}function cv(u){return u.includes("cdn")||u.includes("static")||u.includes(".html")||u.includes("file://")}function lv(u){return u.includes("nav")||u.includes("menu")||u.includes("header")||u.includes("sidebar")||u.includes("footer")}function uv(u){return u.includes("app")||u.includes("dashboard")||u.includes("#/")||u.includes("react")||u.includes("angular")||u.includes("vue")}function dv(u){return u.includes("gov")||u.includes("edu")||u.includes("a11y")||u.includes("accessible")}function mv(u){return u.includes("form")||u.includes("contact")||u.includes("register")||u.includes("signup")||u.includes("login")||u.includes("checkout")||u.includes("submit")||u.includes("search")}function pv(u){return u.includes("modal")||u.includes("dialog")||u.includes("popup")||u.includes("overlay")||u.includes("lightbox")}function gv(u){return u.includes("dashboard")||u.includes("admin")||u.includes("grid")||u.includes("layout")||u.includes("multi")}function hv(){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 fv(){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 yv(){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 vv(){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 bv(){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 wv(){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 Cv(){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 Sv(){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 Rv(u,t){let e=[],r=ft(t.url),i=parseInt(r,36),n=u.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<u.simulationFailureRate){let c=Tv(u.id,a);e.push({selector:c,html:`<element class="${u.id}-element-${a}">Content</element>`,target:[c],failureSummary:"Element does not meet accessibility requirements",fixSuggestion:"Review and update the element to meet WCAG guidelines"})}return e}function Tv(u,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"]}[u]||["div"],i=r[t%r.length],n=["content","widget","component","item","element"],s=n[t%n.length];return`${i}.${s}`}function vm(u,t){let e=u.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 Cm(u,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}[u.id]??.1,i=u.id.charCodeAt(0)*100,s=(t+i)%100/100>=r;return{passed:s,reason:s?void 0:`Criterion ${u.id} (${u.title}) not fully satisfied`}}function Yc(u){let t=["h1","p","a","button",".card-text",".nav-link"],e=[],r=ft(u),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,l=s==="h1"||s==="button"?3:4.5,d=o>=l,m=20+(i+n*50)%30,g=200+(i+n*30)%55,h=m.toString(16).padStart(2,"0"),b=g.toString(16).padStart(2,"0");e.push({element:s,foreground:`#${h}${h}${h}`,background:`#${b}${b}${b}`,ratio:o,requiredRatio:l,passes:d,wcagLevel:"AA"})}return e}function Xc(u){let t=ft(u),e=Av(u,t),r=Ev(e),i=xv(u,t);return{url:u,focusableElements:e.length,tabOrder:e,issues:r,traps:i}}function Av(u,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 Ev(u){let t=[];for(let r of u)r.hasVisibleFocus||t.push({type:"no-focus-indicator",selector:r.selector,description:`Element ${r.selector} does not have a visible focus indicator`});return u.some(r=>r.selector.includes("skip"))||t.push({type:"skip-link-missing",selector:"body",description:"Page is missing a skip navigation link"}),u.every((r,i)=>{if(i===0)return!0;let n=r.selector.includes("nav")||r.selector.includes("header"),s=u[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 xv(u,t){let e=[],r=parseInt(t,36),i=u.includes("modal")||u.includes("dialog")||u.includes("popup"),n=u.includes("form")||u.includes("checkout")||u.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 ft(u){let t=0;for(let e=0;e<u.length;e++){let r=u.charCodeAt(e);t=(t<<5)-t+r,t=t&t}return Math.abs(t).toString(36)}var Pv={defaultWCAGLevel:"AA",includeWarnings:!0,auditTimeout:3e4,enableColorContrastCheck:!0,enableKeyboardCheck:!0,simulationMode:!1,useBrowserMode:!0,browserConfig:{headless:!0,timeout:3e4},browserClient:void 0,preferAgentBrowser:!0},xr=R.create("visual-accessibility/accessibility-tester"),Pr=class{constructor(t,e={},r){this.memory=t;this.config={...Pv,...e},this.rules=bm(),this.vibiumClient=r??null,this.browserClient=e.browserClient??null,this.euComplianceService=new va(t)}memory;config;rules;vibiumClient;browserClient;managedBrowserClient=null;euComplianceService;shouldUseBrowserMode(){return this.config.useBrowserMode?this.browserClient||this.config.preferAgentBrowser?!0:!(!sn()||!an()||!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 ns("accessibility");if(await t.isAvailable())return this.managedBrowserClient=t,t}catch{xr.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 pm(i,t,r,this.config.browserConfig,e);if(n.success)return await this.storeReport(n.value),n;let s=ce(n);xr.warn(`Browser client audit failed: ${s}`)}if(this.vibiumClient&&sn()&&an()){let n=await gm(this.vibiumClient,t,r,this.config.browserConfig,e);if(n.success)return await this.storeReport(n.value),n;let s=ce(n);xr.warn(`Vibium audit failed, falling back to heuristic mode: ${s}`)}}return this.auditWithHeuristics(t,r,e)}catch(r){return p(y(r))}}async auditElement(t,e){if(this.shouldUseBrowserMode()&&this.vibiumClient){let r=await hm(this.vibiumClient,t,e,this.config.defaultWCAGLevel,this.config.browserConfig);if(r.success)return await this.storeReport(r.value),r;let i=ce(r);xr.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?Jc(this.rules,e):Jc(this.rules,e).filter(g=>g.impact!=="minor"),s=[],a=[],o=[];for(let g of n){let h=wm(g,{url:t},this.config.simulationMode,this.config.enableColorContrastCheck);h.nodes.length>0?s.push({id:g.id,impact:g.impact,wcagCriteria:g.wcagCriteria.map(b=>Er[b]).filter(Boolean),description:g.description,help:`Fix ${g.description.toLowerCase()}`,helpUrl:`https://www.w3.org/WAI/WCAG22/Understanding/${g.wcagCriteria[0]}`,nodes:h.nodes}):h.passed?a.push({id:g.id,description:g.description,nodes:h.checkedNodes}):o.push({id:g.id,description:g.description,reason:"Could not determine compliance",nodes:h.nodes})}let c=n.length,l=s.length,d=Math.round((c-l)/c*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 p(y(i))}}async checkContrast(t){try{let e=`visual-accessibility:contrast:${ft(t)}`,r=await this.memory.get(e);if(r)return f(r);let i;if(this.shouldUseBrowserMode()&&this.vibiumClient){let n=await fm(this.vibiumClient,t,this.config.defaultWCAGLevel,this.config.browserConfig);if(n.success)i=n.value;else{let s=ce(n);xr.warn(`Browser mode contrast check failed, falling back to heuristic mode: ${s}`),i=Yc(t)}}else i=Yc(t);return await this.memory.set(e,i,{namespace:"visual-accessibility",ttl:3600}),f(i)}catch(e){return p(y(e))}}async validateWCAGLevel(t,e){try{let r={A:1,AA:2,AAA:3},i=r[e],n=Object.values(Er).filter(m=>r[m.level]<=i),s=[],a=[],o=ft(t),c=parseInt(o,36);for(let m of n)Cm(m,c).passed?a.push(m):s.push(m);let l=s.length===0,d=Math.round(a.length/n.length*100);return f({level:e,passed:l,failedCriteria:s,passedCriteria:a,score:d})}catch(r){return p(y(r))}}async checkKeyboardNavigation(t){try{let e=`visual-accessibility:keyboard:${ft(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 ym(this.vibiumClient,t,this.config.defaultWCAGLevel,this.config.browserConfig);if(n.success)i=n.value;else{let s=ce(n);xr.warn(`Browser mode keyboard check failed, falling back to heuristic mode: ${s}`),i=Xc(t)}}else i=Xc(t);return await this.memory.set(e,i,{namespace:"visual-accessibility",ttl:3600}),f(i)}catch(e){return p(y(e))}}async storeReport(t){let e=v();await this.memory.set(`visual-accessibility:report:${e}`,t,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:latest:${ft(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):p(new Error(`WCAG audit failed: ${r.error.message}`))}catch(r){return p(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)}};A();var ba={"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}},kv={viewports:[ba["iphone-14"],ba["ipad-mini"],ba.laptop,ba["desktop-hd"]],breakpoints:[320,480,768,1024,1280,1920],checkTouchTargets:!0,minFontSize:12,minTouchTargetSize:44,simulationMode:!1},kr=class{constructor(t,e={}){this.memory=t;this.config={...kv,...e}}memory;config;async testResponsiveness(t,e){try{let r={...this.config,...e},i=[],n=[];for(let l of r.viewports){let d=await this.testViewport(t,l,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),c={url:t,timestamp:new Date,viewports:i,breakpointIssues:s,layoutScore:a,recommendations:o};return await this.storeResult(c),f(c)}catch(r){return p(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 p(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 p(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 p(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,c=n.filter(l=>l.severity==="critical").length===0;return{viewport:e,screenshot:i,layoutIssues:n,renderTime:o,passed:c}}createScreenshot(t,e){let r=this.hashUrl(t),n=500+(parseInt(r,36)+e.width+e.height)%2e3;return{id:v(),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 c=(s+e.width+200)%100/100;r.checkTouchTargets&&e.isMobile&&c<.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 l=(s+e.width+300)%100/100;return e.isMobile&&l<.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,c)=>o.viewport.width-c.viewport.width);for(let o=0;o<a.length-1;o++){let c=a[o],l=a[o+1],d=r.breakpoints.find(m=>m>c.viewport.width&&m<l.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 c=0;c<n.length;c++){let l=n[c],d=(i+c*100+l)%100,m,g,h;if(s?(m=40,g=[".product-grid",".cart-items",".checkout-form",".filters"],h="Product grid layout adjusts for viewport"):a?(m=50,g=[".sidebar",".dashboard-cards",".data-table",".nav-menu"],h="Dashboard layout reorganizes for smaller screens"):o?(m=60,g=[".article-content",".sidebar-widgets",".comments"],h="Content width and sidebar visibility changes"):(m=55,g=[".container",".grid",".navigation",".footer"],h="Content layout changes significantly"),d<m){let b=Math.min(g.length,1+Math.floor((i+l)%g.length)),w=g.slice(0,b);e.push({width:l,reason:h,affectedElements:w})}}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=v();await this.memory.set(`visual-accessibility:responsive:${e}`,t,{namespace:"visual-accessibility",persist:!0})}};se();var Iv={stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4,nSteps:5,entropyCoeff:.01,valueLossCoeff:.5},wa=class extends ae{actor;critic;a2cConfig;actions=[];constructor(t={}){super("a2c","actor-critic"),this.a2cConfig={...Iv,...t},this.initializeActions(),this.actor=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.actor.forward(e),i=pe.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 c=0;c<s.length;c++){let l=s[c],d=this.prepareState(l.state),m=this.actionToIndex(l.action),g=o[c],h=this.actor.forward(d),b=pe.forward(h),C=-Math.log(b[m]+1e-10)*g,S=this.calculateEntropy(b),k=this.a2cConfig.entropyCoeff*S,P=new Float32Array(b.length);for(let Y=0;Y<P.length;Y++)Y===m?P[Y]=-g*(1-b[Y]):P[Y]=g*b[Y];this.actor.backward(P);for(let Y of this.actor.layers)Y.update(this.config.learningRate*.1);let O=this.critic.forward(d)[0],z=a[c],K=(O-z)**2,Ce=new Float32Array([z]);this.critic.train(d,Ce,new fe),r+=Math.abs(C-k),i+=K}}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 q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new B]),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(L()<this.config.explorationRate)return le(0,this.actions.length);let e=L(),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 q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.critic=new q({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate})}};var Dv={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},ke=R.create("visual-accessibility"),Ca=class extends Q{constructor(e,r,i,n={},s={},a={},o={}){let c={...Dv,...n};super(e,"visual-accessibility",c,{verifyFindingTypes:["accessibility-violation","visual-regression","wcag-non-compliance"]});this.memory=r;this.agentCoordinator=i;this.visualTester=fa(r,s),this.accessibilityTester=new Pr(r,a),this.responsiveTester=new kr(r,o)}memory;agentCoordinator;visualTester;accessibilityTester;responsiveTester;a2cAlgorithm;flashAttention;async onInitialize(){if(this.config.enableA2C)try{this.a2cAlgorithm=new wa({stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4}),ke.info("A2C algorithm created successfully")}catch(e){throw ke.error("Failed to create A2C:",e instanceof Error?e:void 0),new Error(`A2C creation failed: ${T(e)}`)}if(this.config.enableFlashAttention)try{this.flashAttention=await Ie("test-similarity"),ke.info("QEFlashAttention initialized successfully")}catch(e){throw ke.error("Failed to initialize Flash Attention:",e instanceof Error?e:void 0),new Error(`Flash Attention initialization failed: ${T(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=v();try{if(this.startWorkflow(i,"visual"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ke.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Operation paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(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),p(n.error);this.addAgentToWorkflow(i,n.value);let s=[],a=0,o=0,c=0,l=[];for(let w of e)for(let C of r)l.push({url:w,viewport:C});if(this.config.enableA2C&&l.length>1){let w={urgency:5,availableResources:80,historicalFailureRate:.1},C=await this.prioritizeVisualTests(l.map(S=>({...S,priority:5})),w);C.success&&(l=C.value.orderedTests.map(S=>({url:S.url,viewport:S.viewport})),ke.info(`[visual-accessibility] Using ${C.value.strategy} strategy for visual test order (confidence: ${C.value.confidence.toFixed(2)})`))}let d=l.length,m=0;for(let{url:w,viewport:C}of l){let S=await this.visualTester.captureScreenshot(w,{viewport:C});if(!S.success){o++,s.push({url:w,viewport:C,status:"failed",screenshot:{id:"",url:w,viewport:C,timestamp:new Date,path:he.create("error-placeholder.png"),metadata:{browser:"",os:"",fullPage:!1,loadTime:0}}});continue}let k=S.value,P=await this.visualTester.getBaseline(w,C);if(!P)await this.visualTester.setBaseline(k),c++,s.push({url:w,viewport:C,status:"new",screenshot:k});else{let O=await this.visualTester.compare(k,P.id);if(O.success){let z=O.value,K=z.status==="identical"||z.status==="acceptable"?"passed":"failed";K==="passed"?a++:o++,s.push({url:w,viewport:C,status:K,diff:z,screenshot:k}),K==="failed"&&this.config.publishEvents&&await this.publishVisualRegressionEvent(w,C,z)}else o++,s.push({url:w,viewport:C,status:"failed",screenshot:k})}m++,this.updateWorkflowProgress(i,m/d*100)}let g=this.workflows.get(i)?.startedAt.getTime()??Date.now(),h=Date.now()-g,b={totalTests:s.length,passed:a,failed:o,newBaselines:c,results:s,duration:h};return this.completeWorkflow(i),await this.agentCoordinator.stop(n.value),f(b)}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async runAccessibilityAudit(e,r){let i=v();try{if(this.startWorkflow(i,"accessibility"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ke.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(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),p(n.error);this.addAgentToWorkflow(i,n.value);let s=[],a=0,o=0,c=0;for(let g=0;g<e.length;g++){let h=e[g],b=await this.accessibilityTester.audit(h,{wcagLevel:r});if(b.success){let w=b.value;s.push(w),a+=w.violations.length,o+=w.violations.filter(C=>C.impact==="critical").length,w.violations.length===0&&c++,this.config.publishEvents&&await this.publishAccessibilityAuditEvent(w)}this.updateWorkflowProgress(i,(g+1)/e.length*100)}let l=s.length>0?Math.round(s.reduce((g,h)=>g+h.score,0)/s.length):0,d=this.identifyTopIssues(s),m={totalUrls:e.length,passingUrls:c,totalViolations:a,criticalViolations:o,averageScore:l,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 p(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 p(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 g of i){let h=await this.memory.get(g);h&&(h.status==="changed"||h.status==="failed")&&n++}let a=Array.from(this.workflows.values()).filter(g=>g.type==="visual"&&g.status==="completed").sort((g,h)=>(h.completedAt?.getTime()??0)-(g.completedAt?.getTime()??0))[0]?.completedAt??new Date,o=Array.from(this.workflows.values()).filter(g=>g.type==="visual").length,c=Array.from(this.workflows.values()).filter(g=>g.type==="visual"&&g.status==="failed").length,l=o>0?c/o:0,d=await this.calculateViewportCoverage(e);return f({baselineCount:r,pendingReviews:n,lastTestRun:a,failureRate:l,coverageByViewport:d})}catch(e){return p(y(e))}}async runVisualRegression(e){let r=v();try{if(this.startWorkflow(r,"visual"),!this.agentCoordinator.canSpawn())return this.failWorkflow(r,"Agent limit reached"),p(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),p(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 c of a){let l=await this.visualTester.captureScreenshot(`${e.baselineUrl}${o}`,{viewport:c}),d=await this.visualTester.captureScreenshot(`${e.compareUrl}${o}`,{viewport:c});if(l.success&&d.success){let m=await this.visualTester.compare(d.value,l.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 p(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 p(y(r))}}async analyzeColorContrast(e){try{let r=e.wcagLevel??"AA",i=await this.accessibilityTester.audit(e.url,{wcagLevel:r});if(!i.success)return p(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 p(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 p(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[,c,l]=o,d=parseInt(l,10);i.add(c);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 c=Math.min(100,Math.round(o/n*100));s.set(a,c)}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:v(),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:v(),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:v(),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>
3000
3001
  <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(l=>l.viewport.width<=480).length/Math.max(1,e.length),e.filter(l=>l.viewport.width>1024).length/Math.max(1,e.length),e.filter(l=>(l.priority??5)>7).length/Math.max(1,e.length),e.filter(l=>l.url.includes("dashboard")).length/Math.max(1,e.length),e.filter(l=>l.url.includes("checkout")).length/Math.max(1,e.length),e.filter(l=>l.url.includes("login")).length/Math.max(1,e.length)]},n=await this.a2cAlgorithm.predict(i),s=e.map(l=>({...l,priority:l.priority??5,reason:"default"})),a="default";switch(n.action.type){case"coordinate":if(n.action.value==="parallel")s.sort((g,h)=>g.viewport.width-h.viewport.width),s=s.map(g=>({...g,priority:10-Math.floor(g.viewport.width/200),reason:"parallel-viewport-order"})),a="parallel-viewport-order";else if(n.action.value==="sequential"){let g=["checkout","payment","login"];s.sort((h,b)=>{let w=g.some(S=>h.url.includes(S))?1:0;return(g.some(S=>b.url.includes(S))?1:0)-w}),s=s.map(h=>({...h,priority:g.some(b=>h.url.includes(b))?9:5,reason:"sequential-critical-url"})),a="sequential-critical-url"}break;case"allocate":let l=typeof n.action.value=="object"?n.action.value.agents??2:2,d=Math.ceil(s.length/l);s=s.map((g,h)=>({...g,priority:10-Math.floor(h/d),reason:`allocate-agent-${Math.floor(h/d)}`})),a="allocate-by-agent";break;case"rebalance":let m=new Map;for(let g of s)m.set(g.viewport.width,(m.get(g.viewport.width)||0)+1);s.sort((g,h)=>(m.get(g.viewport.width)||0)-(m.get(h.viewport.width)||0)),s=s.map(g=>({...g,priority:10-(m.get(g.viewport.width)||0),reason:"rebalance-viewport-coverage"})),a="rebalance-viewport-coverage";break;default:break}let o=await this.calculatePrioritizationReward(s,r),c=n.action;return await this.a2cAlgorithm.train({state:i,action:c,reward:o,nextState:i,done:!0}),ke.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 ke.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(c=>o.url.includes(c))).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 ke.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=(et(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}),ke.info(`Stored visual pattern for ${e} at ${r.width}x${r.height}`)}catch(s){ke.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 l=0;l<100;l++)s.push((a>>l%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 c=this.extractPathFeatures(e);return s.push(...c.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=V({id:v(),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=V({id:v(),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)}};A();var Zc=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;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 p(new Error("Coordinator not initialized"));let r=e.urls,i=e.viewports;return!r||r.length===0?p(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 p(new Error("Coordinator not initialized"));let r=e.urls,i=e.level||"AA";return!r||r.length===0?p(new Error("Invalid run-accessibility-audit payload: missing urls")):this.coordinator.runAccessibilityAudit(r,i)}],["capture-screenshot",async e=>{if(!this.visualTester)return p(new Error("Visual tester not initialized"));let r=e.url;return r?this.visualTester.captureScreenshot(r,e.options):p(new Error("Invalid capture-screenshot payload: missing url"))}],["test-responsiveness",async e=>{if(!this.responsiveTester)return p(new Error("Responsive tester not initialized"));let r=e.url;return r?this.responsiveTester.testResponsiveness(r,e.options):p(new Error("Invalid test-responsiveness payload: missing url"))}],["validate-wcag",async e=>{if(!this.accessibilityTester)return p(new Error("Accessibility tester not initialized"));let r=e.url;if(!r)return p(new Error("Invalid validate-wcag payload: missing url"));let i=e.level||"AA";return this.accessibilityTester.validateWCAGLevel(r,i)}]])}async onInitialize(){this.visualTester=fa(this.memory,this.pluginConfig.visualTester),this.accessibilityTester=new Pr(this.memory,this.pluginConfig.accessibilityTester),this.responsiveTester=new kr(this.memory,this.pluginConfig.responsiveTester),this.coordinator=new Ca(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator,this.pluginConfig.visualTester,this.pluginConfig.accessibilityTester,this.pluginConfig.responsiveTester),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 p(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}))}):p(a.error)}catch(n){return p(y(n))}}),e.registerAction("visual-accessibility","runAccessibilityTest",async(r,i)=>{try{this.ensureInitialized();let n=this.extractUrls(r);if(n.length===0)return p(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}))}):p(a.error)}catch(n){return p(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 Sm(u,t,e,r){return new Zc(u,t,e,r)}M();A();M();import*as Tm from"net";import{execFile as Rm}from"child_process";A();H();se();var Mv={defaultTimeout:6e4,maxConcurrentFaults:3,enableDryRun:!0,safetyCheckInterval:5e3,autoRollbackOnFailure:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},N=R.create("chaos-resilience/chaos-engineer"),Ir=class u{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={...Mv,...e},this.httpClient=new ze,this.metricsCollector=ic()}async createExperiment(t){try{let e=this.validateExperiment(t);if(!e.success)return p(e.error);let r=await this.analyzeExperimentWithLLM(t);return r&&N.info(`LLM Analysis:
3001
3002
  ${r}`),await this.memory.set(`chaos:experiments:${t.id}`,t,{namespace:"chaos-resilience",persist:!0}),f(t.id)}catch(e){return p(y(e))}}async runExperiment(t){try{let e=await this.memory.get(`chaos:experiments:${t}`);if(!e)return p(new Error(`Experiment not found: ${t}`));if(this.activeExperiments.has(t))return p(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:T(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 p(y(e))}}async abortExperiment(t,e){try{let r=this.activeExperiments.get(t);if(!r)return p(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 p(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 p(y(e))}}async injectFault(t){try{if(this.activeFaults.size>=this.config.maxConcurrentFaults)return p(new Error(`Maximum concurrent faults (${this.config.maxConcurrentFaults}) reached`));let e=this.validateFault(t);if(!e.success)return p(e.error);let r=Date.now();if(t.probability!==void 0&&L()>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 p(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 p(y(e))}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}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:
3002
3003
  Experiment: ${t.name}
@@ -3018,4 +3019,4 @@ Provide:
3018
3019
  3. Recommendations for pattern application`}],maxTokens:this.config.llmMaxTokens})).content}catch{return Em.warn("LLM synthesis failed:"),null}}async learnPattern(t){try{if(t.length<this.config.minExperiencesForPattern)return p(new Error(`Need at least ${this.config.minExperiencesForPattern} experiences to learn a pattern`));let e=this.extractCommonActions(t),r=this.calculateSuccessRate(t);if(r<this.config.patternConfidenceThreshold)return p(new Error(`Success rate ${r} below threshold ${this.config.patternConfidenceThreshold}`));let i=this.inferPatternType(t),n=t[0].domain,s=this.generatePatternTemplate(t,e),a=this.extractPatternContext(t),o={id:v(),type:i,domain:n,name:`${i}-${n}-${Date.now()}`,description:`Learned pattern from ${t.length} experiences with ${r*100}% success rate`,confidence:r,usageCount:0,successRate:r,context:a,template:s,createdAt:new Date,lastUsedAt:new Date};return await this.storePattern(o),await this.recordPatternCreation(o,t),f(o)}catch(e){return p(y(e))}}async findMatchingPatterns(t,e=10){try{let r=[],i=await this.memory.search("learning:pattern:*",100);for(let n of i){let s=await this.memory.get(n);s&&this.matchesContext(s,t)&&r.push(s)}return r.sort((n,s)=>{let a=n.confidence*.6+n.successRate*.4;return s.confidence*.6+s.successRate*.4-a}),f(r.slice(0,e))}catch(r){return p(y(r))}}async applyPattern(t,e){try{let r=t.template.content;for(let i of t.template.variables){let n=e[i.name]??i.defaultValue;if(i.required&&n===void 0)return p(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 p(y(r))}}async updatePatternFeedback(t,e){try{let r=`learning:pattern:${t}`,i=await this.memory.get(r);if(!i)return p(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,c={...i,successRate:s,confidence:o,usageCount:i.usageCount+1,lastUsedAt:new Date};return await this.memory.set(r,c,{namespace:"learning-optimization",persist:!0}),f(void 0)}catch(r){return p(y(r))}}async consolidatePatterns(t){try{if(t.length<2)return p(new Error("Need at least 2 patterns to consolidate"));let e=[];for(let s of t){let a=await this.memory.get(`learning:pattern:${s}`);a&&e.push(a)}if(e.length<2)return p(new Error("Not enough valid patterns found"));let r=e.reduce((s,a)=>a.successRate>s.successRate?a:s),i={language:r.context.language,framework:r.context.framework,testType:r.context.testType,codeContext:r.context.codeContext,tags:[...new Set(e.flatMap(s=>s.context.tags))]},n={id:v(),type:r.type,domain:r.domain,name:`consolidated-${r.name}`,description:`Consolidated from ${e.length} patterns`,confidence:this.calculateConsolidatedConfidence(e),usageCount:e.reduce((s,a)=>s+a.usageCount,0),successRate:this.calculateWeightedSuccessRate(e),context:i,template:r.template,createdAt:new Date,lastUsedAt:new Date};await this.storePattern(n);for(let s of e)await this.archivePattern(s.id);return f(n)}catch(e){return p(y(e))}}async getPatternStats(t){try{let e=await this.memory.search("learning:pattern:*",500),r=[];for(let c of e){let l=await this.memory.get(c);l&&(!t||l.domain===t)&&r.push(l)}let i={"test-pattern":0,"fix-pattern":0,"optimization-pattern":0,"detection-pattern":0,"workflow-pattern":0,"failure-pattern":0},n={"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},s=0,a=0;for(let c of r)i[c.type]++,n[c.domain]++,s+=c.confidence,a+=c.successRate;let o=r.sort((c,l)=>l.successRate-c.successRate).slice(0,10);return f({totalPatterns:r.length,byType:i,byDomain:n,avgConfidence:r.length>0?s/r.length:0,avgSuccessRate:r.length>0?a/r.length:0,topPatterns:o})}catch(e){return p(y(e))}}async recordExperience(t){try{let e=v(),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),f(e)}catch(e){return p(y(e))}}async mineExperiences(t,e){try{let r=await this.getExperiencesByDomainAndTime(t,e);if(r.length===0)return f({experienceCount:0,successRate:0,avgReward:0,patterns:[],anomalies:[],recommendations:["No experiences found in the given time range"]});let i=this.calculateSuccessRate(r),n=this.calculateAverageReward(r),s=await this.extractPatternsFromExperiences(r),a=this.detectAnomalies(r),o=this.generateRecommendations(r,i,a);return f({experienceCount:r.length,successRate:i,avgReward:n,patterns:s,anomalies:a,recommendations:o})}catch(r){return p(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 c=t.outcome[o.metric]??0;this.isConstraintViolated(o,c)&&(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),i=[];for(let n of r){let s=await this.memory.get(n);if(s){let a=await this.memory.get(`learning:experience:${s}`);a&&i.push(a)}}return i.sort((n,s)=>s.timestamp.getTime()-n.timestamp.getTime()),f(i.slice(0,e))}catch(r){return p(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),c=this.calculateAverageReward(s);r.push({id:`cluster-${i++}`,centroid:a,experiences:s,commonActions:o,avgReward:c})}return f(r)}catch(e){return p(y(e))}}async storePattern(t){await this.memory.set(`learning:pattern:${t.id}`,t,{namespace:"learning-optimization",persist:!0})}async archivePattern(t){let e=`learning:pattern:${t}`,r=await this.memory.get(e);r&&(await this.memory.set(`learning:pattern:archived:${t}`,r,{namespace:"learning-optimization",persist:!0}),await this.memory.delete(e))}async updatePatternUsage(t){let e=`learning:pattern:${t}`,r=await this.memory.get(e);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),i=[];for(let n of r){let s=await this.memory.get(n);if(s){let a=await this.memory.get(`learning:experience:${s}`);a&&e.contains(a.timestamp)&&i.push(a)}}return i}async extractPatternsFromExperiences(t){let e=t.filter(n=>n.result.success),r=new Map;for(let n of e){let s=r.get(n.action)||[];s.push(n),r.set(n.action,s)}let i=[];for(let[n,s]of r)if(s.length>=this.config.minExperiencesForPattern){let a=await this.learnPattern(s);a.success&&i.push(a.value)}return i}matchesContext(t,e){return!(e.language&&t.context.language!==e.language||e.framework&&t.context.framework!==e.framework||e.testType&&t.context.testType!==e.testType||e.tags.length>0&&!e.tags.some(i=>t.context.tags.includes(i)))}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
3019
3020
  // Common actions: ${e.join(", ")}
3020
3021
  // Apply to domain: {{domain}}
3021
- // 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)}}calculateConsolidatedConfidence(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.confidence*n}return r}calculateWeightedSuccessRate(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.successRate*n}return r}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={},r={};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}}};A();var Vv={maxKnowledgeItems:1e3,relevanceThreshold:.5,transferDecayFactor:.1,crossDomainBoost:.2},Ht=class{constructor(t,e={}){this.memory=t;this.config={...Vv,...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 p(y(r))}}async queryKnowledge(t){try{let e=[],r;t.domain?r=await this.memory.search(`learning:knowledge:*:${t.domain}:*`,t.limit||100):r=await this.memory.search("learning:knowledge:shared:*",t.limit||100);for(let i of r){let n=await this.memory.get(i);n&&this.matchesQuery(n,t)&&e.push(n)}if(e.sort((i,n)=>n.relevanceScore-i.relevanceScore),t.embedding&&t.embedding.length>0){let i=await this.memory.vectorSearch(t.embedding,t.limit||10);for(let n of i){let s=await this.memory.get(n.key);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 p(y(e))}}async synthesizeKnowledge(t){try{if(t.length<2)return p(new Error("Need at least 2 knowledge items to synthesize"));let e=[];for(let c of t){let l=await this.getKnowledgeById(c);l&&e.push(l)}if(e.length<2)return p(new Error("Not enough valid knowledge items found"));let r=this.determineSynthesizedType(e),i=this.determineSynthesizedDomain(e),n=this.mergeKnowledgeContent(e),s=e.reduce((c,l)=>c+l.relevanceScore,0)/e.length,a=Math.min(1,s+this.config.crossDomainBoost),o={id:v(),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 p(y(e))}}async transferKnowledge(t,e){try{if(t.domain===e)return p(new Error("Cannot transfer knowledge to the same domain"));let r=this.calculateTransferredRelevance(t,e);if(r<this.config.relevanceThreshold)return p(new Error(`Transferred relevance ${r} below threshold ${this.config.relevanceThreshold}`));let i=await this.adaptContentForDomain(t.content,t.domain,e),n={id:v(),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 p(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(c=>a.includes(c));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 p(y(r))}}async createKnowledge(t,e,r,i,n=[],s){try{let a={id:v(),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 p(y(a))}}async getKnowledgeById(t){return await this.memory.get(`learning:knowledge:shared:${t}`)||null}async bulkTransfer(t,e,r){try{let i=await this.memory.search(`learning:knowledge:project:${t}:*`,500),n=[];for(let s of i){let a=await this.memory.get(s);if(!a||r?.types&&!r.types.includes(a.type)||r?.minRelevance&&a.relevanceScore<r.minRelevance)continue;let o=await this.adaptContentForProject(a.content,t,e),c={...a,id:v(),content:o,relevanceScore:a.relevanceScore*(1-this.config.transferDecayFactor),version:a.version+1,createdAt:new Date};await this.memory.set(`learning:knowledge:project:${e}:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),n.push({knowledgeId:c.id,sourceDomain:a.domain,targetDomain:a.domain,originalRelevance:a.relevanceScore,transferredRelevance:c.relevanceScore,adaptations:["project-context-adapted"]})}return f(n)}catch(i){return p(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:be.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})}};A();se();var _v={defaultConfidenceLevel:.95,minSamplesForOptimization:20,maxOptimizationIterations:100,improvementThreshold:.05,explorationRate:.1},zv=["__proto__","constructor","prototype"];function Ui(u){return!zv.includes(u)}var Wt=class{constructor(t,e={}){this.memory=t;this.config={..._v,...e}}memory;config;async optimizeStrategy(t,e,r){try{if(r.length<this.config.minSamplesForOptimization)return p(new Error(`Need at least ${this.config.minSamplesForOptimization} experiences for optimization`));let i=this.evaluateStrategyPerformance(t,r,e),n=await this.optimizeParameters(t.parameters,r,e),s={name:`${t.name}-optimized`,parameters:n,expectedOutcome:this.predictOutcome(n,r)},a=await this.validateOptimization(t,s,r.slice(-10)),o=this.evaluateStrategyPerformance(s,r,e),c=this.calculateImprovement(i,o,e),l=this.calculateOptimizationConfidence(r.length,c,a),d=this.inferDomainFromExperiences(r),m={id:v(),domain:d,objective:e,currentStrategy:t,optimizedStrategy:s,improvement:c,confidence:l,validationResults:a};return await this.storeOptimizationResult(m),f(m)}catch(i){return p(y(i))}}async runABTest(t,e,r){try{let i=await this.collectStrategyMetrics(t,r.metric,r.minSamples),n=await this.collectStrategyMetrics(e,r.metric,r.minSamples),s=this.calculateMean(i),a=this.calculateMean(n),o=this.calculateStdDev(i),c=this.calculateStdDev(n),l=this.calculatePValue(i,n),d;l<1-r.confidenceLevel?d=s>a?"A":"B":d="inconclusive";let m={winner:d,strategyAMetrics:{[r.metric]:s,stdDev:o,samples:i.length},strategyBMetrics:{[r.metric]:a,stdDev:c,samples:n.length},pValue:l,sampleSizeA:i.length,sampleSizeB:n.length};return await this.storeABTestResult(t,e,m),f(m)}catch(i){return p(y(i))}}async recommendStrategy(t){try{let e=await this.memory.search("learning:strategy:optimized:*",100),r=[];for(let i of e){let n=await this.memory.get(i);if(n&&n.confidence>.6){let s=this.scoreContextMatch(n,t),a=n.improvement*n.confidence;r.push({strategy:n.optimizedStrategy,score:s*.4+a*.6})}}return r.length===0?f({name:"default-strategy",parameters:this.getDefaultParameters(t),expectedOutcome:{success_rate:.7}}):(r.sort((i,n)=>n.score-i.score),f(r[0].strategy))}catch(e){return p(y(e))}}async evaluateStrategy(t,e){try{let r={},i=this.calculateSuccessRate(e),n=this.calculateAverageDuration(e),s=this.calculateAverageReward(e);r.success_rate=i,r.avg_duration_ms=n,r.avg_reward=s;let a=[];i>.8&&a.push("High success rate"),n<5e3&&a.push("Fast execution"),s>.7&&a.push("Consistently good rewards");let o=[];i<.5&&o.push("Low success rate needs investigation"),n>3e4&&o.push("Slow execution time"),s<.3&&o.push("Low reward values");let c=this.identifyImprovementAreas(t,r,e),l={strategy:t,metrics:r,strengths:a,weaknesses:o,improvementAreas:c};return await this.storeStrategyEvaluation(l),f(l)}catch(r){return p(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 p(y(r))}}async getMetricsHistory(t,e=100){try{let r=await this.memory.search(`learning:metrics:history:${t}:*`,e),i=[];for(let n of r){let s=await this.memory.get(n);s&&i.push(s)}return i.sort((n,s)=>n.timestamp.getTime()-s.timestamp.getTime()),f(i)}catch(r){return p(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 p(y(i))}}evaluateStrategyPerformance(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.outcome[r.metric]??0;i+=a,n++}return n>0?i/n:0}async optimizeParameters(t,e,r){let i={...t};for(let[n,s]of Object.entries(t))if(Ui(n)&&typeof s=="number"){let a=[-.1,-.05,0,.05,.1],o=0,c=this.scoreParameters(i,e,r);for(let l of a){let d={...i,[n]:s*(1+l)},m=this.scoreParameters(d,e,r);(r.direction==="maximize"?m>c:m<c)&&(c=m,o=l)}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),c=s.result.outcome[r.metric]??0;i+=o*c*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))Ui(a)&&typeof o=="number"&&(i[a]=(i[a]||0)+o,n[a]=(n[a]||0)+1);for(let[s,a]of Object.entries(i))Ui(s)&&(r[s]=a/n[s]);return r}async validateOptimization(t,e,r){let i=[];for(let n of r){let s=e.expectedOutcome,a=Object.entries(s).every(([o,c])=>{let l=n.result.outcome[o]??0;return Math.abs(l-c)/Math.max(c,1)<.2});i.push({testId:n.id,passed:a,metrics:n.state.metrics})}return i}calculateImprovement(t,e,r){if(t===0)return e>0?1:0;let i=e-t,n=r.direction==="maximize"?i/t:-i/t;return Math.max(-1,Math.min(1,n))}calculateOptimizationConfidence(t,e,r){let i=Math.min(1,t/(this.config.minSamplesForOptimization*2)),n=r.filter(a=>a.passed).length/Math.max(r.length,1),s=Math.abs(e)>this.config.improvementThreshold?1:.5;return i*.3+n*.5+s*.2}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,r){let i=await this.memory.search("learning:metrics:history:*:*",r*2),n=[];for(let s of i){let a=await this.memory.get(s);a&&a.metrics[e]!==void 0&&n.push(a.metrics[e])}for(;n.length<r;){let s=t.expectedOutcome[e]||.5,a=(L()-.5)*.2;n.push(s+a)}return n}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,c=Math.sqrt(n/a+s/o);if(c===0)return .5;let l=Math.abs(r-i)/c,d=2*(1-this.normalCDF(l));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 c=1/(1+a*t),l=1-((((s*c+n)*c+i)*c+r)*c+e)*c*Math.exp(-t*t);return .5*(1+o*l)}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(!Ui(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))?.metrics||{};for(let[s,a]of Object.entries(e))Ui(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=v();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=v();await this.memory.set(`learning:evaluation:${e}`,{...t,evaluatedAt:new Date},{namespace:"learning-optimization",ttl:86400*7})}};A();var Bv={metricsRetentionDays:90,anomalyThreshold:2.5,trendWindowSize:7,alertThresholds:{error_rate:.05,latency_p99:5e3,memory_usage:.9,cpu_usage:.8}},jt=class{constructor(t,e={}){this.memory=t;this.config={...Bv,...e}}memory;config;async recordMetric(t,e,r,i,n=[]){try{let s={id:v(),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 p(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 p(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 c=await this.memory.get(`production:metric:${o}`);c&&e.contains(c.timestamp)&&s.push(c)}}return s.sort((a,o)=>a.timestamp.getTime()-o.timestamp.getTime()),f(s)}catch(i){return p(y(i))}}async recordIncident(t,e,r,i,n){try{let s={id:v(),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 p(y(s))}}async resolveIncident(t,e,r){try{let i=await this.memory.get(`production:incident:${t}`);if(!i)return p(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 p(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 c=await this.memory.get(`production:incident:${o}`);c&&n.push(c)}}else{let o=await this.memory.get(a);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 p(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[g,h]of Object.entries(m.metrics))r[`${d}_${g}`]=h}s>0?i="unhealthy":n>t.length/3&&(i="degraded");let a=await this.calculateTrends(),o=await this.getRecentIncidents(5),c=o.success?o.value:[],l=this.generateHealthRecommendations(e,r,c);return f({overall:i,domains:e,metrics:r,trends:a,recentIncidents:c,recommendations:l})}catch(t){return p(y(t))}}async getDomainHealth(t){let e=_e.lastNDays(1),r=await this.getMetricsHistory("*",e,t),i={};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=_e.create(s,a),c=await this.getMetricsHistory(i,o);if(c.success&&c.value.length>0){let l=c.value.reduce((d,m)=>d+m.value,0)/c.value.length;t.push({timestamp:s,metric:i,value:l})}}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 c=a.split("_").slice(-2).join("_"),l=this.config.alertThresholds[c];l&&o>l&&i.push(`Metric ${a} (${o.toFixed(2)}) exceeds threshold (${l})`)}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(g=>g.resolvedAt),c=s.length>0?o.length/s.length:1,l=this.calculateRewardFromIncidents(s),d=this.generateInsightRecommendations(i,s),m=this.detectMetricAnomalies(i);return f({experienceCount:a,successRate:c,avgReward:l,patterns:[],anomalies:m,recommendations:d})}catch(r){return p(y(r))}}async recordMilestone(t,e,r){try{let i={name:t,achievedAt:new Date,domain:e};return await this.memory.set(`production:milestone:${v()}`,{...i,metrics:r},{namespace:"learning-optimization",persist:!0}),f(i)}catch(i){return p(y(i))}}async getRecentMilestones(t=10){try{let e=await this.memory.search("production:milestone:*",t),r=[];for(let i of e){let n=await this.memory.get(i);n&&r.push(n)}return r.sort((i,n)=>n.achievedAt.getTime()-i.achievedAt.getTime()),f(r.slice(0,t))}catch(e){return p(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=_e.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,c)=>o+c,0)/i.length,s=Math.sqrt(i.reduce((o,c)=>o+Math.pow(c-n,2),0)/i.length),a=Math.abs(t.value-n)/(s||1);a>this.config.anomalyThreshold&&await this.memory.set(`production:anomaly:${v()}`,{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:v(),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:v(),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(c=>c.value),a=s.reduce((c,l)=>c+l,0)/s.length,o=Math.sqrt(s.reduce((c,l)=>c+Math.pow(l-a,2),0)/s.length);for(let c of n){let l=Math.abs(c.value-a)/(o||1);l>this.config.anomalyThreshold&&e.push({experienceId:c.id,type:"outlier-reward",description:`${i} value ${c.value.toFixed(2)} is ${l.toFixed(1)} std deviations from mean`,deviation:l})}}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 xm(u,t,e){await u.set(`learning:strategy:current:${t}`,e,{namespace:"learning-optimization",persist:!0})}function Pm(u,t){let e=u.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 km(u){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":be.filter(e=>e!=="learning-optimization"),"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:be.filter(e=>e!=="coordination")}[u]||[]}function Im(u){let t=[],e=new Set;for(let r of u){if(e.has(r.id))continue;let i=[r];e.add(r.id);for(let n of u)e.has(n.id)||r.type===n.type&&r.domain===n.domain&&qv(r.context,n.context)&&(i.push(n),e.add(n.id));i.length>=2&&t.push(i)}return t}function qv(u,t){return u.tags.some(e=>t.tags.includes(e))}function Dm(u,t,e){let r=JSON.stringify({patternCount:u.length,knowledgeCount:t.length,strategyCount:e.length,patternIds:u.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)}M();var Fr=R.create("learning-optimization/consensus");async function Mm(u,t,e,r){let i=V({id:v(),type:"pattern-recommendation",confidence:t,description:`Verify pattern recommendation: ${u.name} (${u.type}) for domain ${u.domain}`,payload:u,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"?(Fr.info(`Pattern recommendation '${u.name}' verified by consensus`),!0):(Fr.warn(`Pattern recommendation '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Fm(u,t,e,r){let i=V({id:v(),type:"optimization-suggestion",confidence:t,description:`Verify optimization: ${u.metric} from ${u.currentValue} to ${u.targetValue} via ${u.strategy}`,payload:u,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"?(Fr.info(`Optimization suggestion for '${u.metric}' verified by consensus`),!0):(Fr.warn(`Optimization suggestion for '${u.metric}' NOT verified`),!1)}return!0}async function Lm(u,t,e,r){let i=V({id:v(),type:"cross-domain-insight",confidence:t,description:`Verify cross-domain insight: ${u.description}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:"high"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Cross-domain insight verified by consensus for ${u.targetDomains.length} target domains`),!0):(Fr.warn(`Cross-domain insight NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var Wv={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},Re=R.create("learning-optimization"),Ta=class extends Q{constructor(e,r,i,n={}){let s={...Wv,...n};super(e,"learning-optimization",s,{verifyFindingTypes:["pattern-recommendation","optimization-suggestion","cross-domain-insight"]});this.memory=r;this.agentCoordinator=i;this.learningService=new Gt({memory:r}),this.transferService=new Ht(r),this.optimizerService=new Wt(r),this.productionIntel=new jt(r)}memory;agentCoordinator;learningService;transferService;optimizerService;productionIntel;sona=null;dreamScheduler=null;async onInitialize(){try{this.sona=await me({domain:"learning-optimization",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.5}),Re.info("PersistentSONAEngine initialized for pattern learning")}catch(e){Re.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),Re.warn("Continuing without SONA pattern persistence"),this.sona=null}if(this.config.enableDreamScheduler)try{let e=await Sl();await e.initialize(),this.dreamScheduler=Rl({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(),Re.info("DreamScheduler initialized and started")}catch{Re.warn("Failed to initialize DreamScheduler:")}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){if(await this.saveWorkflowState(),this.dreamScheduler){try{await this.dreamScheduler.dispose(),Re.info("DreamScheduler disposed")}catch(e){Re.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){Re.error("Error closing SONA engine:",e instanceof Error?e:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async runLearningCycle(e){let r=v();try{if(this.startWorkflow(r,"learning-cycle"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, using conservative strategy for learning cycle"),this.minCutMixin.shouldPauseOperations())return p(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),p(i.error);this.addAgentToWorkflow(r,i.value);let n=_e.lastNDays(1),s=await this.getExperiencesForDomain(e,n),a=s.success?s.value:[];this.updateWorkflowProgress(r,20);let o=await this.learningService.mineExperiences(e,n),c=o.success?o.value.patterns.length:0;this.updateWorkflowProgress(r,50);let l=0,d=[];if(a.length>=10){let h={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(e),w=await this.optimizerService.optimizeStrategy(b,h,a);w.success&&(l=1,d.push({metric:h.metric,before:this.calculateMetricValue(a,h.metric),after:w.value.optimizedStrategy.expectedOutcome[h.metric]||0,percentChange:w.value.improvement*100}))}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 g={domain:e,experiencesProcessed:a.length,patternsLearned:c,strategiesOptimized:l,knowledgeGenerated:m,improvements:d};return this.config.publishEvents&&c>0&&await this.publishPatternConsolidated(c,[e]),f(g)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async optimizeAllStrategies(){let e=v();try{if(this.startWorkflow(e,"optimization"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, using conservative optimization strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Optimization paused: topology is in critical state"));let r={},i=0,n=0,s=0,a=be.filter(c=>c!=="learning-optimization");for(let c=0;c<a.length;c++){let l=a[c];this.updateWorkflowProgress(e,Math.round(c/a.length*100));let d=_e.lastNDays(7),m=await this.getExperiencesForDomain(l,d);if(!m.success||m.value.length<10)continue;let g=m.value,h={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(l),w=await this.optimizerService.optimizeStrategy(b,h,g);w.success&&(i++,n+=w.value.improvement,s++,r[l]={strategiesOptimized:1,avgImprovement:w.value.improvement,bestStrategy:w.value.optimizedStrategy},await this.storeStrategy(l,w.value.optimizedStrategy))}this.completeWorkflow(e);let o={domainsOptimized:s,totalStrategies:i,avgImprovement:i>0?n/i:0,byDomain:r};return this.config.publishEvents&&i>0&&await this.publishOptimizationApplied(o),f(o)}catch(r){return this.failWorkflow(e,String(r)),p(y(r))}}async shareCrossDomainLearnings(){let e=v();try{if(this.startWorkflow(e,"transfer"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, limiting cross-domain transfer scope"),this.minCutMixin.shouldPauseOperations())return p(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),p(o.error);let c=o.value;for(let m of c){let g=this.getRelatedDomains(m.domain);for(let h of g){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/(c.length*2)*100))}let l=await this.learningService.getPatternStats();if(l.success){let m=l.value.topPatterns;if(m.length>=2){let g=this.findSimilarPatterns(m);for(let h of g)h.length>=2&&(await this.learningService.consolidatePatterns(h.map(w=>w.id))).success&&n++}}this.completeWorkflow(e);let d={knowledgeShared:r,domainsUpdated:i,transferSuccessRate:s>0?a/s:1,newPatternsCreated:n};return this.config.publishEvents&&r>0&&await this.publishTransferCompleted(d),f(d)}catch(r){return this.failWorkflow(e,String(r)),p(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=_e.lastNDays(1),a=0;for(let b of be){let w=await this.getExperiencesForDomain(b,s);w.success&&(a+=w.value.length)}let o=await this.productionIntel.getProductionHealth(),c=o.success?o.value.trends:[],l=await this.productionIntel.getRecentMilestones(5),d=l.success?l.value:[],m=r?r.avgSuccessRate*.6+r.avgConfidence*.4:.5,g=[];if(r){let b=Object.entries(r.byDomain).filter(([w,C])=>C>0).map(([w,C])=>({domain:w,score:C})).sort((w,C)=>C.score-w.score);g.push(...b.slice(0,3).map(w=>w.domain))}let h={overallLearningRate:m,totalPatterns:r?.totalPatterns||0,totalKnowledge:n,experiencesLast24h:a,topPerformingDomains:g,learningTrend:c,recentMilestones:d};return f(h)}catch(e){return p(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()}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=v();try{this.startWorkflow(r,"export");let i=e||be,n=[],s=[],a=[];for(let m of i){let g=await this.memory.search("learning:pattern:*",500);for(let h of g){let b=await this.memory.get(h);b&&i.includes(b.domain)&&n.push(b)}this.updateWorkflowProgress(r,Math.round(n.length/100*30))}let o=await this.transferService.queryKnowledge({limit:1e3});if(o.success)for(let m of o.value)i.includes(m.domain)&&s.push(m);this.updateWorkflowProgress(r,60);let c=await this.memory.search("learning:strategy:optimized:*",200);for(let m of c){let g=await this.memory.get(m);g&&i.includes(g.domain)&&a.push(g)}this.updateWorkflowProgress(r,90);let l=this.calculateChecksum(n,s,a);return this.completeWorkflow(r),f({version:"1.0.0",exportedAt:new Date,patterns:n,knowledge:s,strategies:a,checksum:l})}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async importModels(e){let r=v();try{if(this.startWorkflow(r,"import"),this.calculateChecksum(e.patterns,e.knowledge,e.strategies)!==e.checksum)return this.failWorkflow(r,"Checksum mismatch"),p(new Error("Import failed: checksum mismatch"));let n=0,s=0,a=0,o=[];for(let l of e.patterns){let d=await this.memory.get(`learning:pattern:${l.id}`);d?d.confidence<l.confidence?(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++,o.push({type:"pattern",id:l.id,reason:"Existing pattern had lower confidence",resolution:"overwrite"})):o.push({type:"pattern",id:l.id,reason:"Existing pattern has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++),this.updateWorkflowProgress(r,Math.round(n/e.patterns.length*30))}for(let l of e.knowledge){let d=await this.memory.get(`learning:knowledge:shared:${l.id}`);d?l.version>d.version?(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++,o.push({type:"knowledge",id:l.id,reason:"Import has newer version",resolution:"overwrite"})):o.push({type:"knowledge",id:l.id,reason:"Existing knowledge is same or newer version",resolution:"skip"}):(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++),this.updateWorkflowProgress(r,30+Math.round(s/e.knowledge.length*30))}for(let l of e.strategies){let d=await this.memory.get(`learning:strategy:optimized:${l.id}`);d?l.confidence>d.confidence?(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),a++,o.push({type:"strategy",id:l.id,reason:"Import has higher confidence",resolution:"overwrite"})):o.push({type:"strategy",id:l.id,reason:"Existing strategy has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{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)),p(y(i))}}subscribeToEvents(){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("learning.ExperienceCaptured",this.handleExperienceCaptured.bind(this))}async handleTestRunCompleted(e){let{runId:r,passed:i,failed:n,duration:s}=e.payload,a=i+n>0?i/(i+n):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r},metrics:{passed:i,failed:n,duration:s}},result:{success:a>.8,outcome:{success_rate:a,passed:i,failed:n},duration:s},reward:a})}async handleCoverageGap(e){let{gapId:r,file:i,riskScore:n}=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,file:i},metrics:{riskScore:n}},result:{success:!0,outcome:{risk_score:n},duration:0},reward:1-n})}async handleQualityGate(e){let{gateId:r,passed:i}=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},metrics:{passed:i?1:0}},result:{success:i,outcome:{gate_passed:i?1:0},duration:0},reward:i?1:0})}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);Re.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=D(Ge.PatternConsolidated,"learning-optimization",i);await this.eventBus.publish(n)}async publishTransferCompleted(e){let r={sourceProject:"current",targetProject:"current",patternsTransferred:e.knowledgeShared,successRate:e.transferSuccessRate},i=D(Ge.TransferCompleted,"learning-optimization",r);await this.eventBus.publish(i)}async publishOptimizationApplied(e){let r=D(Ge.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=D(Ge.DreamCycleCompleted,"learning-optimization",a);await this.eventBus.publish(o),Re.info(`[LearningOptimizationCoordinator] Published dream cycle completion: ${n.length} insights for ${i} concepts`)}async spawnLearningAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(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=await this.memory.get(`learning:experience:${a}`);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:{success_rate:.8}}}async storeStrategy(e,r){await xm(this.memory,e,r)}calculateMetricValue(e,r){return Pm(e,r)}getRelatedDomains(e){return km(e)}findSimilarPatterns(e){return Im(e)}calculateChecksum(e,r,i){return Dm(e,r,i)}async verifyPatternRecommendation(e,r){return Mm(e,r,this.consensusMixin,this.domainName)}async verifyOptimizationSuggestion(e,r){return Fm(e,r,this.consensusMixin,this.domainName)}async verifyCrossDomainInsight(e,r){return Lm(e,r,this.consensusMixin,this.domainName)}};A();var tl=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;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,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 p(new Error("Coordinator not initialized"));let r=e.domain;return r?this.coordinator.runLearningCycle(r):p(new Error("Invalid run-learning-cycle payload: missing domain"))}],["optimize-strategies",async e=>this.coordinator?this.coordinator.optimizeAllStrategies():p(new Error("Coordinator not initialized"))],["share-learnings",async e=>this.coordinator?this.coordinator.shareCrossDomainLearnings():p(new Error("Coordinator not initialized"))],["learn-pattern",async e=>{if(!this.learningService)return p(new Error("Learning service not initialized"));let r=e.experiences;return!r||r.length===0?p(new Error("Invalid learn-pattern payload: missing experiences")):this.learningService.learnPattern(r)}],["query-knowledge",async e=>{if(!this.transferService)return p(new Error("Transfer service not initialized"));let r=e.query;return r?this.transferService.queryKnowledge(r):p(new Error("Invalid query-knowledge payload: missing query"))}]])}async onInitialize(){this.learningService=new Gt({memory:this.memory},this.pluginConfig.learningService),this.transferService=new Ht(this.memory,this.pluginConfig.transferService),this.optimizerService=new Wt(this.memory,this.pluginConfig.optimizerService),this.productionIntel=new jt(this.memory,this.pluginConfig.productionIntel),this.coordinator=new Ta(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,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})}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}),await this.productionIntel.recordMetric("test_success_rate",i,"ratio","test-execution",["automated"])}async handleCoverageGap(e){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})}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})}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})}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})}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}),p(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 $m(u,t,e,r){return new tl(u,t,e,r)}var rl=class extends W{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 be.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=Tl(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 Om(u,t,e,r){return new rl(u,t,e,r)}var Te={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"},il=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())}},Ae=new il;Ae.register(Te.createTestGeneratorService,u=>Tt(u));Ae.register(Te.CoverageAnalyzerService,u=>new mt(u));Ae.register(Te.SecurityScannerService,u=>new $e(u));Ae.register(Te.isSemgrepAvailable,Vi);Ae.register(Te.runSemgrepWithRules,Gs);Ae.register(Te.convertSemgrepFindings,Hs);Ae.register(Te.KnowledgeGraphService,u=>new Rt(u));A();Ae.register(Te.QualityAnalyzerService,u=>new Ye(u));A();M();A();var Ut={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"},Kv={maxConcurrentWorkflows:8,defaultTimeout:12e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Aa=R.create("enterprise-integration"),Ea=class extends Q{constructor(e,r,i,n={}){let s={...Kv,...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(),Aa.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=v();try{if(this.startWorkflow(r,"soap"),this.minCutMixin.shouldPauseOperations())return p(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)),p(y(i))}}async testSoapOperation(e,r,i){let n=v();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),p(s.error);let a={operation:r,passed:!0,request:JSON.stringify(i),response:"",validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.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)),p(y(s))}}async testMessageFlow(e,r){let i=v();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),p(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(D(Ut.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)),p(y(n))}}async testDlqHandling(e,r){let i=v();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),p(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)),p(y(n))}}async testBapiCall(e,r){let i=v();try{if(this.startWorkflow(i,"rfc"),this.minCutMixin.shouldPauseOperations())return p(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),p(n.error);let s={bapiName:r.name,passed:!0,returnMessages:[],exportValues:{},tableData:{},duration:0,transactionCommitted:!1};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.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)),p(y(n))}}async validateIdoc(e,r){let i=v();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),p(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(D(Ut.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)),p(y(n))}}async validateODataMetadata(e){let r=v();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),p(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)),p(y(i))}}async testODataEntitySet(e,r){let i=v();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),p(n.error);let s={entitySet:r,operation:"CRUD",passed:!0,statusCode:200,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.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)),p(y(n))}}async validateMessageFlow(e,r){let i=v();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),p(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(D(Ut.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)),p(y(n))}}async validateTransformation(e,r,i){let n=v();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),p(s.error))}catch(s){return this.failWorkflow(n,String(s)),p(y(s))}}async analyzeSod(e,r){let i=v();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),p(n.error);let s={userId:e,conflicts:[],riskScore:0,compliant:!0,recommendations:[]};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.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)),p(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=V({id:v(),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"?(Aa.info(`Finding verified by consensus: ${e.type}`),!0):(Aa.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"))&&Aa.info(`Middleware fault injection detected: ${r.targetService}`)}};var nl=class extends W{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 p(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?p(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 p(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):p(new Error("Invalid message-broker-test payload: missing testCase")):p(new Error("Invalid message-broker-test payload: missing brokerConfig"))}],["enterprise-integration:sap-rfc-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.connection,i=e.bapi;return!r||!i?p(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 p(new Error("Enterprise integration coordinator not initialized"));let r=e.definition,i=e.content;return!r||!i?p(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 p(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?p(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 p(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?p(new Error("Invalid esb-flow-test payload: missing transformInput or expectedOutput for transformation")):this.coordinator.validateTransformation(n,s,a)}return!r||!i?p(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 p(new Error("Enterprise integration coordinator not initialized"));let r=e.userId,i=e.ruleset;return!r||!i?p(new Error("Invalid sod-analyze payload: missing userId or ruleset")):this.coordinator.analyzeSod(r,i)}]])}async onInitialize(){this.coordinator=new Ea(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 Vm(u,t,e,r){return new nl(u,t,e,r)}var _m={"test-generation":(u,t,e)=>Eo(u,t,e),"test-execution":(u,t)=>Fu(u,t),"coverage-analysis":(u,t)=>Zo(u,t),"quality-assessment":(u,t,e)=>lc(u,t,e),"defect-intelligence":(u,t,e)=>hd(u,t,e),"requirements-validation":(u,t,e)=>bd(u,t,e),"code-intelligence":(u,t,e)=>Tc(u,t,e),"security-compliance":(u,t,e)=>Uc(u,t,e),"contract-testing":(u,t,e)=>om(u,t,e),"visual-accessibility":(u,t,e)=>Sm(u,t,e),"chaos-resilience":(u,t,e)=>Am(u,t,e),"learning-optimization":(u,t,e)=>$m(u,t,e),"enterprise-integration":(u,t,e)=>Vm(u,t,e),coordination:(u,t,e)=>Om(u,t,e)},Yv={maxConcurrentAgents:Lr.MAX_CONCURRENT_AGENTS,memoryBackend:"hybrid",hnswEnabled:!0,lazyLoading:!0,enabledDomains:[...be],dataDir:void 0},sl=class{_eventBus;_coordinator;_plugins;_memory;_config;_startTime;_initialized=!1;_loopTracker;constructor(t={}){this._config={...Yv,...t},this._startTime=new Date,this._memory=new Da,this._eventBus=new on,this._coordinator=new cn(this._config.maxConcurrentAgents),this._plugins=new qr(this._eventBus,this._memory,this._config.lazyLoading),this._loopTracker=new ln}get eventBus(){return this._eventBus}get coordinator(){return this._coordinator}get plugins(){return this._plugins}get memory(){return this._memory}async initialize(){if(this._initialized)return;let t=cl(),e=this._config.dataDir||Qt.join(t,".agentic-qe");if(xa.existsSync(e)||xa.mkdirSync(e,{recursive:!0}),this._config.memoryBackend==="memory"){let i=Qt.join(Pa("os").tmpdir(),`aqe-test-${Date.now()}-${Jv().slice(0,12)}.db`);await ul({dbPath:i})}else this._memory=new ll({sqlite:{path:Qt.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:ol.BUSY_TIMEOUT_MS},enableFallback:!0,defaultNamespace:"qe-kernel"}),this._plugins=new qr(this._eventBus,this._memory,this._config.lazyLoading);for(let i of this._config.enabledDomains){let n=_m[i];n&&this._plugins.registerFactory(i,async(s,a)=>Promise.resolve(n(s,a,this._coordinator)))}await this._memory.initialize();let r=new dn({agentId:"qe-kernel"});this._eventBus.registerMiddleware(r);try{let i=Qt.join(e,"plugins"),n=new dl({cacheDir:i}),a=new ml({cache:n}).resolveLoadOrder();for(let o of a.ordered){let c=o.manifest,l=n.get(c.name,c.version);if(!l)continue;let d=Qt.join(l.path,c.entryPoint);for(let m of c.domains){let g=m;if(_m[g])continue;this._plugins.registerFactory(g,async(b,w)=>{let C=await import(d),S=C.default??C.createPlugin;if(typeof S!="function")throw new Error(`Plugin "${c.name}" entry point must export a default function or "createPlugin" function`);return S(b,w,this._coordinator)})}}}catch{}this._config.lazyLoading||await this._plugins.loadAll();try{let{isAgentMemoryBranchingEnabled:i,isRVFPatternStoreEnabled:n}=await import("./feature-flags-264QUQ3E.js");if(i()&&n()){let{getSharedRvfAdapter:s}=await import("./shared-rvf-adapter-5UQSTUSR.js"),{AgentMemoryBranch:a}=await import("./agent-memory-branch-3GGTDVR4.js"),o=s(e,384);if(o){let c=new a(o,{branchDir:Qt.join(e,"branches")});this._coordinator.setMemoryBranch(c)}}}catch{}try{let{getRvfMigrationStage:i}=await import("./feature-flags-264QUQ3E.js"),n=i();if(n>=2){let{RvfMigrationCoordinator:s}=await import("./rvf-migration-coordinator-FYBIF3SX.js");await s.getInstance({stage:n}).initialize()}}catch{}this._initialized=!0}async dispose(){await this._plugins.disposeAll(),await this._coordinator.dispose(),await this._eventBus.dispose(),await this._memory.dispose(),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}:`,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}:`,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 c of this._plugins.getLoaded()){let l=this._plugins.getPlugin(c);l&&(e[c]=l.getHealth())}for(let c of be)if(!e[c]){let l=this._config.enabledDomains.includes(c),d=this._config.lazyLoading&&l;e[c]={status:d?"healthy":l?"degraded":"healthy",agents:{total:0,active:0,idle:0,failed:0},errors:d?[]:l?["Domain not yet loaded"]:[],loaded:!1,lazyLoadable:d}}let r=this._coordinator.getActiveCount(),i=0,n=Number.MAX_SAFE_INTEGER;if(this._memory instanceof Da){let c=this._memory.getStats();i=c.entries+c.vectors}else i=0;let a=this._eventBus.getMiddlewares().find(c=>c.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:za.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:za.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 i6(u){return new sl(u)}export{Tt as a,mt as b,cr as c,dr as d,Ot as e,Sc as f,he as g,_e as h,zt as i,xc as j,qs as k,Tr as l,Ar as m,fa as n,Pr as o,Ir as p,Gt as q,Ht as r,Wt as s,Te as t,Ae as u,sl as v,i6 as w};
3022
+ // 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)}}calculateConsolidatedConfidence(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.confidence*n}return r}calculateWeightedSuccessRate(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.successRate*n}return r}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={},r={};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}}};A();var Vv={maxKnowledgeItems:1e3,relevanceThreshold:.5,transferDecayFactor:.1,crossDomainBoost:.2},Ht=class{constructor(t,e={}){this.memory=t;this.config={...Vv,...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 p(y(r))}}async queryKnowledge(t){try{let e=[],r;t.domain?r=await this.memory.search(`learning:knowledge:*:${t.domain}:*`,t.limit||100):r=await this.memory.search("learning:knowledge:shared:*",t.limit||100);for(let i of r){let n=await this.memory.get(i);n&&this.matchesQuery(n,t)&&e.push(n)}if(e.sort((i,n)=>n.relevanceScore-i.relevanceScore),t.embedding&&t.embedding.length>0){let i=await this.memory.vectorSearch(t.embedding,t.limit||10);for(let n of i){let s=await this.memory.get(n.key);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 p(y(e))}}async synthesizeKnowledge(t){try{if(t.length<2)return p(new Error("Need at least 2 knowledge items to synthesize"));let e=[];for(let c of t){let l=await this.getKnowledgeById(c);l&&e.push(l)}if(e.length<2)return p(new Error("Not enough valid knowledge items found"));let r=this.determineSynthesizedType(e),i=this.determineSynthesizedDomain(e),n=this.mergeKnowledgeContent(e),s=e.reduce((c,l)=>c+l.relevanceScore,0)/e.length,a=Math.min(1,s+this.config.crossDomainBoost),o={id:v(),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 p(y(e))}}async transferKnowledge(t,e){try{if(t.domain===e)return p(new Error("Cannot transfer knowledge to the same domain"));let r=this.calculateTransferredRelevance(t,e);if(r<this.config.relevanceThreshold)return p(new Error(`Transferred relevance ${r} below threshold ${this.config.relevanceThreshold}`));let i=await this.adaptContentForDomain(t.content,t.domain,e),n={id:v(),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 p(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(c=>a.includes(c));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 p(y(r))}}async createKnowledge(t,e,r,i,n=[],s){try{let a={id:v(),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 p(y(a))}}async getKnowledgeById(t){return await this.memory.get(`learning:knowledge:shared:${t}`)||null}async bulkTransfer(t,e,r){try{let i=await this.memory.search(`learning:knowledge:project:${t}:*`,500),n=[];for(let s of i){let a=await this.memory.get(s);if(!a||r?.types&&!r.types.includes(a.type)||r?.minRelevance&&a.relevanceScore<r.minRelevance)continue;let o=await this.adaptContentForProject(a.content,t,e),c={...a,id:v(),content:o,relevanceScore:a.relevanceScore*(1-this.config.transferDecayFactor),version:a.version+1,createdAt:new Date};await this.memory.set(`learning:knowledge:project:${e}:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),n.push({knowledgeId:c.id,sourceDomain:a.domain,targetDomain:a.domain,originalRelevance:a.relevanceScore,transferredRelevance:c.relevanceScore,adaptations:["project-context-adapted"]})}return f(n)}catch(i){return p(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:be.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})}};A();se();var _v={defaultConfidenceLevel:.95,minSamplesForOptimization:20,maxOptimizationIterations:100,improvementThreshold:.05,explorationRate:.1},zv=["__proto__","constructor","prototype"];function Ui(u){return!zv.includes(u)}var Wt=class{constructor(t,e={}){this.memory=t;this.config={..._v,...e}}memory;config;async optimizeStrategy(t,e,r){try{if(r.length<this.config.minSamplesForOptimization)return p(new Error(`Need at least ${this.config.minSamplesForOptimization} experiences for optimization`));let i=this.evaluateStrategyPerformance(t,r,e),n=await this.optimizeParameters(t.parameters,r,e),s={name:`${t.name}-optimized`,parameters:n,expectedOutcome:this.predictOutcome(n,r)},a=await this.validateOptimization(t,s,r.slice(-10)),o=this.evaluateStrategyPerformance(s,r,e),c=this.calculateImprovement(i,o,e),l=this.calculateOptimizationConfidence(r.length,c,a),d=this.inferDomainFromExperiences(r),m={id:v(),domain:d,objective:e,currentStrategy:t,optimizedStrategy:s,improvement:c,confidence:l,validationResults:a};return await this.storeOptimizationResult(m),f(m)}catch(i){return p(y(i))}}async runABTest(t,e,r){try{let i=await this.collectStrategyMetrics(t,r.metric,r.minSamples),n=await this.collectStrategyMetrics(e,r.metric,r.minSamples),s=this.calculateMean(i),a=this.calculateMean(n),o=this.calculateStdDev(i),c=this.calculateStdDev(n),l=this.calculatePValue(i,n),d;l<1-r.confidenceLevel?d=s>a?"A":"B":d="inconclusive";let m={winner:d,strategyAMetrics:{[r.metric]:s,stdDev:o,samples:i.length},strategyBMetrics:{[r.metric]:a,stdDev:c,samples:n.length},pValue:l,sampleSizeA:i.length,sampleSizeB:n.length};return await this.storeABTestResult(t,e,m),f(m)}catch(i){return p(y(i))}}async recommendStrategy(t){try{let e=await this.memory.search("learning:strategy:optimized:*",100),r=[];for(let i of e){let n=await this.memory.get(i);if(n&&n.confidence>.6){let s=this.scoreContextMatch(n,t),a=n.improvement*n.confidence;r.push({strategy:n.optimizedStrategy,score:s*.4+a*.6})}}return r.length===0?f({name:"default-strategy",parameters:this.getDefaultParameters(t),expectedOutcome:{success_rate:.7}}):(r.sort((i,n)=>n.score-i.score),f(r[0].strategy))}catch(e){return p(y(e))}}async evaluateStrategy(t,e){try{let r={},i=this.calculateSuccessRate(e),n=this.calculateAverageDuration(e),s=this.calculateAverageReward(e);r.success_rate=i,r.avg_duration_ms=n,r.avg_reward=s;let a=[];i>.8&&a.push("High success rate"),n<5e3&&a.push("Fast execution"),s>.7&&a.push("Consistently good rewards");let o=[];i<.5&&o.push("Low success rate needs investigation"),n>3e4&&o.push("Slow execution time"),s<.3&&o.push("Low reward values");let c=this.identifyImprovementAreas(t,r,e),l={strategy:t,metrics:r,strengths:a,weaknesses:o,improvementAreas:c};return await this.storeStrategyEvaluation(l),f(l)}catch(r){return p(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 p(y(r))}}async getMetricsHistory(t,e=100){try{let r=await this.memory.search(`learning:metrics:history:${t}:*`,e),i=[];for(let n of r){let s=await this.memory.get(n);s&&i.push(s)}return i.sort((n,s)=>n.timestamp.getTime()-s.timestamp.getTime()),f(i)}catch(r){return p(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 p(y(i))}}evaluateStrategyPerformance(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.outcome[r.metric]??0;i+=a,n++}return n>0?i/n:0}async optimizeParameters(t,e,r){let i={...t};for(let[n,s]of Object.entries(t))if(Ui(n)&&typeof s=="number"){let a=[-.1,-.05,0,.05,.1],o=0,c=this.scoreParameters(i,e,r);for(let l of a){let d={...i,[n]:s*(1+l)},m=this.scoreParameters(d,e,r);(r.direction==="maximize"?m>c:m<c)&&(c=m,o=l)}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),c=s.result.outcome[r.metric]??0;i+=o*c*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))Ui(a)&&typeof o=="number"&&(i[a]=(i[a]||0)+o,n[a]=(n[a]||0)+1);for(let[s,a]of Object.entries(i))Ui(s)&&(r[s]=a/n[s]);return r}async validateOptimization(t,e,r){let i=[];for(let n of r){let s=e.expectedOutcome,a=Object.entries(s).every(([o,c])=>{let l=n.result.outcome[o]??0;return Math.abs(l-c)/Math.max(c,1)<.2});i.push({testId:n.id,passed:a,metrics:n.state.metrics})}return i}calculateImprovement(t,e,r){if(t===0)return e>0?1:0;let i=e-t,n=r.direction==="maximize"?i/t:-i/t;return Math.max(-1,Math.min(1,n))}calculateOptimizationConfidence(t,e,r){let i=Math.min(1,t/(this.config.minSamplesForOptimization*2)),n=r.filter(a=>a.passed).length/Math.max(r.length,1),s=Math.abs(e)>this.config.improvementThreshold?1:.5;return i*.3+n*.5+s*.2}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,r){let i=await this.memory.search("learning:metrics:history:*:*",r*2),n=[];for(let s of i){let a=await this.memory.get(s);a&&a.metrics[e]!==void 0&&n.push(a.metrics[e])}for(;n.length<r;){let s=t.expectedOutcome[e]||.5,a=(L()-.5)*.2;n.push(s+a)}return n}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,c=Math.sqrt(n/a+s/o);if(c===0)return .5;let l=Math.abs(r-i)/c,d=2*(1-this.normalCDF(l));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 c=1/(1+a*t),l=1-((((s*c+n)*c+i)*c+r)*c+e)*c*Math.exp(-t*t);return .5*(1+o*l)}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(!Ui(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))?.metrics||{};for(let[s,a]of Object.entries(e))Ui(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=v();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=v();await this.memory.set(`learning:evaluation:${e}`,{...t,evaluatedAt:new Date},{namespace:"learning-optimization",ttl:86400*7})}};A();var Bv={metricsRetentionDays:90,anomalyThreshold:2.5,trendWindowSize:7,alertThresholds:{error_rate:.05,latency_p99:5e3,memory_usage:.9,cpu_usage:.8}},jt=class{constructor(t,e={}){this.memory=t;this.config={...Bv,...e}}memory;config;async recordMetric(t,e,r,i,n=[]){try{let s={id:v(),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 p(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 p(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 c=await this.memory.get(`production:metric:${o}`);c&&e.contains(c.timestamp)&&s.push(c)}}return s.sort((a,o)=>a.timestamp.getTime()-o.timestamp.getTime()),f(s)}catch(i){return p(y(i))}}async recordIncident(t,e,r,i,n){try{let s={id:v(),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 p(y(s))}}async resolveIncident(t,e,r){try{let i=await this.memory.get(`production:incident:${t}`);if(!i)return p(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 p(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 c=await this.memory.get(`production:incident:${o}`);c&&n.push(c)}}else{let o=await this.memory.get(a);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 p(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[g,h]of Object.entries(m.metrics))r[`${d}_${g}`]=h}s>0?i="unhealthy":n>t.length/3&&(i="degraded");let a=await this.calculateTrends(),o=await this.getRecentIncidents(5),c=o.success?o.value:[],l=this.generateHealthRecommendations(e,r,c);return f({overall:i,domains:e,metrics:r,trends:a,recentIncidents:c,recommendations:l})}catch(t){return p(y(t))}}async getDomainHealth(t){let e=_e.lastNDays(1),r=await this.getMetricsHistory("*",e,t),i={};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=_e.create(s,a),c=await this.getMetricsHistory(i,o);if(c.success&&c.value.length>0){let l=c.value.reduce((d,m)=>d+m.value,0)/c.value.length;t.push({timestamp:s,metric:i,value:l})}}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 c=a.split("_").slice(-2).join("_"),l=this.config.alertThresholds[c];l&&o>l&&i.push(`Metric ${a} (${o.toFixed(2)}) exceeds threshold (${l})`)}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(g=>g.resolvedAt),c=s.length>0?o.length/s.length:1,l=this.calculateRewardFromIncidents(s),d=this.generateInsightRecommendations(i,s),m=this.detectMetricAnomalies(i);return f({experienceCount:a,successRate:c,avgReward:l,patterns:[],anomalies:m,recommendations:d})}catch(r){return p(y(r))}}async recordMilestone(t,e,r){try{let i={name:t,achievedAt:new Date,domain:e};return await this.memory.set(`production:milestone:${v()}`,{...i,metrics:r},{namespace:"learning-optimization",persist:!0}),f(i)}catch(i){return p(y(i))}}async getRecentMilestones(t=10){try{let e=await this.memory.search("production:milestone:*",t),r=[];for(let i of e){let n=await this.memory.get(i);n&&r.push(n)}return r.sort((i,n)=>n.achievedAt.getTime()-i.achievedAt.getTime()),f(r.slice(0,t))}catch(e){return p(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=_e.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,c)=>o+c,0)/i.length,s=Math.sqrt(i.reduce((o,c)=>o+Math.pow(c-n,2),0)/i.length),a=Math.abs(t.value-n)/(s||1);a>this.config.anomalyThreshold&&await this.memory.set(`production:anomaly:${v()}`,{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:v(),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:v(),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(c=>c.value),a=s.reduce((c,l)=>c+l,0)/s.length,o=Math.sqrt(s.reduce((c,l)=>c+Math.pow(l-a,2),0)/s.length);for(let c of n){let l=Math.abs(c.value-a)/(o||1);l>this.config.anomalyThreshold&&e.push({experienceId:c.id,type:"outlier-reward",description:`${i} value ${c.value.toFixed(2)} is ${l.toFixed(1)} std deviations from mean`,deviation:l})}}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 xm(u,t,e){await u.set(`learning:strategy:current:${t}`,e,{namespace:"learning-optimization",persist:!0})}function Pm(u,t){let e=u.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 km(u){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":be.filter(e=>e!=="learning-optimization"),"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:be.filter(e=>e!=="coordination")}[u]||[]}function Im(u){let t=[],e=new Set;for(let r of u){if(e.has(r.id))continue;let i=[r];e.add(r.id);for(let n of u)e.has(n.id)||r.type===n.type&&r.domain===n.domain&&qv(r.context,n.context)&&(i.push(n),e.add(n.id));i.length>=2&&t.push(i)}return t}function qv(u,t){return u.tags.some(e=>t.tags.includes(e))}function Dm(u,t,e){let r=JSON.stringify({patternCount:u.length,knowledgeCount:t.length,strategyCount:e.length,patternIds:u.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)}M();var Fr=R.create("learning-optimization/consensus");async function Mm(u,t,e,r){let i=V({id:v(),type:"pattern-recommendation",confidence:t,description:`Verify pattern recommendation: ${u.name} (${u.type}) for domain ${u.domain}`,payload:u,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"?(Fr.info(`Pattern recommendation '${u.name}' verified by consensus`),!0):(Fr.warn(`Pattern recommendation '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Fm(u,t,e,r){let i=V({id:v(),type:"optimization-suggestion",confidence:t,description:`Verify optimization: ${u.metric} from ${u.currentValue} to ${u.targetValue} via ${u.strategy}`,payload:u,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"?(Fr.info(`Optimization suggestion for '${u.metric}' verified by consensus`),!0):(Fr.warn(`Optimization suggestion for '${u.metric}' NOT verified`),!1)}return!0}async function Lm(u,t,e,r){let i=V({id:v(),type:"cross-domain-insight",confidence:t,description:`Verify cross-domain insight: ${u.description}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:"high"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Cross-domain insight verified by consensus for ${u.targetDomains.length} target domains`),!0):(Fr.warn(`Cross-domain insight NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var Wv={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},Re=R.create("learning-optimization"),Ta=class extends Q{constructor(e,r,i,n={}){let s={...Wv,...n};super(e,"learning-optimization",s,{verifyFindingTypes:["pattern-recommendation","optimization-suggestion","cross-domain-insight"]});this.memory=r;this.agentCoordinator=i;this.learningService=new Gt({memory:r}),this.transferService=new Ht(r),this.optimizerService=new Wt(r),this.productionIntel=new jt(r)}memory;agentCoordinator;learningService;transferService;optimizerService;productionIntel;sona=null;dreamScheduler=null;async onInitialize(){try{this.sona=await me({domain:"learning-optimization",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.5}),Re.info("PersistentSONAEngine initialized for pattern learning")}catch(e){Re.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),Re.warn("Continuing without SONA pattern persistence"),this.sona=null}if(this.config.enableDreamScheduler)try{let e=await Sl();await e.initialize(),this.dreamScheduler=Rl({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(),Re.info("DreamScheduler initialized and started")}catch{Re.warn("Failed to initialize DreamScheduler:")}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){if(await this.saveWorkflowState(),this.dreamScheduler){try{await this.dreamScheduler.dispose(),Re.info("DreamScheduler disposed")}catch(e){Re.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){Re.error("Error closing SONA engine:",e instanceof Error?e:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async runLearningCycle(e){let r=v();try{if(this.startWorkflow(r,"learning-cycle"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, using conservative strategy for learning cycle"),this.minCutMixin.shouldPauseOperations())return p(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),p(i.error);this.addAgentToWorkflow(r,i.value);let n=_e.lastNDays(1),s=await this.getExperiencesForDomain(e,n),a=s.success?s.value:[];this.updateWorkflowProgress(r,20);let o=await this.learningService.mineExperiences(e,n),c=o.success?o.value.patterns.length:0;this.updateWorkflowProgress(r,50);let l=0,d=[];if(a.length>=10){let h={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(e),w=await this.optimizerService.optimizeStrategy(b,h,a);w.success&&(l=1,d.push({metric:h.metric,before:this.calculateMetricValue(a,h.metric),after:w.value.optimizedStrategy.expectedOutcome[h.metric]||0,percentChange:w.value.improvement*100}))}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 g={domain:e,experiencesProcessed:a.length,patternsLearned:c,strategiesOptimized:l,knowledgeGenerated:m,improvements:d};return this.config.publishEvents&&c>0&&await this.publishPatternConsolidated(c,[e]),f(g)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async optimizeAllStrategies(){let e=v();try{if(this.startWorkflow(e,"optimization"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, using conservative optimization strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Optimization paused: topology is in critical state"));let r={},i=0,n=0,s=0,a=be.filter(c=>c!=="learning-optimization");for(let c=0;c<a.length;c++){let l=a[c];this.updateWorkflowProgress(e,Math.round(c/a.length*100));let d=_e.lastNDays(7),m=await this.getExperiencesForDomain(l,d);if(!m.success||m.value.length<10)continue;let g=m.value,h={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(l),w=await this.optimizerService.optimizeStrategy(b,h,g);w.success&&(i++,n+=w.value.improvement,s++,r[l]={strategiesOptimized:1,avgImprovement:w.value.improvement,bestStrategy:w.value.optimizedStrategy},await this.storeStrategy(l,w.value.optimizedStrategy))}this.completeWorkflow(e);let o={domainsOptimized:s,totalStrategies:i,avgImprovement:i>0?n/i:0,byDomain:r};return this.config.publishEvents&&i>0&&await this.publishOptimizationApplied(o),f(o)}catch(r){return this.failWorkflow(e,String(r)),p(y(r))}}async shareCrossDomainLearnings(){let e=v();try{if(this.startWorkflow(e,"transfer"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, limiting cross-domain transfer scope"),this.minCutMixin.shouldPauseOperations())return p(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),p(o.error);let c=o.value;for(let m of c){let g=this.getRelatedDomains(m.domain);for(let h of g){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/(c.length*2)*100))}let l=await this.learningService.getPatternStats();if(l.success){let m=l.value.topPatterns;if(m.length>=2){let g=this.findSimilarPatterns(m);for(let h of g)h.length>=2&&(await this.learningService.consolidatePatterns(h.map(w=>w.id))).success&&n++}}this.completeWorkflow(e);let d={knowledgeShared:r,domainsUpdated:i,transferSuccessRate:s>0?a/s:1,newPatternsCreated:n};return this.config.publishEvents&&r>0&&await this.publishTransferCompleted(d),f(d)}catch(r){return this.failWorkflow(e,String(r)),p(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=_e.lastNDays(1),a=0;for(let b of be){let w=await this.getExperiencesForDomain(b,s);w.success&&(a+=w.value.length)}let o=await this.productionIntel.getProductionHealth(),c=o.success?o.value.trends:[],l=await this.productionIntel.getRecentMilestones(5),d=l.success?l.value:[],m=r?r.avgSuccessRate*.6+r.avgConfidence*.4:.5,g=[];if(r){let b=Object.entries(r.byDomain).filter(([w,C])=>C>0).map(([w,C])=>({domain:w,score:C})).sort((w,C)=>C.score-w.score);g.push(...b.slice(0,3).map(w=>w.domain))}let h={overallLearningRate:m,totalPatterns:r?.totalPatterns||0,totalKnowledge:n,experiencesLast24h:a,topPerformingDomains:g,learningTrend:c,recentMilestones:d};return f(h)}catch(e){return p(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()}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=v();try{this.startWorkflow(r,"export");let i=e||be,n=[],s=[],a=[];for(let m of i){let g=await this.memory.search("learning:pattern:*",500);for(let h of g){let b=await this.memory.get(h);b&&i.includes(b.domain)&&n.push(b)}this.updateWorkflowProgress(r,Math.round(n.length/100*30))}let o=await this.transferService.queryKnowledge({limit:1e3});if(o.success)for(let m of o.value)i.includes(m.domain)&&s.push(m);this.updateWorkflowProgress(r,60);let c=await this.memory.search("learning:strategy:optimized:*",200);for(let m of c){let g=await this.memory.get(m);g&&i.includes(g.domain)&&a.push(g)}this.updateWorkflowProgress(r,90);let l=this.calculateChecksum(n,s,a);return this.completeWorkflow(r),f({version:"1.0.0",exportedAt:new Date,patterns:n,knowledge:s,strategies:a,checksum:l})}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async importModels(e){let r=v();try{if(this.startWorkflow(r,"import"),this.calculateChecksum(e.patterns,e.knowledge,e.strategies)!==e.checksum)return this.failWorkflow(r,"Checksum mismatch"),p(new Error("Import failed: checksum mismatch"));let n=0,s=0,a=0,o=[];for(let l of e.patterns){let d=await this.memory.get(`learning:pattern:${l.id}`);d?d.confidence<l.confidence?(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++,o.push({type:"pattern",id:l.id,reason:"Existing pattern had lower confidence",resolution:"overwrite"})):o.push({type:"pattern",id:l.id,reason:"Existing pattern has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++),this.updateWorkflowProgress(r,Math.round(n/e.patterns.length*30))}for(let l of e.knowledge){let d=await this.memory.get(`learning:knowledge:shared:${l.id}`);d?l.version>d.version?(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++,o.push({type:"knowledge",id:l.id,reason:"Import has newer version",resolution:"overwrite"})):o.push({type:"knowledge",id:l.id,reason:"Existing knowledge is same or newer version",resolution:"skip"}):(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++),this.updateWorkflowProgress(r,30+Math.round(s/e.knowledge.length*30))}for(let l of e.strategies){let d=await this.memory.get(`learning:strategy:optimized:${l.id}`);d?l.confidence>d.confidence?(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),a++,o.push({type:"strategy",id:l.id,reason:"Import has higher confidence",resolution:"overwrite"})):o.push({type:"strategy",id:l.id,reason:"Existing strategy has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{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)),p(y(i))}}subscribeToEvents(){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("learning.ExperienceCaptured",this.handleExperienceCaptured.bind(this))}async handleTestRunCompleted(e){let{runId:r,passed:i,failed:n,duration:s}=e.payload,a=i+n>0?i/(i+n):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r},metrics:{passed:i,failed:n,duration:s}},result:{success:a>.8,outcome:{success_rate:a,passed:i,failed:n},duration:s},reward:a})}async handleCoverageGap(e){let{gapId:r,file:i,riskScore:n}=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,file:i},metrics:{riskScore:n}},result:{success:!0,outcome:{risk_score:n},duration:0},reward:1-n})}async handleQualityGate(e){let{gateId:r,passed:i}=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},metrics:{passed:i?1:0}},result:{success:i,outcome:{gate_passed:i?1:0},duration:0},reward:i?1:0})}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);Re.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=D(Ge.PatternConsolidated,"learning-optimization",i);await this.eventBus.publish(n)}async publishTransferCompleted(e){let r={sourceProject:"current",targetProject:"current",patternsTransferred:e.knowledgeShared,successRate:e.transferSuccessRate},i=D(Ge.TransferCompleted,"learning-optimization",r);await this.eventBus.publish(i)}async publishOptimizationApplied(e){let r=D(Ge.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=D(Ge.DreamCycleCompleted,"learning-optimization",a);await this.eventBus.publish(o),Re.info(`[LearningOptimizationCoordinator] Published dream cycle completion: ${n.length} insights for ${i} concepts`)}async spawnLearningAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(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=await this.memory.get(`learning:experience:${a}`);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:{success_rate:.8}}}async storeStrategy(e,r){await xm(this.memory,e,r)}calculateMetricValue(e,r){return Pm(e,r)}getRelatedDomains(e){return km(e)}findSimilarPatterns(e){return Im(e)}calculateChecksum(e,r,i){return Dm(e,r,i)}async verifyPatternRecommendation(e,r){return Mm(e,r,this.consensusMixin,this.domainName)}async verifyOptimizationSuggestion(e,r){return Fm(e,r,this.consensusMixin,this.domainName)}async verifyCrossDomainInsight(e,r){return Lm(e,r,this.consensusMixin,this.domainName)}};A();var tl=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;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,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 p(new Error("Coordinator not initialized"));let r=e.domain;return r?this.coordinator.runLearningCycle(r):p(new Error("Invalid run-learning-cycle payload: missing domain"))}],["optimize-strategies",async e=>this.coordinator?this.coordinator.optimizeAllStrategies():p(new Error("Coordinator not initialized"))],["share-learnings",async e=>this.coordinator?this.coordinator.shareCrossDomainLearnings():p(new Error("Coordinator not initialized"))],["learn-pattern",async e=>{if(!this.learningService)return p(new Error("Learning service not initialized"));let r=e.experiences;return!r||r.length===0?p(new Error("Invalid learn-pattern payload: missing experiences")):this.learningService.learnPattern(r)}],["query-knowledge",async e=>{if(!this.transferService)return p(new Error("Transfer service not initialized"));let r=e.query;return r?this.transferService.queryKnowledge(r):p(new Error("Invalid query-knowledge payload: missing query"))}]])}async onInitialize(){this.learningService=new Gt({memory:this.memory},this.pluginConfig.learningService),this.transferService=new Ht(this.memory,this.pluginConfig.transferService),this.optimizerService=new Wt(this.memory,this.pluginConfig.optimizerService),this.productionIntel=new jt(this.memory,this.pluginConfig.productionIntel),this.coordinator=new Ta(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,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})}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}),await this.productionIntel.recordMetric("test_success_rate",i,"ratio","test-execution",["automated"])}async handleCoverageGap(e){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})}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})}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})}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})}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}),p(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 $m(u,t,e,r){return new tl(u,t,e,r)}var rl=class extends W{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 be.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=Tl(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 Om(u,t,e,r){return new rl(u,t,e,r)}var Te={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"},il=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())}},Ae=new il;Ae.register(Te.createTestGeneratorService,u=>Tt(u));Ae.register(Te.CoverageAnalyzerService,u=>new mt(u));Ae.register(Te.SecurityScannerService,u=>new $e(u));Ae.register(Te.isSemgrepAvailable,Vi);Ae.register(Te.runSemgrepWithRules,Gs);Ae.register(Te.convertSemgrepFindings,Hs);Ae.register(Te.KnowledgeGraphService,u=>new Rt(u));A();Ae.register(Te.QualityAnalyzerService,u=>new Ye(u));A();M();A();var Ut={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"},Kv={maxConcurrentWorkflows:8,defaultTimeout:12e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Aa=R.create("enterprise-integration"),Ea=class extends Q{constructor(e,r,i,n={}){let s={...Kv,...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(),Aa.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=v();try{if(this.startWorkflow(r,"soap"),this.minCutMixin.shouldPauseOperations())return p(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)),p(y(i))}}async testSoapOperation(e,r,i){let n=v();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),p(s.error);let a={operation:r,passed:!0,request:JSON.stringify(i),response:"",validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.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)),p(y(s))}}async testMessageFlow(e,r){let i=v();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),p(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(D(Ut.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)),p(y(n))}}async testDlqHandling(e,r){let i=v();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),p(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)),p(y(n))}}async testBapiCall(e,r){let i=v();try{if(this.startWorkflow(i,"rfc"),this.minCutMixin.shouldPauseOperations())return p(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),p(n.error);let s={bapiName:r.name,passed:!0,returnMessages:[],exportValues:{},tableData:{},duration:0,transactionCommitted:!1};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.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)),p(y(n))}}async validateIdoc(e,r){let i=v();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),p(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(D(Ut.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)),p(y(n))}}async validateODataMetadata(e){let r=v();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),p(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)),p(y(i))}}async testODataEntitySet(e,r){let i=v();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),p(n.error);let s={entitySet:r,operation:"CRUD",passed:!0,statusCode:200,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.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)),p(y(n))}}async validateMessageFlow(e,r){let i=v();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),p(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(D(Ut.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)),p(y(n))}}async validateTransformation(e,r,i){let n=v();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),p(s.error))}catch(s){return this.failWorkflow(n,String(s)),p(y(s))}}async analyzeSod(e,r){let i=v();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),p(n.error);let s={userId:e,conflicts:[],riskScore:0,compliant:!0,recommendations:[]};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.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)),p(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=V({id:v(),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"?(Aa.info(`Finding verified by consensus: ${e.type}`),!0):(Aa.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"))&&Aa.info(`Middleware fault injection detected: ${r.targetService}`)}};var nl=class extends W{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 p(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?p(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 p(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):p(new Error("Invalid message-broker-test payload: missing testCase")):p(new Error("Invalid message-broker-test payload: missing brokerConfig"))}],["enterprise-integration:sap-rfc-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.connection,i=e.bapi;return!r||!i?p(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 p(new Error("Enterprise integration coordinator not initialized"));let r=e.definition,i=e.content;return!r||!i?p(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 p(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?p(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 p(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?p(new Error("Invalid esb-flow-test payload: missing transformInput or expectedOutput for transformation")):this.coordinator.validateTransformation(n,s,a)}return!r||!i?p(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 p(new Error("Enterprise integration coordinator not initialized"));let r=e.userId,i=e.ruleset;return!r||!i?p(new Error("Invalid sod-analyze payload: missing userId or ruleset")):this.coordinator.analyzeSod(r,i)}]])}async onInitialize(){this.coordinator=new Ea(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 Vm(u,t,e,r){return new nl(u,t,e,r)}var _m={"test-generation":(u,t,e)=>Eo(u,t,e),"test-execution":(u,t)=>Fu(u,t),"coverage-analysis":(u,t)=>Zo(u,t),"quality-assessment":(u,t,e)=>lc(u,t,e),"defect-intelligence":(u,t,e)=>hd(u,t,e),"requirements-validation":(u,t,e)=>bd(u,t,e),"code-intelligence":(u,t,e)=>Tc(u,t,e),"security-compliance":(u,t,e)=>Uc(u,t,e),"contract-testing":(u,t,e)=>om(u,t,e),"visual-accessibility":(u,t,e)=>Sm(u,t,e),"chaos-resilience":(u,t,e)=>Am(u,t,e),"learning-optimization":(u,t,e)=>$m(u,t,e),"enterprise-integration":(u,t,e)=>Vm(u,t,e),coordination:(u,t,e)=>Om(u,t,e)},Yv={maxConcurrentAgents:Lr.MAX_CONCURRENT_AGENTS,memoryBackend:"hybrid",hnswEnabled:!0,lazyLoading:!0,enabledDomains:[...be],dataDir:void 0},sl=class{_eventBus;_coordinator;_plugins;_memory;_config;_startTime;_initialized=!1;_loopTracker;constructor(t={}){this._config={...Yv,...t},this._startTime=new Date,this._memory=new Da,this._eventBus=new on,this._coordinator=new cn(this._config.maxConcurrentAgents),this._plugins=new qr(this._eventBus,this._memory,this._config.lazyLoading),this._loopTracker=new ln}get eventBus(){return this._eventBus}get coordinator(){return this._coordinator}get plugins(){return this._plugins}get memory(){return this._memory}async initialize(){if(this._initialized)return;let t=cl(),e=this._config.dataDir||Qt.join(t,".agentic-qe");if(xa.existsSync(e)||xa.mkdirSync(e,{recursive:!0}),this._config.memoryBackend==="memory"){let i=Qt.join(Pa("os").tmpdir(),`aqe-test-${Date.now()}-${Jv().slice(0,12)}.db`);await ul({dbPath:i})}else this._memory=new ll({sqlite:{path:Qt.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:ol.BUSY_TIMEOUT_MS},enableFallback:!0,defaultNamespace:"qe-kernel"}),this._plugins=new qr(this._eventBus,this._memory,this._config.lazyLoading);for(let i of this._config.enabledDomains){let n=_m[i];n&&this._plugins.registerFactory(i,async(s,a)=>Promise.resolve(n(s,a,this._coordinator)))}await this._memory.initialize();let r=new dn({agentId:"qe-kernel"});this._eventBus.registerMiddleware(r);try{let i=Qt.join(e,"plugins"),n=new dl({cacheDir:i}),a=new ml({cache:n}).resolveLoadOrder();for(let o of a.ordered){let c=o.manifest,l=n.get(c.name,c.version);if(!l)continue;let d=Qt.join(l.path,c.entryPoint);for(let m of c.domains){let g=m;if(_m[g])continue;this._plugins.registerFactory(g,async(b,w)=>{let C=await import(d),S=C.default??C.createPlugin;if(typeof S!="function")throw new Error(`Plugin "${c.name}" entry point must export a default function or "createPlugin" function`);return S(b,w,this._coordinator)})}}}catch{}this._config.lazyLoading||await this._plugins.loadAll();try{let{isAgentMemoryBranchingEnabled:i,isRVFPatternStoreEnabled:n}=await import("./feature-flags-6ALWBTHS.js");if(i()&&n()){let{getSharedRvfAdapter:s}=await import("./shared-rvf-adapter-BMFIVWMJ.js"),{AgentMemoryBranch:a}=await import("./agent-memory-branch-YCVTQEMJ.js"),o=s(e,384);if(o){let c=new a(o,{branchDir:Qt.join(e,"branches")});this._coordinator.setMemoryBranch(c)}}}catch{}try{let{getRvfMigrationStage:i}=await import("./feature-flags-6ALWBTHS.js"),n=i();if(n>=2){let{RvfMigrationCoordinator:s}=await import("./rvf-migration-coordinator-6BY5GI47.js");await s.getInstance({stage:n}).initialize()}}catch{}this._initialized=!0}async dispose(){await this._plugins.disposeAll(),await this._coordinator.dispose(),await this._eventBus.dispose(),await this._memory.dispose(),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}:`,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}:`,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 c of this._plugins.getLoaded()){let l=this._plugins.getPlugin(c);l&&(e[c]=l.getHealth())}for(let c of be)if(!e[c]){let l=this._config.enabledDomains.includes(c),d=this._config.lazyLoading&&l;e[c]={status:d?"healthy":l?"degraded":"healthy",agents:{total:0,active:0,idle:0,failed:0},errors:d?[]:l?["Domain not yet loaded"]:[],loaded:!1,lazyLoadable:d}}let r=this._coordinator.getActiveCount(),i=0,n=Number.MAX_SAFE_INTEGER;if(this._memory instanceof Da){let c=this._memory.getStats();i=c.entries+c.vectors}else i=0;let a=this._eventBus.getMiddlewares().find(c=>c.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:za.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:za.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 i6(u){return new sl(u)}export{Tt as a,mt as b,cr as c,dr as d,Ot as e,Sc as f,he as g,_e as h,zt as i,xc as j,qs as k,Tr as l,Ar as m,fa as n,Pr as o,Ir as p,Gt as q,Ht as r,Wt as s,Te as t,Ae as u,sl as v,i6 as w};