agentic-qe 3.9.11 → 3.9.13

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 (383) hide show
  1. package/.claude/agents/v3/qe-coverage-specialist.md +1 -1
  2. package/.claude/agents/v3/qe-fleet-commander.md +1 -1
  3. package/.claude/agents/v3/qe-pentest-validator.md +4 -2
  4. package/.claude/agents/v3/qe-queen-coordinator.md +1 -1
  5. package/.claude/agents/v3/qe-risk-assessor.md +1 -1
  6. package/.claude/agents/v3/qe-root-cause-analyzer.md +1 -1
  7. package/.claude/agents/v3/qe-security-auditor.md +4 -2
  8. package/.claude/agents/v3/qe-security-scanner.md +3 -1
  9. package/.claude/agents/v3/qe-test-architect.md +1 -1
  10. package/.claude/commands/aqe-costs.md +6 -6
  11. package/.claude/skills/.validation/schemas/skill-eval.schema.json +3 -0
  12. package/.claude/skills/.validation/test-data/sample-output.json +1 -1
  13. package/.claude/skills/a11y-ally/SKILL.md +1 -1
  14. package/.claude/skills/accessibility-testing/evals/accessibility-testing.yaml +1 -1
  15. package/.claude/skills/api-testing-patterns/evals/api-testing-patterns.yaml +2 -2
  16. package/.claude/skills/chaos-engineering-resilience/evals/chaos-engineering-resilience.yaml +1 -1
  17. package/.claude/skills/contract-testing/evals/contract-testing.yaml +2 -2
  18. package/.claude/skills/database-testing/evals/database-testing.yaml +2 -2
  19. package/.claude/skills/localization-testing/evals/localization-testing.yaml +1 -1
  20. package/.claude/skills/n8n-trigger-testing-strategies/evals/n8n-trigger-testing-strategies.yaml +1 -1
  21. package/.claude/skills/performance-testing/evals/performance-testing.yaml +1 -1
  22. package/.claude/skills/quality-metrics/evals/quality-metrics.yaml +1 -1
  23. package/.claude/skills/skills-manifest.json +1 -1
  24. package/.claude/skills/testability-scoring/evals/testability-scoring.yaml +2 -2
  25. package/CHANGELOG.md +29 -0
  26. package/assets/agents/v3/qe-coverage-specialist.md +1 -1
  27. package/assets/agents/v3/qe-fleet-commander.md +1 -1
  28. package/assets/agents/v3/qe-pentest-validator.md +4 -2
  29. package/assets/agents/v3/qe-queen-coordinator.md +1 -1
  30. package/assets/agents/v3/qe-risk-assessor.md +1 -1
  31. package/assets/agents/v3/qe-root-cause-analyzer.md +1 -1
  32. package/assets/agents/v3/qe-security-auditor.md +4 -2
  33. package/assets/agents/v3/qe-security-scanner.md +3 -1
  34. package/assets/agents/v3/qe-test-architect.md +1 -1
  35. package/assets/skills/.validation/schemas/skill-eval.schema.json +3 -0
  36. package/assets/skills/.validation/test-data/sample-output.json +1 -1
  37. package/assets/skills/a11y-ally/SKILL.md +1 -1
  38. package/assets/skills/accessibility-testing/evals/accessibility-testing.yaml +1 -1
  39. package/assets/skills/api-testing-patterns/evals/api-testing-patterns.yaml +2 -2
  40. package/assets/skills/chaos-engineering-resilience/evals/chaos-engineering-resilience.yaml +1 -1
  41. package/assets/skills/contract-testing/evals/contract-testing.yaml +2 -2
  42. package/assets/skills/database-testing/evals/database-testing.yaml +2 -2
  43. package/assets/skills/localization-testing/evals/localization-testing.yaml +1 -1
  44. package/assets/skills/n8n-trigger-testing-strategies/evals/n8n-trigger-testing-strategies.yaml +1 -1
  45. package/assets/skills/performance-testing/evals/performance-testing.yaml +1 -1
  46. package/assets/skills/quality-metrics/evals/quality-metrics.yaml +1 -1
  47. package/assets/skills/skills-manifest.json +1 -1
  48. package/assets/skills/testability-scoring/evals/testability-scoring.yaml +2 -2
  49. package/dist/adapters/claude-flow/detect.js +13 -0
  50. package/dist/cli/bundle.js +5 -5
  51. package/dist/cli/chunks/adapter-VP3WBXE5.js +2 -0
  52. package/dist/cli/chunks/{agent-booster-wasm-ERBGW3L7.js → agent-booster-wasm-3RBPTJAU.js} +2 -2
  53. package/dist/cli/chunks/{agent-handler-G5WC5V6J.js → agent-handler-XV45GCWC.js} +2 -2
  54. package/dist/cli/chunks/{agent-memory-branch-XAM3NPTO.js → agent-memory-branch-V6EXWWMY.js} +2 -2
  55. package/dist/cli/chunks/aqe-learning-engine-ASPPEOKQ.js +2 -0
  56. package/dist/cli/chunks/{audit-QW4RPP6W.js → audit-WXFI4AC4.js} +2 -2
  57. package/dist/cli/chunks/base-SIAOYPTD.js +2 -0
  58. package/dist/cli/chunks/{better-sqlite3-JNLN3EQY.js → better-sqlite3-23MIVVHF.js} +2 -2
  59. package/dist/cli/chunks/{brain-handler-YXCEHA2J.js → brain-handler-LQUMAACV.js} +3 -3
  60. package/dist/cli/chunks/{branch-enumerator-ZJUGC2OB.js → branch-enumerator-HE37VX7G.js} +2 -2
  61. package/dist/cli/chunks/{browser-RLRS7JBO.js → browser-3VG5M7WM.js} +2 -2
  62. package/dist/cli/chunks/browser-workflow-BG3M3RZU.js +2 -0
  63. package/dist/cli/chunks/{chunk-E5XSCY5J.js → chunk-2RTGP76Y.js} +2 -2
  64. package/dist/cli/chunks/{chunk-YSNVBAUR.js → chunk-3AOWTHLS.js} +2 -2
  65. package/dist/cli/chunks/{chunk-W2CIYDNQ.js → chunk-3I6KWFJT.js} +2 -2
  66. package/dist/cli/chunks/{chunk-PX2LQIS3.js → chunk-3IJ4NRJF.js} +2 -2
  67. package/dist/cli/chunks/{chunk-KUU5KPBS.js → chunk-3RM2VNYG.js} +2 -2
  68. package/dist/cli/chunks/{chunk-C6EG74P6.js → chunk-4MZZMWF6.js} +1 -1
  69. package/dist/cli/chunks/{chunk-KNG3K26M.js → chunk-4PCHU2X7.js} +1 -1
  70. package/dist/cli/chunks/{chunk-GF6KRBPQ.js → chunk-4VETZICF.js} +1 -1
  71. package/dist/cli/chunks/{chunk-TSXTP4MO.js → chunk-4WJ3BHCN.js} +3 -3
  72. package/dist/cli/chunks/{chunk-ZWGFOQOS.js → chunk-54A2LVKM.js} +2 -2
  73. package/dist/cli/chunks/{chunk-2PM3SD63.js → chunk-5TDHUYYF.js} +2 -2
  74. package/dist/cli/chunks/{chunk-TRCNODAD.js → chunk-67TMNSO3.js} +1 -1
  75. package/dist/cli/chunks/{chunk-7H46NSQI.js → chunk-6GYMFSPA.js} +2 -2
  76. package/dist/cli/chunks/{chunk-UMRNJLCT.js → chunk-6HSHLSGU.js} +2 -2
  77. package/dist/cli/chunks/{chunk-MFHKKNVZ.js → chunk-6LDRSG7C.js} +2 -2
  78. package/dist/cli/chunks/{chunk-2SPDBBGB.js → chunk-77GZ7LXL.js} +2 -2
  79. package/dist/cli/chunks/{chunk-7WTKRSJW.js → chunk-7HX2PMBB.js} +2 -2
  80. package/dist/cli/chunks/{chunk-LPTSNKCM.js → chunk-AEKTVLLF.js} +2 -2
  81. package/dist/cli/chunks/{chunk-L7LOSW5T.js → chunk-AOTEEGQA.js} +24 -24
  82. package/dist/cli/chunks/{chunk-QEBXLE7N.js → chunk-APQYMAKG.js} +4 -4
  83. package/dist/cli/chunks/{chunk-OUCFT3RT.js → chunk-AV23XNRL.js} +2 -2
  84. package/dist/cli/chunks/{chunk-JJS3OOFV.js → chunk-AXDGBI4Y.js} +1 -1
  85. package/dist/cli/chunks/{chunk-RRCFW2M3.js → chunk-AZPDX4KS.js} +2 -2
  86. package/dist/cli/chunks/{chunk-I3V5VPNQ.js → chunk-BE2DYHUB.js} +2 -2
  87. package/dist/cli/chunks/{chunk-CL6NRSRJ.js → chunk-BSTCXDVH.js} +1 -1
  88. package/dist/cli/chunks/{chunk-TI4B6LPH.js → chunk-BUIMIUJA.js} +1 -1
  89. package/dist/cli/chunks/{chunk-44P37G45.js → chunk-CF5EJGOV.js} +2 -2
  90. package/dist/cli/chunks/{chunk-2NQ37ZD2.js → chunk-CPRYUCPC.js} +1 -1
  91. package/dist/cli/chunks/{chunk-5BOJ7G3B.js → chunk-D22MEX2U.js} +2 -2
  92. package/dist/cli/chunks/{chunk-KK6MUW7H.js → chunk-DHYJMGKC.js} +1 -1
  93. package/dist/cli/chunks/{chunk-NEI3CUGT.js → chunk-DY5JRJXV.js} +3 -3
  94. package/dist/cli/chunks/{chunk-Y5YE6LVE.js → chunk-E7P6GAD7.js} +2 -2
  95. package/dist/cli/chunks/{chunk-NMJFMH4E.js → chunk-EBQUXPIG.js} +2 -2
  96. package/dist/cli/chunks/{chunk-VMBRYYYH.js → chunk-EC2CI3ZC.js} +2 -2
  97. package/dist/cli/chunks/{chunk-IFVGKXD2.js → chunk-ERGY45RL.js} +1 -1
  98. package/dist/cli/chunks/{chunk-KE5INK6G.js → chunk-ES6CEZG2.js} +1 -1
  99. package/dist/cli/chunks/{chunk-XBG6EFDT.js → chunk-F74IVEON.js} +2 -2
  100. package/dist/cli/chunks/{chunk-MQTFPGGG.js → chunk-FEGITTAE.js} +1 -1
  101. package/dist/cli/chunks/{chunk-YZNN62EM.js → chunk-FHWDVN65.js} +2 -2
  102. package/dist/cli/chunks/{chunk-TIKBMCDQ.js → chunk-FLML5IT7.js} +2 -2
  103. package/dist/cli/chunks/{chunk-7CSQKBZM.js → chunk-FS4TPAAA.js} +1 -1
  104. package/dist/cli/chunks/{chunk-V45UPEEM.js → chunk-GHAEDZDE.js} +2 -2
  105. package/dist/cli/chunks/{chunk-KXNVYDJF.js → chunk-GKRKCJ6D.js} +2 -2
  106. package/dist/cli/chunks/{chunk-4DHHTDMU.js → chunk-H53V7GI3.js} +1 -1
  107. package/dist/cli/chunks/{chunk-Y5WIREMP.js → chunk-HEHGQM2H.js} +23 -23
  108. package/dist/cli/chunks/{chunk-5QQVR2PJ.js → chunk-HHRUXDLT.js} +2 -2
  109. package/dist/cli/chunks/{chunk-BMDH76Z5.js → chunk-HJHFGPGP.js} +2 -2
  110. package/dist/cli/chunks/{chunk-NU5DOYGG.js → chunk-HRD7LL7Q.js} +2 -2
  111. package/dist/cli/chunks/{chunk-FOONOTJJ.js → chunk-HXLAXSEM.js} +2 -2
  112. package/dist/cli/chunks/{chunk-YIZNQK5R.js → chunk-I6O4MVEY.js} +4 -4
  113. package/dist/cli/chunks/{chunk-L4TU4IIE.js → chunk-IQGVQBVS.js} +1 -1
  114. package/dist/cli/chunks/{chunk-NWUOACDR.js → chunk-JOCR5TWI.js} +2 -2
  115. package/dist/cli/chunks/chunk-JV7HKHQS.js +2 -0
  116. package/dist/cli/chunks/{chunk-P5GOHOPL.js → chunk-KULWZMVC.js} +3 -3
  117. package/dist/cli/chunks/{chunk-WUDYOEEV.js → chunk-LHZLH6I4.js} +2 -2
  118. package/dist/cli/chunks/{chunk-I2HIQGZ2.js → chunk-LRHJOYKY.js} +3 -3
  119. package/dist/cli/chunks/{chunk-P6O43I72.js → chunk-MXT7YUOZ.js} +2 -2
  120. package/dist/cli/chunks/{chunk-JG6GFIR4.js → chunk-OBDM6OJL.js} +1 -1
  121. package/dist/cli/chunks/{chunk-O374BYD4.js → chunk-OGHIQCJU.js} +2 -2
  122. package/dist/cli/chunks/{chunk-WGKNSWGX.js → chunk-OHG6SNIA.js} +2 -2
  123. package/dist/cli/chunks/{chunk-TFK7FDC4.js → chunk-OJGR56BP.js} +2 -2
  124. package/dist/cli/chunks/{chunk-PRUG76TG.js → chunk-OKCI6BNZ.js} +2 -2
  125. package/dist/cli/chunks/{chunk-XS7YNHNG.js → chunk-OM7A3YC3.js} +2 -2
  126. package/dist/cli/chunks/{chunk-QL5O27ES.js → chunk-OP54A7C6.js} +2 -2
  127. package/dist/cli/chunks/{chunk-C4BDVGMS.js → chunk-OUNZPHTA.js} +1 -1
  128. package/dist/cli/chunks/{chunk-N3LKRXKM.js → chunk-Q3MQYATA.js} +2 -2
  129. package/dist/cli/chunks/{chunk-HGPK3IIX.js → chunk-Q7TWE55T.js} +3 -3
  130. package/dist/cli/chunks/{chunk-GOWDJPOX.js → chunk-QHCOAG7D.js} +1 -1
  131. package/dist/cli/chunks/{chunk-G3XXEPHS.js → chunk-QIE76ERL.js} +1 -1
  132. package/dist/cli/chunks/{chunk-F2OCIVD2.js → chunk-QKTB5FZP.js} +2 -2
  133. package/dist/cli/chunks/{chunk-NKUPM5KQ.js → chunk-QNUVC6OX.js} +1 -1
  134. package/dist/cli/chunks/{chunk-XIJ6LU5G.js → chunk-R4B2B6MZ.js} +2 -2
  135. package/dist/cli/chunks/{chunk-22OWZHSK.js → chunk-RMNZSGTE.js} +2 -2
  136. package/dist/cli/chunks/{chunk-ZM7WJNQY.js → chunk-RURYOWWU.js} +1 -1
  137. package/dist/cli/chunks/{chunk-5RDXUTEB.js → chunk-RYPUA6E2.js} +2 -2
  138. package/dist/cli/chunks/{chunk-TEHFGVQG.js → chunk-SI7AQK7I.js} +2 -2
  139. package/dist/cli/chunks/{chunk-RI5IUJ2E.js → chunk-SL66MHDM.js} +1 -1
  140. package/dist/cli/chunks/{chunk-5XQLA5PW.js → chunk-SSZMISGC.js} +2 -2
  141. package/dist/cli/chunks/{chunk-LKYO7SZ7.js → chunk-TNQBHQFH.js} +2 -2
  142. package/dist/cli/chunks/{chunk-7BYZSHCI.js → chunk-TOS3PI5Q.js} +1 -1
  143. package/dist/cli/chunks/{chunk-QRQV2KJ3.js → chunk-TPTKR5ZO.js} +1 -1
  144. package/dist/cli/chunks/{chunk-VQIBPHLI.js → chunk-TRJRRJV3.js} +1 -1
  145. package/dist/cli/chunks/{chunk-ZGWNU6V6.js → chunk-TU3JIH3U.js} +5 -5
  146. package/dist/cli/chunks/{chunk-CV3KHYEY.js → chunk-TVASP2E6.js} +2 -2
  147. package/dist/cli/chunks/{chunk-2DSXKIGI.js → chunk-TWRGM5TY.js} +2 -2
  148. package/dist/cli/chunks/chunk-UCCNB75R.js +3 -0
  149. package/dist/cli/chunks/{chunk-DZZKBPOK.js → chunk-UDIRBCZW.js} +1 -1
  150. package/dist/cli/chunks/{chunk-6RU5DG36.js → chunk-V2CV6J2A.js} +2 -2
  151. package/dist/cli/chunks/{chunk-AIHD3V62.js → chunk-V6UODTBP.js} +1 -1
  152. package/dist/cli/chunks/{chunk-LLC3GJXO.js → chunk-VCJP7HQG.js} +2 -2
  153. package/dist/cli/chunks/chunk-VHSDZEYF.js +2 -0
  154. package/dist/cli/chunks/{chunk-YGZOCUJM.js → chunk-VJN7NQGI.js} +9 -9
  155. package/dist/cli/chunks/{chunk-F6ADG6BA.js → chunk-VLZBQ3XN.js} +2 -2
  156. package/dist/cli/chunks/{chunk-C5QJV576.js → chunk-VU7ENCSU.js} +2 -2
  157. package/dist/cli/chunks/{chunk-KFNPCKTB.js → chunk-VVVIRGO7.js} +2 -2
  158. package/dist/cli/chunks/chunk-VWEGO7BY.js +2 -0
  159. package/dist/cli/chunks/{chunk-K6S2C76B.js → chunk-W2YCNX4O.js} +2 -2
  160. package/dist/cli/chunks/{chunk-Z5CFWIET.js → chunk-W6LEOFA4.js} +2 -2
  161. package/dist/cli/chunks/{chunk-YBVFSBYN.js → chunk-WQGP5ULD.js} +2 -2
  162. package/dist/cli/chunks/{chunk-S37G7A6J.js → chunk-WQIB5ERQ.js} +2 -2
  163. package/dist/cli/chunks/{chunk-NDLYVPON.js → chunk-WVWB7K6H.js} +1 -1
  164. package/dist/cli/chunks/{chunk-7D352FKW.js → chunk-X3UVXJIK.js} +2 -2
  165. package/dist/cli/chunks/{chunk-K33CP3M4.js → chunk-XV42SKJD.js} +2 -2
  166. package/dist/cli/chunks/{chunk-C3W4M7UY.js → chunk-XXQYSDLV.js} +2 -2
  167. package/dist/cli/chunks/chunk-Y2ONHWXI.js +2 -0
  168. package/dist/cli/chunks/{chunk-WY4RNWWV.js → chunk-Y7YSJD4I.js} +2 -2
  169. package/dist/cli/chunks/{chunk-DKJZW6KO.js → chunk-YBKSENTJ.js} +3 -3
  170. package/dist/cli/chunks/{chunk-N5EQ3Q63.js → chunk-YCQ2GHFH.js} +2 -2
  171. package/dist/cli/chunks/{chunk-R5FOT2GW.js → chunk-YCTGWMCP.js} +3 -3
  172. package/dist/cli/chunks/{chunk-F57L5LEP.js → chunk-YYQVSVBO.js} +2 -2
  173. package/dist/cli/chunks/{chunk-STVZ2TBG.js → chunk-Z6F4GRXY.js} +1 -1
  174. package/dist/cli/chunks/chunk-ZN7KPIJW.js +2 -0
  175. package/dist/cli/chunks/{chunk-QWWYIHND.js → chunk-ZS5BM2EE.js} +2 -2
  176. package/dist/cli/chunks/{chunk-6V7446OP.js → chunk-ZUW3KVML.js} +2 -2
  177. package/dist/cli/chunks/chunk-ZXJNX5D2.js +2 -0
  178. package/dist/cli/chunks/{ci-3W7NMONI.js → ci-FEEIAOQN.js} +2 -2
  179. package/dist/cli/chunks/{ci-output-S3L4ODFZ.js → ci-output-2WMUTORB.js} +2 -2
  180. package/dist/cli/chunks/{circuit-breaker-2KWBO7XA.js → circuit-breaker-MFEE23XA.js} +2 -2
  181. package/dist/cli/chunks/claude-flow-setup-6D655INK.js +2 -0
  182. package/dist/cli/chunks/client-LMOHUGOA.js +2 -0
  183. package/dist/cli/chunks/{cline-installer-EJZWTH4O.js → cline-installer-5PIYMPAG.js} +2 -2
  184. package/dist/cli/chunks/{code-M5S5TNSV.js → code-ACS453WG.js} +2 -2
  185. package/dist/cli/chunks/{code-index-extractor-YKAU2SIV.js → code-index-extractor-5SERI6TM.js} +2 -2
  186. package/dist/cli/chunks/{codex-installer-2RO7UPOC.js → codex-installer-WCUUWHP5.js} +2 -2
  187. package/dist/cli/chunks/{completions-6X4AQ43R.js → completions-6WFG3FPJ.js} +2 -2
  188. package/dist/cli/chunks/{complexity-analyzer-TVSEUC4O.js → complexity-analyzer-IFZEFCB6.js} +2 -2
  189. package/dist/cli/chunks/{continuedev-installer-OPFGF74I.js → continuedev-installer-RW6FEEND.js} +2 -2
  190. package/dist/cli/chunks/{copilot-installer-RRL4SCGA.js → copilot-installer-UZPE65RL.js} +2 -2
  191. package/dist/cli/chunks/{cost-tracker-XBNJ7WKR.js → cost-tracker-2R4FT6TY.js} +2 -2
  192. package/dist/cli/chunks/{coverage-FPJJTRAR.js → coverage-ZUC5U47P.js} +3 -3
  193. package/dist/cli/chunks/cross-domain-router-IZB5ZMXO.js +2 -0
  194. package/dist/cli/chunks/{cursor-installer-OPY7SFFC.js → cursor-installer-7JBZT7JZ.js} +2 -2
  195. package/dist/cli/chunks/{daemon-S3ZA7RT3.js → daemon-YNF54UYB.js} +3 -3
  196. package/dist/cli/chunks/{dag-attention-scheduler-AOAJOWRN.js → dag-attention-scheduler-MS7D2NFM.js} +2 -2
  197. package/dist/cli/chunks/{detect-3F2HT32S.js → detect-UHOSHYVB.js} +2 -2
  198. package/dist/cli/chunks/{domain-handler-SCWOCRON.js → domain-handler-BVW4AX7O.js} +2 -2
  199. package/dist/cli/chunks/{domain-transfer-4I3QTX44.js → domain-transfer-PA2ENF3D.js} +2 -2
  200. package/dist/cli/chunks/dream-SAPSS25B.js +2 -0
  201. package/dist/cli/chunks/esm-node-FTBUMV4L.js +2 -0
  202. package/dist/cli/chunks/{eval-M46NFR6V.js → eval-Y3ODM7JU.js} +2 -2
  203. package/dist/cli/chunks/{fast-paths-I2NAO6KL.js → fast-paths-DYQ5NC4Y.js} +2 -2
  204. package/dist/cli/chunks/{feature-flags-NQHRPIUT.js → feature-flags-V34UZPHG.js} +2 -2
  205. package/dist/cli/chunks/{feature-flags-PPFEWUVO.js → feature-flags-YMMGYWT3.js} +2 -2
  206. package/dist/cli/chunks/{file-discovery-WHHTABIG.js → file-discovery-75ZHSK4G.js} +2 -2
  207. package/dist/cli/chunks/{fleet-O5C6B37V.js → fleet-DD2CFGJL.js} +3 -3
  208. package/dist/cli/chunks/{gnn-wrapper-RYIYJINN.js → gnn-wrapper-UXM3L5LV.js} +2 -2
  209. package/dist/cli/chunks/{heartbeat-handler-NUE27AHM.js → heartbeat-handler-ANHRYXNS.js} +4 -4
  210. package/dist/cli/chunks/{heartbeat-scheduler-COBJE65L.js → heartbeat-scheduler-HYVMXCXT.js} +2 -2
  211. package/dist/cli/chunks/hnsw-adapter-CBDRZLXX.js +2 -0
  212. package/dist/cli/chunks/hnsw-index-EOJG4VF4.js +2 -0
  213. package/dist/cli/chunks/{hnsw-legacy-bridge-4YLY2WU2.js → hnsw-legacy-bridge-IFUEUOVF.js} +2 -2
  214. package/dist/cli/chunks/{hnswlib-node-GCYY3MVY.js → hnswlib-node-GYVDPTWU.js} +2 -2
  215. package/dist/cli/chunks/{hooks-F3ZDOXBU.js → hooks-R3DQNG2F.js} +6 -6
  216. package/dist/cli/chunks/hybrid-router-MSCQ2XGU.js +2 -0
  217. package/dist/cli/chunks/{hypergraph-engine-7P7HDFAU.js → hypergraph-engine-3TKB5O7T.js} +2 -2
  218. package/dist/cli/chunks/{hypergraph-handler-L2PIBHKZ.js → hypergraph-handler-4APYID2S.js} +3 -3
  219. package/dist/cli/chunks/impact-analyzer-C2TXXYPC.js +2 -0
  220. package/dist/cli/chunks/{init-handler-6FQSEU3G.js → init-handler-E7B2GKH3.js} +6 -6
  221. package/dist/cli/chunks/init-wizard-IQV7SBMW.js +2 -0
  222. package/dist/cli/chunks/kernel-NJOPFGK7.js +2 -0
  223. package/dist/cli/chunks/{kilocode-installer-F2OCU37B.js → kilocode-installer-WY6VTFSA.js} +2 -2
  224. package/dist/cli/chunks/{kiro-installer-NXSCDS3D.js → kiro-installer-SCNF3JXD.js} +4 -4
  225. package/dist/cli/chunks/knowledge-graph-EUMGCQPH.js +2 -0
  226. package/dist/cli/chunks/{learning-X2WZCNO2.js → learning-Y4OZJFBV.js} +3 -3
  227. package/dist/cli/chunks/{llm-router-LG3AFXW4.js → llm-router-RBKYYHBJ.js} +5 -5
  228. package/dist/cli/chunks/{load-N4TOWO47.js → load-FY64UGHV.js} +2 -2
  229. package/dist/cli/chunks/load-test-LBYVVG35.js +2 -0
  230. package/dist/cli/chunks/{mcp-L6GELR4I.js → mcp-6VMQOWMX.js} +2 -2
  231. package/dist/cli/chunks/{memory-XWVTSHTR.js → memory-Y5RO4PGM.js} +5 -5
  232. package/dist/cli/chunks/memory-backend-NQMJKHCQ.js +2 -0
  233. package/dist/cli/chunks/{memory-handlers-N4HCIXM6.js → memory-handlers-CMMVHHPG.js} +2 -2
  234. package/dist/cli/chunks/multi-model-executor-JO3MNMPZ.js +14 -0
  235. package/dist/cli/chunks/{opencode-installer-MID5ZQNA.js → opencode-installer-WQBTY6JT.js} +2 -2
  236. package/dist/cli/chunks/{orchestrator-HIOP5K2H.js → orchestrator-4J7OSNSG.js} +6 -6
  237. package/dist/cli/chunks/{pipeline-DXEZV7FN.js → pipeline-63T6HN72.js} +2 -2
  238. package/dist/cli/chunks/{platform-LDZ6HBEA.js → platform-UJMD4EPZ.js} +2 -2
  239. package/dist/cli/chunks/{plugin-XPQBUDKJ.js → plugin-NDOZ63JW.js} +2 -2
  240. package/dist/cli/chunks/{prime-radiant-advanced-wasm-OVJE7LH7.js → prime-radiant-advanced-wasm-ELGHVIFI.js} +2 -2
  241. package/dist/cli/chunks/protocol-executor-ZSWPG5SU.js +2 -0
  242. package/dist/cli/chunks/{protocol-handler-BI37HYPC.js → protocol-handler-KYERIMVF.js} +2 -2
  243. package/dist/cli/chunks/{prove-4A65UZVW.js → prove-ATSSBP4Z.js} +2 -2
  244. package/dist/cli/chunks/provider-manager-YYMIF23V.js +24 -0
  245. package/dist/cli/chunks/qe-reasoning-bank-4RLPRCGF.js +2 -0
  246. package/dist/cli/chunks/{quality-4RQ3D3JL.js → quality-2AGJSJW6.js} +2 -2
  247. package/dist/cli/chunks/queen-coordinator-KQ673NYE.js +2 -0
  248. package/dist/cli/chunks/{real-embeddings-GT7AC5MU.js → real-embeddings-H36GVXMI.js} +2 -2
  249. package/dist/cli/chunks/{roocode-installer-L77GZ3ZK.js → roocode-installer-PMRBAY7O.js} +2 -2
  250. package/dist/cli/chunks/router-UBNV4H5S.js +2 -0
  251. package/dist/cli/chunks/routing-feedback-BMMGZ346.js +2 -0
  252. package/dist/cli/chunks/{routing-handler-3GKAOO3V.js → routing-handler-Z7VZSDXW.js} +2 -2
  253. package/dist/cli/chunks/{ruvector-commands-JG4JJJIE.js → ruvector-commands-N3FZ3ZEE.js} +2 -2
  254. package/dist/cli/chunks/{rvf-dual-writer-HSJJLGC7.js → rvf-dual-writer-L5DQHUF3.js} +2 -2
  255. package/dist/cli/chunks/{rvf-migration-adapter-YKJNIXE6.js → rvf-migration-adapter-NPGFA3SL.js} +2 -2
  256. package/dist/cli/chunks/{rvf-migration-coordinator-ROE2JI6M.js → rvf-migration-coordinator-MCJDNKXG.js} +2 -2
  257. package/dist/cli/chunks/rvf-native-adapter-LXBCTTVF.js +2 -0
  258. package/dist/cli/chunks/safe-db-FFSPBUAK.js +2 -0
  259. package/dist/cli/chunks/schedule-2MOMNZ6B.js +2 -0
  260. package/dist/cli/chunks/scheduler-5VGVANFG.js +2 -0
  261. package/dist/cli/chunks/{security-Q46N26CF.js → security-TX7TXUGI.js} +3 -3
  262. package/dist/cli/chunks/shared-rvf-adapter-6JWYF7WV.js +2 -0
  263. package/dist/cli/chunks/{shared-rvf-dual-writer-3HAS2G2C.js → shared-rvf-dual-writer-6K3ZAG7P.js} +2 -2
  264. package/dist/cli/chunks/sqlite-persistence-LCOAORK7.js +2 -0
  265. package/dist/cli/chunks/{status-handler-LMQZIGFN.js → status-handler-MIRLQRNN.js} +2 -2
  266. package/dist/cli/chunks/{structural-health-DTU6QRF5.js → structural-health-CIHASLUE.js} +2 -2
  267. package/dist/cli/chunks/{sync-QIUCA4J6.js → sync-FGLAP7EK.js} +2 -2
  268. package/dist/cli/chunks/{task-handler-PVZ5GTKK.js → task-handler-7HMPRCHY.js} +2 -2
  269. package/dist/cli/chunks/{task-handlers-W34B2327.js → task-handlers-DQLQCLCT.js} +2 -2
  270. package/dist/cli/chunks/{test-JQJAOFZO.js → test-JKDO5ZHU.js} +4 -4
  271. package/dist/cli/chunks/{test-scheduling-4ZE5MPNY.js → test-scheduling-2YKZ7PVZ.js} +3 -3
  272. package/dist/cli/chunks/{token-bootstrap-GL5WJ5SI.js → token-bootstrap-C7UUPMQN.js} +2 -2
  273. package/dist/cli/chunks/{token-usage-BUSEAXEB.js → token-usage-2RVIPCY4.js} +2 -2
  274. package/dist/cli/chunks/{transformers-FLJ4PR2F.js → transformers-UEMAGHQ5.js} +2 -2
  275. package/dist/cli/chunks/{tree-sitter-wasm-parser-VHFVZOVZ.js → tree-sitter-wasm-parser-MELABICK.js} +2 -2
  276. package/dist/cli/chunks/{types-DD6ZWJZW.js → types-5B4RD7ZV.js} +2 -2
  277. package/dist/cli/chunks/unified-memory-CZCWZUFP.js +2 -0
  278. package/dist/cli/chunks/unified-memory-hnsw-QEOXVSOZ.js +2 -0
  279. package/dist/cli/chunks/unified-persistence-HGZAYZGP.js +2 -0
  280. package/dist/cli/chunks/{validate-RAX2MQKU.js → validate-CHDG7SC3.js} +2 -2
  281. package/dist/cli/chunks/{validate-swarm-7FDYRKAC.js → validate-swarm-LB7GORKE.js} +2 -2
  282. package/dist/cli/chunks/{vibium-FUESVL6F.js → vibium-ZMC4G2YA.js} +2 -2
  283. package/dist/cli/chunks/visual-security-ITKF4E4Z.js +2 -0
  284. package/dist/cli/chunks/{web-tree-sitter-DNSKYDCS.js → web-tree-sitter-THNO6S2V.js} +2 -2
  285. package/dist/cli/chunks/{windsurf-installer-YA244VF3.js → windsurf-installer-LRB43BPX.js} +2 -2
  286. package/dist/cli/chunks/{witness-chain-SGGPG6VR.js → witness-chain-JC5UBXPM.js} +2 -2
  287. package/dist/cli/chunks/witness-chain-SYFYXQD3.js +2 -0
  288. package/dist/cli/chunks/{workflow-TCQSFBBE.js → workflow-Q4IYQ6F2.js} +4 -4
  289. package/dist/cli/chunks/workflow-orchestrator-GZS2O3KW.js +2 -0
  290. package/dist/cli/chunks/{wrappers-44R4HXVW.js → wrappers-WSSLMFSE.js} +2 -2
  291. package/dist/cli/commands/claude-flow-setup.js +1 -29
  292. package/dist/cli/commands/llm-router.js +3 -3
  293. package/dist/coordination/consensus/providers/claude-provider.d.ts +3 -3
  294. package/dist/coordination/consensus/providers/claude-provider.js +6 -3
  295. package/dist/coordination/task-executor.js +5 -5
  296. package/dist/domains/chaos-resilience/services/chaos-engineer.js +3 -3
  297. package/dist/domains/code-intelligence/services/knowledge-graph.js +5 -5
  298. package/dist/domains/constants.d.ts +3 -3
  299. package/dist/domains/constants.js +3 -3
  300. package/dist/domains/contract-testing/services/contract-validator.js +3 -3
  301. package/dist/domains/coverage-analysis/services/coverage-analyzer.js +5 -5
  302. package/dist/domains/coverage-analysis/services/gap-detector.js +5 -5
  303. package/dist/domains/defect-intelligence/services/defect-predictor.js +5 -5
  304. package/dist/domains/defect-intelligence/services/root-cause-analyzer.js +5 -5
  305. package/dist/domains/learning-optimization/services/learning-coordinator.js +3 -3
  306. package/dist/domains/quality-assessment/services/deployment-advisor.js +5 -5
  307. package/dist/domains/quality-assessment/services/quality-analyzer.js +5 -5
  308. package/dist/domains/requirements-validation/services/requirements-validator.js +5 -5
  309. package/dist/domains/security-compliance/services/scanners/sast-scanner.js +5 -5
  310. package/dist/domains/test-execution/services/test-executor.js +3 -3
  311. package/dist/domains/test-generation/services/test-generator.js +5 -5
  312. package/dist/domains/visual-accessibility/services/visual-tester.js +3 -3
  313. package/dist/init/init-wizard-steps.js +1 -1
  314. package/dist/init/kiro-installer.js +8 -8
  315. package/dist/init/phases/12-verification.js +1 -1
  316. package/dist/init/settings-merge.js +2 -0
  317. package/dist/integrations/agentic-flow/model-router/types.js +8 -8
  318. package/dist/mcp/bundle.js +204 -204
  319. package/dist/mcp/security/sampling-server.js +1 -1
  320. package/dist/routing/advisor/multi-model-executor.d.ts +6 -2
  321. package/dist/routing/advisor/multi-model-executor.js +19 -3
  322. package/dist/routing/security/cyber-pin.d.ts +58 -0
  323. package/dist/routing/security/cyber-pin.js +75 -0
  324. package/dist/shared/llm/cost-tracker.js +5 -0
  325. package/dist/shared/llm/effort-resolver.d.ts +79 -0
  326. package/dist/shared/llm/effort-resolver.js +128 -0
  327. package/dist/shared/llm/interfaces.d.ts +11 -1
  328. package/dist/shared/llm/metrics/cost-metrics.js +1 -1
  329. package/dist/shared/llm/model-mapping.js +31 -0
  330. package/dist/shared/llm/model-registry.d.ts +40 -0
  331. package/dist/shared/llm/model-registry.js +126 -2
  332. package/dist/shared/llm/provider-manager.js +1 -1
  333. package/dist/shared/llm/providers/bedrock.js +9 -7
  334. package/dist/shared/llm/providers/claude.js +31 -4
  335. package/dist/shared/llm/router/agent-router-config.js +16 -16
  336. package/dist/shared/llm/router/hybrid-router.js +18 -1
  337. package/dist/shared/llm/router/routing-rules.js +9 -9
  338. package/dist/shared/llm/router/types.js +29 -29
  339. package/dist/shared/llm/translation/message-formatter.js +3 -3
  340. package/package.json +1 -1
  341. package/dist/cli/chunks/adapter-LDF6QG2T.js +0 -2
  342. package/dist/cli/chunks/aqe-learning-engine-4BL4TKWF.js +0 -2
  343. package/dist/cli/chunks/base-KJWQLVQN.js +0 -2
  344. package/dist/cli/chunks/browser-workflow-CWRD6MPO.js +0 -2
  345. package/dist/cli/chunks/chunk-5Z3K47TT.js +0 -2
  346. package/dist/cli/chunks/chunk-7J3CK3UY.js +0 -2
  347. package/dist/cli/chunks/chunk-C2HPZ65V.js +0 -2
  348. package/dist/cli/chunks/chunk-GEXHAKJ3.js +0 -2
  349. package/dist/cli/chunks/chunk-IURQ4SKQ.js +0 -3
  350. package/dist/cli/chunks/chunk-JDJRCINX.js +0 -2
  351. package/dist/cli/chunks/claude-flow-setup-NXRU3CZJ.js +0 -2
  352. package/dist/cli/chunks/client-6QLRJHON.js +0 -2
  353. package/dist/cli/chunks/cross-domain-router-Z4NI2VT3.js +0 -2
  354. package/dist/cli/chunks/dream-ICDONOKV.js +0 -2
  355. package/dist/cli/chunks/esm-node-PH6TIFQ6.js +0 -2
  356. package/dist/cli/chunks/hnsw-adapter-5BSHU4UF.js +0 -2
  357. package/dist/cli/chunks/hnsw-index-KX6DATRE.js +0 -2
  358. package/dist/cli/chunks/hybrid-router-ZKOXVYVB.js +0 -2
  359. package/dist/cli/chunks/impact-analyzer-KNWIKJVU.js +0 -2
  360. package/dist/cli/chunks/init-wizard-VKUUCD2T.js +0 -2
  361. package/dist/cli/chunks/kernel-LRGVOUOH.js +0 -2
  362. package/dist/cli/chunks/knowledge-graph-7O4ACKK7.js +0 -2
  363. package/dist/cli/chunks/load-test-MWJ46OOI.js +0 -2
  364. package/dist/cli/chunks/memory-backend-XNNH47PJ.js +0 -2
  365. package/dist/cli/chunks/multi-model-executor-QVV6JZYD.js +0 -14
  366. package/dist/cli/chunks/protocol-executor-C4VLLOXH.js +0 -2
  367. package/dist/cli/chunks/provider-manager-MAP3LEV2.js +0 -24
  368. package/dist/cli/chunks/qe-reasoning-bank-ALMRMCX6.js +0 -2
  369. package/dist/cli/chunks/queen-coordinator-PJMDHNCR.js +0 -2
  370. package/dist/cli/chunks/router-5EMK2VI4.js +0 -2
  371. package/dist/cli/chunks/routing-feedback-GM474EAA.js +0 -2
  372. package/dist/cli/chunks/rvf-native-adapter-L6TVMXZG.js +0 -2
  373. package/dist/cli/chunks/safe-db-D2JVWU7V.js +0 -2
  374. package/dist/cli/chunks/schedule-ATMJHEWX.js +0 -2
  375. package/dist/cli/chunks/scheduler-FFU5HTXP.js +0 -2
  376. package/dist/cli/chunks/shared-rvf-adapter-KBGYVHKT.js +0 -2
  377. package/dist/cli/chunks/sqlite-persistence-CDUAJ4WV.js +0 -2
  378. package/dist/cli/chunks/unified-memory-H55OLMCH.js +0 -2
  379. package/dist/cli/chunks/unified-memory-hnsw-EL4ZOWLV.js +0 -2
  380. package/dist/cli/chunks/unified-persistence-SW3GZQOI.js +0 -2
  381. package/dist/cli/chunks/visual-security-7RHKMS2T.js +0 -2
  382. package/dist/cli/chunks/witness-chain-PBFNSR2Z.js +0 -2
  383. package/dist/cli/chunks/workflow-orchestrator-KQP277ZB.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.11");process.exit(0)}
2
- import{b as t4,c as r4}from"./chunk-TI4B6LPH.js";import{a as i4}from"./chunk-P5GOHOPL.js";import{a as o4}from"./chunk-GOWDJPOX.js";import{d as p4}from"./chunk-MFHKKNVZ.js";import{a as L,b as U0,c as Pu,d as dt,e as mt,f as Dt,g as Ee,h as Yi,i as Yu}from"./chunk-YBVFSBYN.js";import{a as s4,c as l4}from"./chunk-7CSQKBZM.js";import{a as Xi,b as ht,c as un,d as Q0,e as en,f as an,g as Y0,h as tn,i as pt}from"./chunk-OUCFT3RT.js";import{a as Yl}from"./chunk-CL6NRSRJ.js";import{a as E4,b as d4,e as m4}from"./chunk-R5FOT2GW.js";import{o as D4,s as h4}from"./chunk-YIZNQK5R.js";import{a as e4}from"./chunk-N5EQ3Q63.js";import{e as At,l as yt,q as o3}from"./chunk-K33CP3M4.js";import{a as n4,j as Ku}from"./chunk-N3LKRXKM.js";import{c as X0}from"./chunk-W2CIYDNQ.js";import{g as c4}from"./chunk-5RDXUTEB.js";import{a as ea}from"./chunk-CV3KHYEY.js";import{a as M,b as Z0,c as Re,d as Pe,e as ua,f as ju,g as ze}from"./chunk-NEI3CUGT.js";import{c as Ct}from"./chunk-2PM3SD63.js";import{b as nn}from"./chunk-NU5DOYGG.js";import{f as n3}from"./chunk-7WTKRSJW.js";import{c as Et,d as a4}from"./chunk-Z5CFWIET.js";import{f as u4,o as c0}from"./chunk-NMJFMH4E.js";import{a as N}from"./chunk-7J3CK3UY.js";import{c as B}from"./chunk-5QQVR2PJ.js";import{b as rn,d as gt}from"./chunk-VMBRYYYH.js";import{b as T,d as J}from"./chunk-LLC3GJXO.js";import{a as Fu,b as p,c as m}from"./chunk-G3XXEPHS.js";import{a as k,b as g,c as S}from"./chunk-YSNVBAUR.js";import{f as A}from"./chunk-L4TU4IIE.js";import{a as Qi}from"./chunk-WY4RNWWV.js";import{a as K,b as Du,d as cu}from"./chunk-F57L5LEP.js";import{a as Xl,c as J0,d as Ui,e as Zi}from"./chunk-QWWYIHND.js";import{a as ce,b as we,c as lt,d as ct}from"./chunk-RRCFW2M3.js";import{S as Qu,b as Te,n as Me}from"./chunk-K6S2C76B.js";import{a as Ji,c as Zu,e as s0,g as l0}from"./chunk-IFVGKXD2.js";var f4={};s0(f4,{ALL_SUPPORTED_LANGUAGES:()=>h3,ALL_TEST_FRAMEWORKS:()=>Bt,DEFAULT_FRAMEWORKS:()=>cn,FRAMEWORK_ALIASES:()=>y4,FRAMEWORK_TO_LANGUAGE:()=>D3,LANGUAGE_FILE_EXTENSIONS:()=>x4,getLanguageFromExtension:()=>de,resolveFrameworkAlias:()=>kt});function kt(s){let e=s.toLowerCase().trim();return Bt.includes(e)?e:y4[e]}function de(s){return x4[s.startsWith(".")?s:`.${s}`]}var cn,y4,D3,x4,Bt,h3,d0=Zu(()=>{"use strict";cn={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"},y4={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"},D3={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"},x4={".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"},Bt=["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"],h3=["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]});function Oo(s,e={}){let{additionalContext:u,sourceCode:a,includeEvidence:t=!0,includeRemediation:r=!0,maxLength:i=8e3}=e,n=[];n.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.13");process.exit(0)}
2
+ import{b as t4,c as r4}from"./chunk-BUIMIUJA.js";import{a as i4}from"./chunk-KULWZMVC.js";import{a as o4}from"./chunk-QHCOAG7D.js";import{d as p4}from"./chunk-6LDRSG7C.js";import{a as L,b as U0,c as Pu,d as dt,e as mt,f as Dt,g as Ee,h as Yi,i as Yu}from"./chunk-WQGP5ULD.js";import{a as s4,c as l4}from"./chunk-FS4TPAAA.js";import{a as Xi,b as ht,c as un,d as Q0,e as en,f as an,g as Y0,h as tn,i as pt}from"./chunk-AV23XNRL.js";import{a as Yl}from"./chunk-BSTCXDVH.js";import{a as E4,b as d4,e as m4}from"./chunk-YCTGWMCP.js";import{o as D4,s as h4}from"./chunk-I6O4MVEY.js";import{a as e4}from"./chunk-YCQ2GHFH.js";import{e as At,l as yt,q as o3}from"./chunk-XV42SKJD.js";import{a as n4,j as Ku}from"./chunk-Q3MQYATA.js";import{c as X0}from"./chunk-3I6KWFJT.js";import{g as c4}from"./chunk-RYPUA6E2.js";import{a as ea}from"./chunk-TVASP2E6.js";import{a as M,b as Z0,c as Re,d as Pe,e as ua,f as ju,g as ze}from"./chunk-DY5JRJXV.js";import{c as Ct}from"./chunk-5TDHUYYF.js";import{b as nn}from"./chunk-HRD7LL7Q.js";import{f as n3}from"./chunk-7HX2PMBB.js";import{c as Et,d as a4}from"./chunk-W6LEOFA4.js";import{f as u4,o as c0}from"./chunk-EBQUXPIG.js";import{a as N}from"./chunk-Y2ONHWXI.js";import{c as B}from"./chunk-HHRUXDLT.js";import{b as rn,d as gt}from"./chunk-EC2CI3ZC.js";import{b as T,d as J}from"./chunk-VCJP7HQG.js";import{a as Fu,b as p,c as m}from"./chunk-QIE76ERL.js";import{a as k,b as g,c as S}from"./chunk-3AOWTHLS.js";import{f as A}from"./chunk-IQGVQBVS.js";import{a as Qi}from"./chunk-Y7YSJD4I.js";import{a as K,b as Du,d as cu}from"./chunk-YYQVSVBO.js";import{a as Xl,c as J0,d as Ui,e as Zi}from"./chunk-ZS5BM2EE.js";import{a as ce,b as we,c as lt,d as ct}from"./chunk-AZPDX4KS.js";import{S as Qu,b as Te,n as Me}from"./chunk-W2YCNX4O.js";import{a as Ji,c as Zu,e as s0,g as l0}from"./chunk-ERGY45RL.js";var f4={};s0(f4,{ALL_SUPPORTED_LANGUAGES:()=>h3,ALL_TEST_FRAMEWORKS:()=>Bt,DEFAULT_FRAMEWORKS:()=>cn,FRAMEWORK_ALIASES:()=>y4,FRAMEWORK_TO_LANGUAGE:()=>D3,LANGUAGE_FILE_EXTENSIONS:()=>x4,getLanguageFromExtension:()=>de,resolveFrameworkAlias:()=>kt});function kt(s){let e=s.toLowerCase().trim();return Bt.includes(e)?e:y4[e]}function de(s){return x4[s.startsWith(".")?s:`.${s}`]}var cn,y4,D3,x4,Bt,h3,d0=Zu(()=>{"use strict";cn={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"},y4={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"},D3={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"},x4={".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"},Bt=["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"],h3=["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]});function Oo(s,e={}){let{additionalContext:u,sourceCode:a,includeEvidence:t=!0,includeRemediation:r=!0,maxLength:i=8e3}=e,n=[];n.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
 
@@ -69,7 +69,7 @@ ${Vo(s.content,500)}
69
69
  `)}function Vo(s,e){return s.length<=e?s:s.substring(0,e-3)+"..."}function _o(s){let e={assessment:"inconclusive",confidence:.5,reasoning:"",suggestions:[],parseSuccess:!1,rawResponse:s};try{let u=s.match(/ASSESSMENT:\s*(CONFIRMED|REJECTED|INCONCLUSIVE|NEEDS_CONTEXT|PARTIAL)/i);u&&(e.assessment=A6u(u[1].toUpperCase()));let a=s.match(/CONFIDENCE:\s*(\d+(?:\.\d+)?)\s*%?/i);a&&(e.confidence=Math.min(1,parseFloat(a[1])/100));let t=s.match(/SEVERITY:\s*(original|critical|high|medium|low|info)/i);t&&t[1].toLowerCase()!=="original"&&(e.suggestedSeverity=t[1].toLowerCase());let r=s.toUpperCase().indexOf("REASONING:"),i=s.toUpperCase().indexOf("SUGGESTIONS:");if(r!==-1){let n=s.indexOf(`
70
70
  `,r),o=i!==-1?i:s.length;n!==-1&&n<o&&(e.reasoning=s.slice(n+1,o).trim())}if(e.reasoning||(e.reasoning=s),i!==-1){let n=s.indexOf(`
71
71
  `,i);n!==-1&&(e.suggestions=s.slice(n+1).split(`
72
- `).map(o=>o.replace(/^[-*]\s*/,"").trim()).filter(o=>o.length>0))}e.parseSuccess=u!==null}catch{e.reasoning=s,e.parseSuccess=!1}return e}function A6u(s){return{CONFIRMED:"confirmed",REJECTED:"rejected",INCONCLUSIVE:"inconclusive",NEEDS_CONTEXT:"needs-context",PARTIAL:"partial"}[s]||"inconclusive"}function Wo(s){let{modelId:e,modelVersion:u,parsedResponse:a,executionTime:t,tokenUsage:r,cost:i}=s,n=a.assessment==="confirmed"||a.assessment==="partial";return{modelId:e,modelVersion:u,agrees:n,assessment:a.assessment,confidence:a.confidence,reasoning:a.reasoning,suggestedSeverity:a.suggestedSeverity,suggestions:a.suggestions.length>0?a.suggestions:void 0,executionTime:t,tokenUsage:r,cost:i,votedAt:new Date}}function ya(s){let e=new Aa;return s&&s.forEach(u=>e.register(u)),e}var bu,Aa,Hu=Zu(()=>{"use strict";S();cu();bu=class{healthCache=null;healthCacheTtlMs=6e4;disposed=!1;async isAvailable(){if(this.disposed)return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(this.disposed)return{healthy:!1,error:"Provider has been disposed"};if(this.healthCache&&Date.now()-this.healthCache.timestamp<this.healthCacheTtlMs)return this.healthCache.result;try{let e=await this.performHealthCheck();return this.healthCache={result:e,timestamp:Date.now()},e}catch(e){let u={healthy:!1,error:k(e)};return this.healthCache={result:u,timestamp:Date.now()},u}}getCostPerToken(){return{...this.costPerToken}}getSupportedModels(){return[...this.supportedModels]}async dispose(){this.disposed=!0,this.healthCache=null}invalidateHealthCache(){this.healthCache=null}};Aa=class{providers=new Map;register(e){if(this.providers.has(e.id))throw new Error(`Provider with ID '${e.id}' is already registered`);this.providers.set(e.id,e)}unregister(e){return this.providers.delete(e)}get(e){return this.providers.get(e)}has(e){return this.providers.has(e)}getAll(){return Array.from(this.providers.values())}getIds(){return Array.from(this.providers.keys())}async getAvailable(){return(await Promise.all(this.getAll().map(async u=>({provider:u,available:await u.isAvailable()})))).filter(u=>u.available).map(u=>u.provider)}getByType(e){return this.getAll().filter(u=>u.type===e)}clear(){this.providers.clear()}async dispose(){await Promise.all(this.getAll().map(e=>e.dispose())),this.clear()}}});var Ot,cc=Zu(()=>{"use strict";Ot=class{latched=new Map;disabled=process.env.AQE_PROMPT_CACHE_LATCH==="false";latch(e,u){return this.disabled?(this.latched.set(e,u),!0):this.latched.has(e)?!1:(this.latched.set(e,u),!0)}get(e){return this.latched.get(e)}has(e){return this.latched.has(e)}reset(e){this.latched.delete(e)}resetAll(){this.latched.clear()}getSnapshot(){return Object.fromEntries(this.latched)}get size(){return this.latched.size}}});var Ec={};s0(Ec,{ClaudeModelProvider:()=>p0,createClaudeProvider:()=>$o});function $o(s){return new p0(s)}var p0,qo=Zu(()=>{"use strict";S();Hu();cc();p0=class extends bu{id="claude";name="Claude (Anthropic)";type="claude";costPerToken={input:3/1e6,output:15/1e6};supportedModels=["claude-3-5-sonnet-20241022","claude-3-5-sonnet-latest","claude-3-opus-20240229","claude-3-opus-latest"];config;apiKey;baseUrl;cacheLatch=new Ot;constructor(e={}){super();let u=e.apiKey||process.env.ANTHROPIC_API_KEY||"";if(!u)throw new Error("Claude API key is required. Provide via config.apiKey or ANTHROPIC_API_KEY environment variable.");this.apiKey=u,this.baseUrl=e.baseUrl||"https://api.anthropic.com",this.config={apiKey:u,defaultModel:e.defaultModel||"claude-3-5-sonnet-20241022",baseUrl:this.baseUrl,defaultTimeout:e.defaultTimeout||3e4,maxRetries:e.maxRetries??3,retryDelayMs:e.retryDelayMs||1e3,enableLogging:e.enableLogging||!1},this.updateCostForModel(this.config.defaultModel)}async complete(e,u){if(this.disposed)throw new Error("Provider has been disposed");let a=u?.model||this.config.defaultModel,t=u?.maxTokens||4096,r=u?.temperature??.7,i=u?.timeout||this.config.defaultTimeout,n=u?.systemPrompt||this.getDefaultSystemPrompt();this.cacheLatch.has("model")&&this.cacheLatch.get("model")!==a&&this.cacheLatch.reset("model"),this.cacheLatch.has("max_tokens")&&this.cacheLatch.get("max_tokens")!==t&&this.cacheLatch.reset("max_tokens"),this.cacheLatch.has("system")&&this.cacheLatch.get("system")!==n&&this.cacheLatch.reset("system"),this.cacheLatch.latch("model",a),this.cacheLatch.latch("max_tokens",t),this.cacheLatch.latch("system",n);let o=this.cacheLatch.get("model"),l=this.cacheLatch.get("max_tokens"),c=this.cacheLatch.get("system"),E={model:o,max_tokens:l,temperature:r,system:c,messages:[{role:"user",content:e}]};this.config.enableLogging&&console.log(`[Claude] Sending request to ${o}`);let d=null;for(let D=0;D<=this.config.maxRetries;D++)try{let h=await this.makeRequest(E,i);return this.config.enableLogging&&console.log(`[Claude] Received response (${h.usage.input_tokens} in, ${h.usage.output_tokens} out)`),h.content.filter(y=>y.type==="text").map(y=>y.text).join(`
72
+ `).map(o=>o.replace(/^[-*]\s*/,"").trim()).filter(o=>o.length>0))}e.parseSuccess=u!==null}catch{e.reasoning=s,e.parseSuccess=!1}return e}function A6u(s){return{CONFIRMED:"confirmed",REJECTED:"rejected",INCONCLUSIVE:"inconclusive",NEEDS_CONTEXT:"needs-context",PARTIAL:"partial"}[s]||"inconclusive"}function Wo(s){let{modelId:e,modelVersion:u,parsedResponse:a,executionTime:t,tokenUsage:r,cost:i}=s,n=a.assessment==="confirmed"||a.assessment==="partial";return{modelId:e,modelVersion:u,agrees:n,assessment:a.assessment,confidence:a.confidence,reasoning:a.reasoning,suggestedSeverity:a.suggestedSeverity,suggestions:a.suggestions.length>0?a.suggestions:void 0,executionTime:t,tokenUsage:r,cost:i,votedAt:new Date}}function ya(s){let e=new Aa;return s&&s.forEach(u=>e.register(u)),e}var bu,Aa,Hu=Zu(()=>{"use strict";S();cu();bu=class{healthCache=null;healthCacheTtlMs=6e4;disposed=!1;async isAvailable(){if(this.disposed)return!1;try{return(await this.healthCheck()).healthy}catch{return!1}}async healthCheck(){if(this.disposed)return{healthy:!1,error:"Provider has been disposed"};if(this.healthCache&&Date.now()-this.healthCache.timestamp<this.healthCacheTtlMs)return this.healthCache.result;try{let e=await this.performHealthCheck();return this.healthCache={result:e,timestamp:Date.now()},e}catch(e){let u={healthy:!1,error:k(e)};return this.healthCache={result:u,timestamp:Date.now()},u}}getCostPerToken(){return{...this.costPerToken}}getSupportedModels(){return[...this.supportedModels]}async dispose(){this.disposed=!0,this.healthCache=null}invalidateHealthCache(){this.healthCache=null}};Aa=class{providers=new Map;register(e){if(this.providers.has(e.id))throw new Error(`Provider with ID '${e.id}' is already registered`);this.providers.set(e.id,e)}unregister(e){return this.providers.delete(e)}get(e){return this.providers.get(e)}has(e){return this.providers.has(e)}getAll(){return Array.from(this.providers.values())}getIds(){return Array.from(this.providers.keys())}async getAvailable(){return(await Promise.all(this.getAll().map(async u=>({provider:u,available:await u.isAvailable()})))).filter(u=>u.available).map(u=>u.provider)}getByType(e){return this.getAll().filter(u=>u.type===e)}clear(){this.providers.clear()}async dispose(){await Promise.all(this.getAll().map(e=>e.dispose())),this.clear()}}});var Ot,cc=Zu(()=>{"use strict";Ot=class{latched=new Map;disabled=process.env.AQE_PROMPT_CACHE_LATCH==="false";latch(e,u){return this.disabled?(this.latched.set(e,u),!0):this.latched.has(e)?!1:(this.latched.set(e,u),!0)}get(e){return this.latched.get(e)}has(e){return this.latched.has(e)}reset(e){this.latched.delete(e)}resetAll(){this.latched.clear()}getSnapshot(){return Object.fromEntries(this.latched)}get size(){return this.latched.size}}});var Ec={};s0(Ec,{ClaudeModelProvider:()=>p0,createClaudeProvider:()=>$o});function $o(s){return new p0(s)}var p0,qo=Zu(()=>{"use strict";S();Hu();cc();p0=class extends bu{id="claude";name="Claude (Anthropic)";type="claude";costPerToken={input:3/1e6,output:15/1e6};supportedModels=["claude-sonnet-4-6","claude-opus-4-7","claude-haiku-4-5","claude-3-5-sonnet-20241022","claude-3-5-sonnet-latest","claude-3-opus-20240229","claude-3-opus-latest"];config;apiKey;baseUrl;cacheLatch=new Ot;constructor(e={}){super();let u=e.apiKey||process.env.ANTHROPIC_API_KEY||"";if(!u)throw new Error("Claude API key is required. Provide via config.apiKey or ANTHROPIC_API_KEY environment variable.");this.apiKey=u,this.baseUrl=e.baseUrl||"https://api.anthropic.com",this.config={apiKey:u,defaultModel:e.defaultModel||"claude-sonnet-4-6",baseUrl:this.baseUrl,defaultTimeout:e.defaultTimeout||3e4,maxRetries:e.maxRetries??3,retryDelayMs:e.retryDelayMs||1e3,enableLogging:e.enableLogging||!1},this.updateCostForModel(this.config.defaultModel)}async complete(e,u){if(this.disposed)throw new Error("Provider has been disposed");let a=u?.model||this.config.defaultModel,t=u?.maxTokens||4096,r=u?.temperature??.7,i=u?.timeout||this.config.defaultTimeout,n=u?.systemPrompt||this.getDefaultSystemPrompt();this.cacheLatch.has("model")&&this.cacheLatch.get("model")!==a&&this.cacheLatch.reset("model"),this.cacheLatch.has("max_tokens")&&this.cacheLatch.get("max_tokens")!==t&&this.cacheLatch.reset("max_tokens"),this.cacheLatch.has("system")&&this.cacheLatch.get("system")!==n&&this.cacheLatch.reset("system"),this.cacheLatch.latch("model",a),this.cacheLatch.latch("max_tokens",t),this.cacheLatch.latch("system",n);let o=this.cacheLatch.get("model"),l=this.cacheLatch.get("max_tokens"),c=this.cacheLatch.get("system"),E={model:o,max_tokens:l,temperature:r,system:c,messages:[{role:"user",content:e}]};this.config.enableLogging&&console.log(`[Claude] Sending request to ${o}`);let d=null;for(let D=0;D<=this.config.maxRetries;D++)try{let h=await this.makeRequest(E,i);return this.config.enableLogging&&console.log(`[Claude] Received response (${h.usage.input_tokens} in, ${h.usage.output_tokens} out)`),h.content.filter(y=>y.type==="text").map(y=>y.text).join(`
73
73
  `)}catch(h){if(d=g(h),this.isNonRetryableError(h))throw d;if(D<this.config.maxRetries){let C=this.config.retryDelayMs*Math.pow(2,D);this.config.enableLogging&&console.log(`[Claude] Retry ${D+1}/${this.config.maxRetries} after ${C}ms`),await this.sleep(C)}}throw new Error(`Claude completion failed after ${this.config.maxRetries+1} attempts: ${d?.message}`)}async makeRequest(e,u){let a=new AbortController,t=setTimeout(()=>a.abort(),u);try{let r=await fetch(`${this.baseUrl}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","anthropic-version":"2023-06-01","x-api-key":this.apiKey},body:JSON.stringify(e),signal:a.signal});if(!r.ok){let i=await r.json();throw new Error(`Claude API error (${r.status}): ${i.error.message}`)}return await r.json()}finally{clearTimeout(t)}}async performHealthCheck(){let e=Date.now();try{return await this.complete("Hello",{maxTokens:10,timeout:5e3}),{healthy:!0,latencyMs:Date.now()-e,availableModels:this.supportedModels}}catch(u){return{healthy:!1,error:k(u),availableModels:this.supportedModels}}}getDefaultSystemPrompt(){return`You are a security expert specializing in code security analysis and vulnerability assessment.
74
74
 
75
75
  Your role is to carefully analyze security findings and determine their validity. You should:
@@ -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 W2u}from"crypto";Zi();var on={LOOP_WARNING:"loop.warning",LOOP_DETECTED:"loop.detected"},xt=class{subscriptions=new Map;subscriptionsByEventType=new Map;subscriptionsByChannel=new Map;wildcardSubscriptions=new Set;eventHistory;maxHistorySize=Ui.MAX_HISTORY_SIZE;subscriptionCounter=0;middlewares=[];constructor(e=Ui.MAX_HISTORY_SIZE){this.maxHistorySize=e,this.eventHistory=new Yl(e)}registerMiddleware(e){this.middlewares.push(e),this.middlewares.sort((u,a)=>u.priority-a.priority)}removeMiddleware(e){let u=this.middlewares.findIndex(a=>a.name===e);return u>=0?(this.middlewares.splice(u,1),!0):!1}getMiddlewares(){return this.middlewares}async publish(e){let u=e;for(let o of this.middlewares)if(o.onEmit&&u&&(u=await o.onEmit(u),!u))return;this.eventHistory.push(u);let a=new Set,t=this.subscriptionsByEventType.get(u.type);if(t)for(let o of t)a.add(o);let r=this.subscriptionsByChannel.get(u.source);if(r)for(let o of r)a.add(o);for(let o of this.wildcardSubscriptions)a.add(o);let i=[];for(let o of a){let l=this.subscriptions.get(o);!l||!l.active||l.channel&&l.channel!==u.source||l.eventType!=="*"&&l.eventType!==u.type||i.push(l)}let n=u;for(let o of this.middlewares)if(o.onReceive&&n&&(n=await o.onReceive(n),!n))return;await Promise.allSettled(i.map(o=>o.handler(n)))}subscribe(e,u){let a=`sub_${++this.subscriptionCounter}`,t={id:a,eventType:e,handler:u,active:!0};return this.subscriptions.set(a,t),e==="*"?this.wildcardSubscriptions.add(a):(this.subscriptionsByEventType.has(e)||this.subscriptionsByEventType.set(e,new Set),this.subscriptionsByEventType.get(e).add(a)),{unsubscribe:()=>{t.active=!1,this.subscriptions.delete(a),e==="*"?this.wildcardSubscriptions.delete(a):this.subscriptionsByEventType.get(e)?.delete(a)},get active(){return t.active}}}subscribeToChannel(e,u){let a=`sub_${++this.subscriptionCounter}`,t={id:a,eventType:"*",channel:e,handler:u,active:!0};return this.subscriptions.set(a,t),this.subscriptionsByChannel.has(e)||this.subscriptionsByChannel.set(e,new Set),this.subscriptionsByChannel.get(e).add(a),{unsubscribe:()=>{t.active=!1,this.subscriptions.delete(a),this.subscriptionsByChannel.get(e)?.delete(a)},get active(){return t.active}}}async getHistory(e){let u=this.eventHistory.toArray();return e&&(e.eventTypes?.length&&(u=u.filter(a=>e.eventTypes.includes(a.type))),e.sources?.length&&(u=u.filter(a=>e.sources.includes(a.source))),e.fromTimestamp&&(u=u.filter(a=>a.timestamp>=e.fromTimestamp)),e.toTimestamp&&(u=u.filter(a=>a.timestamp<=e.toTimestamp)),e.correlationId&&(u=u.filter(a=>a.correlationId===e.correlationId)),e.limit&&(u=u.slice(-e.limit))),u}async dispose(){this.subscriptions.clear(),this.subscriptionsByEventType.clear(),this.subscriptionsByChannel.clear(),this.wildcardSubscriptions.clear(),this.eventHistory.clear(),this.middlewares=[]}};Zi();var ft=class{agents=new Map;maxAgents;memoryBranch=null;constructor(e=J0.MAX_CONCURRENT_AGENTS){this.maxAgents=e}setMemoryBranch(e){this.memoryBranch=e}async spawn(e){if(!this.canSpawn())return m(new Error(`Cannot spawn agent: maximum concurrent agents (${this.maxAgents}) reached. Active: ${this.getActiveCount()}`));let u=e.config??{};if(e.progressiveContext?.strategy==="predictive"||process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED==="true")try{let i=u.taskDescription||e.name||"",n=u.availableFiles||[];if(i&&n.length>0){let l=new sn(e.progressiveContext).predictFilesForTask(i,n);u={...u,availableFiles:l,contextFiles:l,initialFiles:l,progressiveContextApplied:!0}}}catch{}let t=A(),r={id:t,name:e.name,domain:e.domain,type:e.type,status:"running",capabilities:e.capabilities,config:u,startedAt:new Date};if(this.agents.set(t,r),this.memoryBranch)try{let i=this.memoryBranch.createBranch(t);r.config={...r.config,_memoryBranchPath:i.childPath,_memoryBranchRecordIngest:n=>{this.memoryBranch?.recordIngest(t,n)}}}catch(i){console.warn(`[AgentCoordinator] Memory branch creation failed for ${t}:`,i)}return p(t)}getStatus(e){return this.agents.get(e)?.status}listAgents(e){let u=Array.from(this.agents.values());return e&&(e.domain&&(u=u.filter(a=>a.domain===e.domain)),e.status&&(u=u.filter(a=>a.status===e.status)),e.type&&(u=u.filter(a=>a.type===e.type))),u.map(a=>({id:a.id,name:a.name,domain:a.domain,type:a.type,status:a.status,startedAt:a.startedAt}))}async stop(e){let u=this.agents.get(e);return u?u.status!=="running"?m(new Error(`Agent ${e} is not running (status: ${u.status})`)):(u.status="completed",u.completedAt=new Date,p(void 0)):m(new Error(`Agent not found: ${e}`))}getActiveCount(){return Array.from(this.agents.values()).filter(e=>e.status==="running"||e.status==="queued").length}canSpawn(){return this.getActiveCount()<this.maxAgents}async dispose(){let e=Array.from(this.agents.values()).filter(u=>u.status==="running");await Promise.all(e.map(u=>this.stop(u.id))),this.agents.clear()}markCompleted(e){let u=this.agents.get(e);u&&u.status==="running"&&(u.status="completed",u.completedAt=new Date,this.handleBranchOnComplete(e,"merge"))}markFailed(e){let u=this.agents.get(e);u&&u.status==="running"&&(u.status="failed",u.completedAt=new Date,this.handleBranchOnComplete(e,"discard"))}handleBranchOnComplete(e,u){if(!this.memoryBranch)return;let a=this.memoryBranch.getBranch(e);if(a)try{u==="merge"?this.memoryBranch.mergeBranch(a).catch(t=>{console.warn(`[AgentCoordinator] Branch merge failed for ${e}:`,t)}):this.memoryBranch.discardBranch(a)}catch(t){console.warn(`[AgentCoordinator] Branch ${u} failed for ${e}:`,t)}}cleanup(e=J0.DEFAULT_AGENT_TTL_MS){let u=Date.now(),a=0;for(let[t,r]of this.agents.entries())(r.status==="completed"||r.status==="failed")&&r.completedAt&&u-r.completedAt.getTime()>e&&(this.agents.delete(t),a++);return a}},s3={strategy:"full",maxInitialFiles:10,predictionThreshold:.7,trackFileRequests:!0},sn=class{config;fileRequests=[];preloadedFiles=new Set;constructor(e){this.config={...s3,...e}}isEnabled(){return process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED==="true"}predictFilesForTask(e,u){if(!this.isEnabled()||this.config.strategy==="full")return[...u];if(!e||e.trim().length===0)return u.slice(0,this.config.maxInitialFiles);if(u.length===0)return[];let a=this.extractKeywords(e);if(a.length===0)return u.slice(0,this.config.maxInitialFiles);let t=u.map(i=>({filePath:i,score:this.scoreFile(i,a)}));t.sort((i,n)=>n.score-i.score);let r=t.slice(0,this.config.maxInitialFiles).map(i=>i.filePath);return this.preloadedFiles=new Set(r),r}recordFileRequest(e){this.config.trackFileRequests&&this.fileRequests.push(e)}getPredictionAccuracy(){let e=this.preloadedFiles.size,u=this.fileRequests.filter(i=>i.wasPreloaded).length,a=new Set(this.fileRequests.map(i=>i.filePath)),t=[...a].filter(i=>this.preloadedFiles.has(i)).length,r=a.size>0?t/a.size:0;return{predicted:e,actuallyUsed:u,hitRate:r}}getFileRequestHistory(e){return e?this.fileRequests.filter(u=>u.agentId===e):[...this.fileRequests]}extractKeywords(e){let u=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"]),a=e.toLowerCase().split(/[\s\-_./\\,;:!?()[\]{}'"]+/).filter(t=>t.length>1&&!u.has(t));return[...new Set(a)]}scoreFile(e,u){let a=e.toLowerCase(),t=a.split(/[\\/.]/).filter(i=>i.length>0),r=0;for(let i of u)if(t.includes(i))r+=2;else if(a.includes(i))r+=1;else for(let n of t)if(n.startsWith(i)||i.startsWith(n)){r+=.5;break}return u.length>0?r/(u.length*2):0}};N();var l3=B.create("plugin-loader"),aa=class{constructor(e,u,a=!0){this.eventBus=e;this.memory=u}plugins=new Map;factories=new Map;loading=new Map;registerFactory(e,u){this.factories.set(e,u)}async load(e){let u=this.plugins.get(e);if(u)return u;let a=this.loading.get(e);if(a)return a;let t=this.factories.get(e);if(!t){let i=Array.from(this.factories.keys());throw new Error(`No factory registered for domain: ${e}
115
115
  This usually means the domain is not enabled in your config.
116
116
  Registered domains: ${i.join(", ")}
117
- Fix: Add '${e}' to domains.enabled in .agentic-qe/config.yaml, or run 'aqe init --auto-migrate' to enable all domains.`)}let r=this.loadPlugin(e,t);this.loading.set(e,r);try{let i=await r;return this.plugins.set(e,i),i}finally{this.loading.delete(e)}}async loadPlugin(e,u){let a=await u(this.eventBus,this.memory);for(let t of a.dependencies)this.isLoaded(t)||await this.load(t);return await a.initialize(),a}async unload(e){let u=this.plugins.get(e);if(u){for(let[a,t]of this.plugins.entries())if(t.dependencies.includes(e))throw new Error(`Cannot unload ${e}: domain ${a} depends on it`);await u.dispose(),this.plugins.delete(e)}}isLoaded(e){return this.plugins.has(e)}getLoaded(){return Array.from(this.plugins.keys())}async loadAll(){let e=Array.from(this.factories.keys()),u=this.topologicalSort(e);for(let a of u)await this.load(a)}topologicalSort(e){let u=[],a=new Set,t=new Set,r=i=>{if(a.has(i))return;if(t.has(i))throw new Error(`Circular dependency detected involving: ${i}`);t.add(i);let o=this.plugins.get(i)?.dependencies??[];for(let l of o)e.includes(l)&&r(l);t.delete(i),a.add(i),u.push(i)};for(let i of e)r(i);return u}getPlugin(e){return this.plugins.get(e)}async disposeAll(){let e=[...this.getLoaded()].reverse();for(let u of e)try{await this.unload(u)}catch(a){l3.debug("Plugin unload failed, force removing",{domain:u,error:a instanceof Error?a.message:String(a)}),this.plugins.delete(u)}}};ct();N();var ln=B.create("anti-drift-middleware"),c3={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 g4(s){let e=2166136261;for(let u=0;u<s.length;u++)e^=s.charCodeAt(u),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}var vt=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(e){this.config={...c3,...e}}trackCall(e,u,a){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return{isLoop:!1,callCount:1,signature:this.createSignature(u,a),action:"allow"};let t=this.createSignature(u,a);this.totalCallsTracked++,this.callHistory.has(e)||this.callHistory.set(e,[]);let r=this.callHistory.get(e);r.push(t);let i=Date.now()-this.config.windowMs,n=r.findIndex(l=>l.timestamp>=i);n>0?r.splice(0,n):n===-1&&(r.length=0,r.push(t));let o=r.filter(l=>l.hash===t.hash).length;return o>=this.config.maxIdenticalCalls?(this.loopsDetected++,{isLoop:!0,callCount:o,signature:t,action:"steer",steeringMessage:this.config.steeringMessage}):o===this.config.maxIdenticalCalls-1?{isLoop:!1,callCount:o,signature:t,action:"warn"}:{isLoop:!1,callCount:o,signature:t,action:"allow"}}getMetrics(){return{totalCallsTracked:this.totalCallsTracked,loopsDetected:this.loopsDetected}}clear(){this.callHistory.clear(),this.totalCallsTracked=0,this.loopsDetected=0}createSignature(e,u){let a=JSON.stringify(u??""),t=g4(a),r=`${e}:${a}`;return{hash:g4(r),toolName:e,argsFingerprint:t,timestamp:Date.now()}}},A4={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},E3={thresholds:A4,agentId:"unknown",maxHistorySize:200,fallbackDimension:64};function d3(s,e){let u=new Float64Array(e),a=2166136261,t=16777619;for(let n=0;n<s.length;n++){let o=s.charCodeAt(n);a^=o,a=Math.imul(a,16777619),t^=o,t=Math.imul(t,2166136261);let l=(a>>>0)%e;u[l]+=(t>>>0)/4294967295*2-1}let r=0;for(let n=0;n<e;n++)r+=u[n]*u[n];r=Math.sqrt(r);let i=new Array(e);for(let n=0;n<e;n++)i[n]=r===0?0:u[n]/r;return i}var C4=!1,E0=!1,Ft=null;async function m3(){if(C4)return E0;C4=!0;try{let s=await import("./real-embeddings-GT7AC5MU.js");if(typeof s.isTransformerAvailable=="function"&&s.isTransformerAvailable())Ft=s.computeRealEmbedding,E0=!0;else try{await s.computeRealEmbedding("probe"),Ft=s.computeRealEmbedding,E0=!0}catch(e){ln.debug("Transformer probe embedding failed",{error:e instanceof Error?e.message:String(e)}),E0=!1}}catch(s){ln.debug("Transformer module import failed",{error:s instanceof Error?s.message:String(s)}),E0=!1}return E0}var bt=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;constructor(e){this.config={...E3,...e,thresholds:{...A4,...e?.thresholds}}}async onEmit(e){let u=JSON.stringify(e.payload),a=await this.embed(u),t=this.resolveCategory(e.type),r=this.config.thresholds[t]??this.config.thresholds.default,i={embedding:a,driftThreshold:r,sourceAgentId:this.config.agentId,hopCount:0,emittedAt:Date.now()};return{...e,semanticFingerprint:i}}async onReceive(e){let u=e.semanticFingerprint;if(!u)return e;let a=JSON.stringify(e.payload),t=await this.embed(a),r=ce(t,u.embedding),n=1-r>u.driftThreshold;this.totalChecked++,this.similaritySum+=r;let o={drifted:n,cosineSimilarity:r,threshold:u.driftThreshold,eventType:e.type,hopCount:u.hopCount+1,checkedAt:Date.now()};if(this.history.push(o),this.history.length>this.config.maxHistorySize&&this.history.shift(),n)return this.driftCount++,await this.emitDriftEvent(e,o),null;let l={...u,hopCount:u.hopCount+1};return{...e,semanticFingerprint:l}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0}}validateConfig(){for(let[e,u]of Object.entries(this.config.thresholds))if(typeof u!="number"||u<0||u>1)return m(new Error(`Invalid threshold for "${e}": must be between 0 and 1, got ${u}`));return this.config.maxHistorySize<=0?m(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?m(new Error("fallbackDimension must be positive")):p(void 0)}async embed(e){return await m3()&&Ft?Ft(e):d3(e,this.config.fallbackDimension)}resolveCategory(e){let u=e.toLowerCase();for(let a of Object.keys(this.config.thresholds))if(a!=="default"&&u.includes(a))return a;return"default"}async emitDriftEvent(e,u){if(!this.config.onDriftDetected)return;let a={id:`drift-${e.id}-${Date.now()}`,type:"SemanticDriftDetected",timestamp:new Date,source:e.source,correlationId:e.correlationId,payload:{originalEventId:e.id,originalEventType:e.type,cosineSimilarity:u.cosineSimilarity,threshold:u.threshold,hopCount:u.hopCount,agentId:this.config.agentId}};try{await this.config.onDriftDetected(a)}catch(t){ln.debug("onDriftDetected callback failed",{error:t instanceof Error?t.message:String(t)})}}};Zi();c0();import*as o0 from"path";import*as qi from"fs";S();var U=class{constructor(e,u){this.eventBus=e;this.memory=u}_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(e){await this.onEvent(e)}async onInitialize(){}async onDispose(){}async onEvent(e){}subscribeToEvents(){}async publishEvent(e,u){let a={id:crypto.randomUUID(),type:e,timestamp:new Date,source:this.name,payload:u};await this.eventBus.publish(a)}updateHealth(e){this._health={...this._health,...e}}setMinCutBridge(e){this._minCutBridge=e,this.onMinCutBridgeSet(e)}getMinCutBridge(){return this._minCutBridge}setConsensusConfig(e){this._consensusConfig=e,this.onConsensusConfigSet(e)}getConsensusConfig(){return this._consensusConfig}setIntegrationConfig(e){e.minCutBridge&&this.setMinCutBridge(e.minCutBridge),e.consensusConfig&&this.setConsensusConfig(e.consensusConfig)}hasMinCutIntegration(){return this._minCutBridge!==void 0}hasConsensusEnabled(){return this._consensusConfig?.enabled===!0}onMinCutBridgeSet(e){}onConsensusConfigSet(e){}getTaskHandlers(){return new Map}canHandleTask(e){return this.getTaskHandlers().has(e)}async executeTask(e,u){let t=this.getTaskHandlers().get(e.taskType);return t?(this.runTaskAsync(e,t,u),p(void 0)):m(new Error(`Domain ${this.name} has no handler for task type: ${e.taskType}`))}async runTaskAsync(e,u,a){let t=Date.now();try{let r=await u(e.payload),i=Date.now()-t,n={taskId:e.taskId,success:r.success,data:r.success?r.value:void 0,error:r.success?void 0:r.error?.message,duration:i};if(await a(n),r.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=r.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(r){let i=Date.now()-t,n=k(r);await a({taskId:e.taskId,success:!1,error:n,duration:i}),this.updateHealth({lastActivity:new Date,errors:[...this._health.errors.slice(-9),n],agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),failed:this._health.agents.failed+1}})}}};N();S();N();import*as oc from"fs";import*as ga from"path";d0();import{randomBytes as p3,randomInt as me,randomUUID as g3}from"node:crypto";function v4(s){return p3(s).toString("hex")}var z={uuid:()=>g3(),email:()=>`user_${v4(3)}@example.com`,fullName:()=>{let s=["Alice","Bob","Carol","Dave","Eve","Frank"],e=["Smith","Jones","Lee","Garcia","Chen","Novak"];return`${s[me(s.length)]} ${e[me(e.length)]}`},url:()=>`https://example.com/${v4(4)}`,recentDate:()=>new Date(Date.now()-me(7*864e5)).toISOString(),phone:()=>`+1${String(me(2e9,9999999999))}`,streetAddress:()=>`${me(1,9999)} Main St`,word:()=>{let s=["alpha","bravo","charlie","delta","echo","foxtrot","golf","hotel"];return s[me(s.length)]},int:(s=1,e=100)=>{if(s>e){let u=s;s=e,e=u}return me(s,e+1)},float:(s=0,e=100,u=2)=>{if(s>e){let t=s;s=e,e=t}if(s===e)return s;let a=s+me(0,1000001)/1e6*(e-s);return Number(a.toFixed(u))}};var uu=class s{static NAME_VALUE_TABLE=[["id",()=>`'${z.uuid()}'`],["email",()=>`'${z.email()}'`],["name",()=>`'${z.fullName()}'`],["url",()=>`'${z.url()}'`],["date",()=>`new Date('${z.recentDate()}')`],["phone",()=>`'${z.phone()}'`],["address",()=>`'${z.streetAddress()}'`]];static TYPE_VALUE_TABLE=[["string",()=>`'${z.word()}'`],["number",()=>String(z.int(1,100))],["boolean",()=>"true"],["[]",()=>"[]"],["array",()=>"[]"],["object",()=>"{}"],["{",()=>"{}"],["function",()=>"() => {}"],["promise",()=>"Promise.resolve()"],["date",()=>"new Date()"]];generateTestValue(e){if(e.defaultValue)return e.defaultValue;let u=e.type?.toLowerCase()||"unknown",a=e.name.toLowerCase();for(let[t,r]of s.NAME_VALUE_TABLE)if(a.includes(t))return r();for(let[t,r]of s.TYPE_VALUE_TABLE)if(u.includes(t))return r();return`{} /* TODO: provide ${e.name}: ${e.type||"unknown"} */`}generateTestCasesForFunction(e){let u=[],a=e.parameters.map(l=>this.generateTestValue(l)).join(", "),t=e.isAsync?`await ${e.name}(${a})`:`${e.name}(${a})`,r=e.returnType==="void"||e.returnType==="Promise<void>",i="expect(result).toBeDefined();";if(!r){if(/^(is|has|can)[A-Z]/.test(e.name))i="expect(typeof result).toBe('boolean');";else if(/^(get|fetch|find)[A-Z]/.test(e.name))i="expect(result).not.toBeUndefined();";else if(/^(create|build|make)[A-Z]/.test(e.name))i="expect(result).toBeTruthy();";else if(e.returnType){let l=e.returnType.toLowerCase().replace(/promise<(.+)>/,"$1");l.includes("{")?i="expect(typeof result).toBe('object');":l==="boolean"?i="expect(typeof result).toBe('boolean');":l==="number"?i="expect(typeof result).toBe('number');":l==="string"?i="expect(typeof result).toBe('string');":l.includes("[]")||l.includes("array")?i="expect(Array.isArray(result)).toBe(true);":l.includes("boolean")?i="expect(typeof result).toBe('boolean');":l.includes("number")?i="expect(typeof result).toBe('number');":l.includes("string")&&(i="expect(typeof result).toBe('string');")}}u.push({description:"should handle valid input correctly",type:"happy-path",action:r?`${t};`:`const result = ${t};`,assertion:r?"// void function \u2014 no return value to assert":i});let n=e.body||"",o=/\bthrow\b/.test(n)||/\bvalidat/i.test(n);for(let l of e.parameters){if(!l.optional){let c=e.parameters.map(E=>E.name===l.name?"undefined":this.generateTestValue(E)).join(", ");if(o)u.push({description:`should handle undefined ${l.name}`,type:"error-handling",action:e.isAsync?`const action = async () => await ${e.name}(${c});`:`const action = () => ${e.name}(${c});`,assertion:"expect(action).toThrow();"});else{let E=e.isAsync?`await ${e.name}(${c})`:`${e.name}(${c})`;u.push({description:`should handle undefined ${l.name}`,type:"edge-case",action:e.isAsync?`let threw = false;
117
+ Fix: Add '${e}' to domains.enabled in .agentic-qe/config.yaml, or run 'aqe init --auto-migrate' to enable all domains.`)}let r=this.loadPlugin(e,t);this.loading.set(e,r);try{let i=await r;return this.plugins.set(e,i),i}finally{this.loading.delete(e)}}async loadPlugin(e,u){let a=await u(this.eventBus,this.memory);for(let t of a.dependencies)this.isLoaded(t)||await this.load(t);return await a.initialize(),a}async unload(e){let u=this.plugins.get(e);if(u){for(let[a,t]of this.plugins.entries())if(t.dependencies.includes(e))throw new Error(`Cannot unload ${e}: domain ${a} depends on it`);await u.dispose(),this.plugins.delete(e)}}isLoaded(e){return this.plugins.has(e)}getLoaded(){return Array.from(this.plugins.keys())}async loadAll(){let e=Array.from(this.factories.keys()),u=this.topologicalSort(e);for(let a of u)await this.load(a)}topologicalSort(e){let u=[],a=new Set,t=new Set,r=i=>{if(a.has(i))return;if(t.has(i))throw new Error(`Circular dependency detected involving: ${i}`);t.add(i);let o=this.plugins.get(i)?.dependencies??[];for(let l of o)e.includes(l)&&r(l);t.delete(i),a.add(i),u.push(i)};for(let i of e)r(i);return u}getPlugin(e){return this.plugins.get(e)}async disposeAll(){let e=[...this.getLoaded()].reverse();for(let u of e)try{await this.unload(u)}catch(a){l3.debug("Plugin unload failed, force removing",{domain:u,error:a instanceof Error?a.message:String(a)}),this.plugins.delete(u)}}};ct();N();var ln=B.create("anti-drift-middleware"),c3={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 g4(s){let e=2166136261;for(let u=0;u<s.length;u++)e^=s.charCodeAt(u),e=Math.imul(e,16777619);return(e>>>0).toString(16).padStart(8,"0")}var vt=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(e){this.config={...c3,...e}}trackCall(e,u,a){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return{isLoop:!1,callCount:1,signature:this.createSignature(u,a),action:"allow"};let t=this.createSignature(u,a);this.totalCallsTracked++,this.callHistory.has(e)||this.callHistory.set(e,[]);let r=this.callHistory.get(e);r.push(t);let i=Date.now()-this.config.windowMs,n=r.findIndex(l=>l.timestamp>=i);n>0?r.splice(0,n):n===-1&&(r.length=0,r.push(t));let o=r.filter(l=>l.hash===t.hash).length;return o>=this.config.maxIdenticalCalls?(this.loopsDetected++,{isLoop:!0,callCount:o,signature:t,action:"steer",steeringMessage:this.config.steeringMessage}):o===this.config.maxIdenticalCalls-1?{isLoop:!1,callCount:o,signature:t,action:"warn"}:{isLoop:!1,callCount:o,signature:t,action:"allow"}}getMetrics(){return{totalCallsTracked:this.totalCallsTracked,loopsDetected:this.loopsDetected}}clear(){this.callHistory.clear(),this.totalCallsTracked=0,this.loopsDetected=0}createSignature(e,u){let a=JSON.stringify(u??""),t=g4(a),r=`${e}:${a}`;return{hash:g4(r),toolName:e,argsFingerprint:t,timestamp:Date.now()}}},A4={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},E3={thresholds:A4,agentId:"unknown",maxHistorySize:200,fallbackDimension:64};function d3(s,e){let u=new Float64Array(e),a=2166136261,t=16777619;for(let n=0;n<s.length;n++){let o=s.charCodeAt(n);a^=o,a=Math.imul(a,16777619),t^=o,t=Math.imul(t,2166136261);let l=(a>>>0)%e;u[l]+=(t>>>0)/4294967295*2-1}let r=0;for(let n=0;n<e;n++)r+=u[n]*u[n];r=Math.sqrt(r);let i=new Array(e);for(let n=0;n<e;n++)i[n]=r===0?0:u[n]/r;return i}var C4=!1,E0=!1,Ft=null;async function m3(){if(C4)return E0;C4=!0;try{let s=await import("./real-embeddings-H36GVXMI.js");if(typeof s.isTransformerAvailable=="function"&&s.isTransformerAvailable())Ft=s.computeRealEmbedding,E0=!0;else try{await s.computeRealEmbedding("probe"),Ft=s.computeRealEmbedding,E0=!0}catch(e){ln.debug("Transformer probe embedding failed",{error:e instanceof Error?e.message:String(e)}),E0=!1}}catch(s){ln.debug("Transformer module import failed",{error:s instanceof Error?s.message:String(s)}),E0=!1}return E0}var bt=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;constructor(e){this.config={...E3,...e,thresholds:{...A4,...e?.thresholds}}}async onEmit(e){let u=JSON.stringify(e.payload),a=await this.embed(u),t=this.resolveCategory(e.type),r=this.config.thresholds[t]??this.config.thresholds.default,i={embedding:a,driftThreshold:r,sourceAgentId:this.config.agentId,hopCount:0,emittedAt:Date.now()};return{...e,semanticFingerprint:i}}async onReceive(e){let u=e.semanticFingerprint;if(!u)return e;let a=JSON.stringify(e.payload),t=await this.embed(a),r=ce(t,u.embedding),n=1-r>u.driftThreshold;this.totalChecked++,this.similaritySum+=r;let o={drifted:n,cosineSimilarity:r,threshold:u.driftThreshold,eventType:e.type,hopCount:u.hopCount+1,checkedAt:Date.now()};if(this.history.push(o),this.history.length>this.config.maxHistorySize&&this.history.shift(),n)return this.driftCount++,await this.emitDriftEvent(e,o),null;let l={...u,hopCount:u.hopCount+1};return{...e,semanticFingerprint:l}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0}}validateConfig(){for(let[e,u]of Object.entries(this.config.thresholds))if(typeof u!="number"||u<0||u>1)return m(new Error(`Invalid threshold for "${e}": must be between 0 and 1, got ${u}`));return this.config.maxHistorySize<=0?m(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?m(new Error("fallbackDimension must be positive")):p(void 0)}async embed(e){return await m3()&&Ft?Ft(e):d3(e,this.config.fallbackDimension)}resolveCategory(e){let u=e.toLowerCase();for(let a of Object.keys(this.config.thresholds))if(a!=="default"&&u.includes(a))return a;return"default"}async emitDriftEvent(e,u){if(!this.config.onDriftDetected)return;let a={id:`drift-${e.id}-${Date.now()}`,type:"SemanticDriftDetected",timestamp:new Date,source:e.source,correlationId:e.correlationId,payload:{originalEventId:e.id,originalEventType:e.type,cosineSimilarity:u.cosineSimilarity,threshold:u.threshold,hopCount:u.hopCount,agentId:this.config.agentId}};try{await this.config.onDriftDetected(a)}catch(t){ln.debug("onDriftDetected callback failed",{error:t instanceof Error?t.message:String(t)})}}};Zi();c0();import*as o0 from"path";import*as qi from"fs";S();var U=class{constructor(e,u){this.eventBus=e;this.memory=u}_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(e){await this.onEvent(e)}async onInitialize(){}async onDispose(){}async onEvent(e){}subscribeToEvents(){}async publishEvent(e,u){let a={id:crypto.randomUUID(),type:e,timestamp:new Date,source:this.name,payload:u};await this.eventBus.publish(a)}updateHealth(e){this._health={...this._health,...e}}setMinCutBridge(e){this._minCutBridge=e,this.onMinCutBridgeSet(e)}getMinCutBridge(){return this._minCutBridge}setConsensusConfig(e){this._consensusConfig=e,this.onConsensusConfigSet(e)}getConsensusConfig(){return this._consensusConfig}setIntegrationConfig(e){e.minCutBridge&&this.setMinCutBridge(e.minCutBridge),e.consensusConfig&&this.setConsensusConfig(e.consensusConfig)}hasMinCutIntegration(){return this._minCutBridge!==void 0}hasConsensusEnabled(){return this._consensusConfig?.enabled===!0}onMinCutBridgeSet(e){}onConsensusConfigSet(e){}getTaskHandlers(){return new Map}canHandleTask(e){return this.getTaskHandlers().has(e)}async executeTask(e,u){let t=this.getTaskHandlers().get(e.taskType);return t?(this.runTaskAsync(e,t,u),p(void 0)):m(new Error(`Domain ${this.name} has no handler for task type: ${e.taskType}`))}async runTaskAsync(e,u,a){let t=Date.now();try{let r=await u(e.payload),i=Date.now()-t,n={taskId:e.taskId,success:r.success,data:r.success?r.value:void 0,error:r.success?void 0:r.error?.message,duration:i};if(await a(n),r.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=r.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(r){let i=Date.now()-t,n=k(r);await a({taskId:e.taskId,success:!1,error:n,duration:i}),this.updateHealth({lastActivity:new Date,errors:[...this._health.errors.slice(-9),n],agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),failed:this._health.agents.failed+1}})}}};N();S();N();import*as oc from"fs";import*as ga from"path";d0();import{randomBytes as p3,randomInt as me,randomUUID as g3}from"node:crypto";function v4(s){return p3(s).toString("hex")}var z={uuid:()=>g3(),email:()=>`user_${v4(3)}@example.com`,fullName:()=>{let s=["Alice","Bob","Carol","Dave","Eve","Frank"],e=["Smith","Jones","Lee","Garcia","Chen","Novak"];return`${s[me(s.length)]} ${e[me(e.length)]}`},url:()=>`https://example.com/${v4(4)}`,recentDate:()=>new Date(Date.now()-me(7*864e5)).toISOString(),phone:()=>`+1${String(me(2e9,9999999999))}`,streetAddress:()=>`${me(1,9999)} Main St`,word:()=>{let s=["alpha","bravo","charlie","delta","echo","foxtrot","golf","hotel"];return s[me(s.length)]},int:(s=1,e=100)=>{if(s>e){let u=s;s=e,e=u}return me(s,e+1)},float:(s=0,e=100,u=2)=>{if(s>e){let t=s;s=e,e=t}if(s===e)return s;let a=s+me(0,1000001)/1e6*(e-s);return Number(a.toFixed(u))}};var uu=class s{static NAME_VALUE_TABLE=[["id",()=>`'${z.uuid()}'`],["email",()=>`'${z.email()}'`],["name",()=>`'${z.fullName()}'`],["url",()=>`'${z.url()}'`],["date",()=>`new Date('${z.recentDate()}')`],["phone",()=>`'${z.phone()}'`],["address",()=>`'${z.streetAddress()}'`]];static TYPE_VALUE_TABLE=[["string",()=>`'${z.word()}'`],["number",()=>String(z.int(1,100))],["boolean",()=>"true"],["[]",()=>"[]"],["array",()=>"[]"],["object",()=>"{}"],["{",()=>"{}"],["function",()=>"() => {}"],["promise",()=>"Promise.resolve()"],["date",()=>"new Date()"]];generateTestValue(e){if(e.defaultValue)return e.defaultValue;let u=e.type?.toLowerCase()||"unknown",a=e.name.toLowerCase();for(let[t,r]of s.NAME_VALUE_TABLE)if(a.includes(t))return r();for(let[t,r]of s.TYPE_VALUE_TABLE)if(u.includes(t))return r();return`{} /* TODO: provide ${e.name}: ${e.type||"unknown"} */`}generateTestCasesForFunction(e){let u=[],a=e.parameters.map(l=>this.generateTestValue(l)).join(", "),t=e.isAsync?`await ${e.name}(${a})`:`${e.name}(${a})`,r=e.returnType==="void"||e.returnType==="Promise<void>",i="expect(result).toBeDefined();";if(!r){if(/^(is|has|can)[A-Z]/.test(e.name))i="expect(typeof result).toBe('boolean');";else if(/^(get|fetch|find)[A-Z]/.test(e.name))i="expect(result).not.toBeUndefined();";else if(/^(create|build|make)[A-Z]/.test(e.name))i="expect(result).toBeTruthy();";else if(e.returnType){let l=e.returnType.toLowerCase().replace(/promise<(.+)>/,"$1");l.includes("{")?i="expect(typeof result).toBe('object');":l==="boolean"?i="expect(typeof result).toBe('boolean');":l==="number"?i="expect(typeof result).toBe('number');":l==="string"?i="expect(typeof result).toBe('string');":l.includes("[]")||l.includes("array")?i="expect(Array.isArray(result)).toBe(true);":l.includes("boolean")?i="expect(typeof result).toBe('boolean');":l.includes("number")?i="expect(typeof result).toBe('number');":l.includes("string")&&(i="expect(typeof result).toBe('string');")}}u.push({description:"should handle valid input correctly",type:"happy-path",action:r?`${t};`:`const result = ${t};`,assertion:r?"// void function \u2014 no return value to assert":i});let n=e.body||"",o=/\bthrow\b/.test(n)||/\bvalidat/i.test(n);for(let l of e.parameters){if(!l.optional){let c=e.parameters.map(E=>E.name===l.name?"undefined":this.generateTestValue(E)).join(", ");if(o)u.push({description:`should handle undefined ${l.name}`,type:"error-handling",action:e.isAsync?`const action = async () => await ${e.name}(${c});`:`const action = () => ${e.name}(${c});`,assertion:"expect(action).toThrow();"});else{let E=e.isAsync?`await ${e.name}(${c})`:`${e.name}(${c})`;u.push({description:`should handle undefined ${l.name}`,type:"edge-case",action:e.isAsync?`let threw = false;
118
118
  try {
119
119
  await ${e.name}(${c});
120
120
  } catch (e) {
@@ -2015,7 +2015,7 @@ ${n}
2015
2015
  `),t=/(?:it|test)\s*\(\s*(?:'[^']*'|"[^"]*"|`[^`]*`)\s*,\s*(?:async\s+)?(?:\(\)\s*=>|function\s*\(\))\s*\{([^}]*)\}\s*\)/,r=i=>i.replace(/\/\*[^*]*\*\//g,"").replace(/\/\/[^\n]*/g,"").trim().length===0;for(let i=0;i<a.length;i++){if(!/(?:it|test)\s*\(/.test(a[i]))continue;let n=a.slice(i,i+4).join(" "),o=t.exec(n);o&&r(o[1])&&u.push({type:"empty-test-body",severity:"error",line:i+1,description:"Empty test body: this test has no assertions or meaningful code.",suggestion:"Add assertions that verify the expected behavior of the code under test."})}return u}detectMirroredAssertions(e,u){let a=[],t=this.extractNonTrivialLiterals(u);if(t.length===0)return a;let r=e.split(`
2016
2016
  `),i=/\.(?:toBe|toEqual|toStrictEqual)\s*\(\s*(.+?)\s*\)/;for(let n=0;n<r.length;n++){let l=r[n].match(i);if(!l)continue;let c=l[1].trim();for(let E of t)if(this.literalMatches(c,E)){a.push({type:"mirrored-assertion",severity:"warning",line:n+1,description:`Assertion expected value "${c}" mirrors a literal from the source code. This may indicate the test was generated by copying source values rather than computing expected results independently.`,suggestion:"Verify the expected value is derived from requirements, not copied from the implementation."});break}}return a}extractNonTrivialLiterals(e){let u=new Set,a=new Set(["true","false","null","undefined","0","1","-1",'""',"''","``"]),t=/(?:=|return|:)\s*(['"])(.+?)\1/g,r;for(;(r=t.exec(e))!==null;){let n=r[2];n.length>=2&&!a.has(n)&&(u.add(`'${n}'`),u.add(`"${n}"`))}let i=/(?:=|return|:)\s*(\d+(?:\.\d+)?)\b/g;for(;(r=i.exec(e))!==null;){let n=r[1];a.has(n)||u.add(n)}return Array.from(u)}literalMatches(e,u){if(e===u)return!0;let a=e.replace(/^['"`]|['"`]$/g,""),t=u.replace(/^['"`]|['"`]$/g,"");return a===t&&a.length>=2}calculateScore(e){let u=100;for(let a of e)a.severity==="error"?u-=20:u-=5;return Math.max(0,u)}};N();function X4(s,e,u){let a=[],t=u?.maxHintsPerPattern??3,r=e.length;if(r===0)return a;let i=e.filter(l=>!l.success).length,n=i/r;if(n>.2&&n<.8&&r>=3&&a.push({patternId:s.id,observation:`Pattern "${s.name}" fails ${(n*100).toFixed(0)}% of the time (${i}/${r} executions)`,diagnosis:"Intermittent failures suggest timing dependencies, external service flakiness, or non-deterministic behavior",suggestion:"Add retry logic, mock external dependencies, or add explicit waits for async operations",confidence:Math.min(.9,.5+r*.05),category:"flaky"}),n>=.8&&r>=2&&a.push({patternId:s.id,observation:`Pattern "${s.name}" fails ${(n*100).toFixed(0)}% of executions \u2014 effectively broken`,diagnosis:"Consistent failures indicate the pattern logic is incorrect or the target code changed",suggestion:"Review the pattern against current code. Consider quarantining and creating a replacement pattern.",confidence:.85,category:"false-positive"}),r>=5){let l=e.slice(-3).filter(E=>!E.success).length,c=e.slice(0,Math.max(1,r-3)).filter(E=>E.success).length;l>=2&&c>=2&&a.push({patternId:s.id,observation:`Pattern "${s.name}" worked previously but now fails consistently`,diagnosis:"Recent code changes likely broke compatibility with this pattern",suggestion:"Update pattern to match current code structure. Check git log for recent changes to affected files.",confidence:.8,category:"outdated"})}s.description&&s.description.length<20&&n>.3&&a.push({patternId:s.id,observation:`Pattern "${s.name}" has a vague description and high failure rate`,diagnosis:"Pattern may be too broadly scoped \u2014 matching contexts where it does not apply",suggestion:"Narrow the pattern scope by adding specific tags, domain constraints, or more detailed matching criteria",confidence:.6,category:"wrong-scope"});let o=e.filter(l=>!l.success&&l.feedback).map(l=>l.feedback).slice(-3);if(o.length>0){let l=e6u(o);l.length>0&&a.push({patternId:s.id,observation:`Failure feedback contains recurring themes: ${l.join(", ")}`,diagnosis:`Common failure keywords suggest a systematic issue: ${l.slice(0,3).join(", ")}`,suggestion:`Address the recurring "${l[0]}" issue in the pattern logic or preconditions`,confidence:.65,category:"missing-context"})}return a.slice(0,t)}var u6u=new Set(["the","a","an","is","was","in","to","for","of","and","or","not","with","test","error"]);function e6u(s){let e=new Map;for(let u of s){let a=u.toLowerCase().split(/\W+/).filter(r=>r.length>2&&!u6u.has(r)),t=new Set(a);for(let r of t)e.set(r,(e.get(r)??0)+1)}return Array.from(e.entries()).filter(([,u])=>u>=2).sort((u,a)=>a[1]-u[1]).map(([u])=>u).slice(0,5)}var uc={topN:3,minConfidence:.5,namespace:"aqe/v3/domains/test-generation"},a6u=B.create("test-generation/edge-case-injector");function ec(s){let e=new Set,u=new Set(["const","let","var","function","class","import","export","return","this","new","async","await","from","type","interface","string","number","boolean","void","null","undefined","true","false","map","filter","reduce","forEach","push","pop","length","toString","valueOf","constructor"]),a=s.matchAll(/function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g);for(let l of a)e.add(l[1]);let t=s.matchAll(/(?:const|let|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=/g);for(let l of t)e.add(l[1]);let r=s.matchAll(/class\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g);for(let l of r)e.add(l[1]);let i=s.matchAll(/import\s+(?:\{([^}]+)\}|([a-zA-Z_$][a-zA-Z0-9_$]*))\s+from/g);for(let l of i){let c=l[1],E=l[2];if(c)for(let d of c.split(",")){let D=d.trim().split(/\s+as\s+/).pop()?.trim();D&&/^[a-zA-Z_$]/.test(D)&&e.add(D)}E&&e.add(E)}let n=s.matchAll(/(?:async\s+)?([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\([^)]*\)\s*(?::\s*\S+\s*)?{/g);for(let l of n)l[1].length>2&&!u.has(l[1])&&e.add(l[1]);let o=s.matchAll(/\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g);for(let l of o)l[1].length>2&&e.add(l[1]);return Array.from(e).filter(l=>!u.has(l)&&l.length>1)}var pa=class{constructor(e,u){this.memory=e;this.config={...uc,...u}}config;async getInjectionContext(e,u){let a={promptContext:"",patternsUsed:0,totalConsidered:0};try{let t=ec(e),r=await this.searchPatterns(t,u);if(r.length===0)return a;let i=r.length,n=r.filter(c=>c.confidence>=this.config.minConfidence);n.sort((c,E)=>{let d=c.successRate*.5+c.confidence*.3+Math.log(c.usageCount+1)/10*.2;return E.successRate*.5+E.confidence*.3+Math.log(E.usageCount+1)/10*.2-d});let o=n.slice(0,this.config.topN);return o.length===0?{promptContext:"",patternsUsed:0,totalConsidered:i}:{promptContext:this.formatPromptContext(o),patternsUsed:o.length,totalConsidered:i}}catch{return a6u.warn("Failed to get injection context:"),a}}async searchPatterns(e,u){let a=[],t=[];u&&(t.push(`edge-case:${u}:*`),t.push(`pattern:${u}:*`));for(let i of e.slice(0,5))t.push(`edge-case:*${i}*`),t.push(`pattern:*${i}*`);t.push(`${this.config.namespace}:*`);let r=new Set;for(let i of t)try{let n=await this.memory.search(i,10);for(let o of n)if(!r.has(o)){r.add(o);try{let l=await this.memory.get(o);if(!l||typeof l!="object")continue;let c=this.parsePattern(o,l);c&&a.push(c)}catch{}}}catch{}return a}parsePattern(e,u){let a=typeof u.name=="string"?u.name:e.split(":").pop()||e,t=typeof u.description=="string"?u.description:"",r=typeof u.confidence=="number"?u.confidence:.5,i=typeof u.successRate=="number"?u.successRate:typeof u.success_rate=="number"?u.success_rate:0,n=typeof u.usageCount=="number"?u.usageCount:typeof u.usage_count=="number"?u.usage_count:0,o=Array.isArray(u.tags)?u.tags.filter(l=>typeof l=="string"):[];return!a&&!t?null:{key:e,name:a,description:t,confidence:r,successRate:i,usageCount:n,tags:o}}formatPromptContext(e){let u=["## Historical Edge Cases (from patterns that caught real bugs):"];for(let r=0;r<e.length;r++){let i=e[r],n=i.tags.length>0?i.tags[0]:this.inferTag(i),o=i.description||i.name;u.push(`${r+1}. [${n}] ${o}`)}let a=e.filter(r=>r.successRate<.5),t=[];for(let r of a){let i=X4({id:r.key,name:r.name,description:r.description,successRate:r.successRate,usageCount:r.usageCount,confidence:r.confidence,tags:r.tags},this.buildSyntheticHistory(r));t.push(...i)}if(t.length>0){u.push(""),u.push("## Remediation Notes (patterns with known issues):");for(let r of t.slice(0,3))u.push(`- [${r.category}] ${r.suggestion}`)}return u.join(`
2017
2017
  `)}buildSyntheticHistory(e){let u=Math.max(e.usageCount,1),a=Math.round(u*e.successRate),t=[];for(let r=0;r<a;r++)t.push({success:!0});for(let r=0;r<u-a;r++)t.push({success:!1});return t}inferTag(e){let u=e.name.toLowerCase();return u.includes("null")||u.includes("undefined")?"null-check":u.includes("empty")||u.includes("boundary")||u.includes("zero")?"boundary":u.includes("async")||u.includes("promise")||u.includes("reject")?"async-error":u.includes("error")||u.includes("throw")||u.includes("exception")?"error-handling":u.includes("type")||u.includes("cast")||u.includes("coerce")?"type-safety":u.includes("concurr")||u.includes("race")||u.includes("parallel")?"concurrency":"edge-case"}};d0();d0();import*as h0 from"path";import*as ue from"fs";var t6u=[/\.g\.cs$/,/\.pb\.go$/,/\.freezed\.dart$/,/_generated\.go$/,/\.generated\.\w+$/,/\.min\.\w+$/];function r6u(s){return t6u.some(e=>e.test(s))}function i6u(s){let e=s.filter(r=>!r6u(r));if(e.length===0)return;let u=new Map;for(let r of e){let i=h0.extname(r),n=de(i);n&&u.set(n,(u.get(n)??0)+1)}if(u.size===0)return;let a,t=0;for(let[r,i]of u)i>t&&(t=i,a=r);return a}function n6u(s,e){if(e){let u=o6u(s,e);if(u)return u}return cn[s]}function o6u(s,e){try{switch(s){case"typescript":case"javascript":{let u=h0.join(e,"package.json");if(ue.existsSync(u)){let a=JSON.parse(ue.readFileSync(u,"utf-8")),t={...a.dependencies,...a.devDependencies};if(t.vitest)return"vitest";if(t.jest)return"jest";if(t.mocha)return"mocha"}return}case"python":return"pytest";case"java":{let u=h0.join(e,"pom.xml");return ue.existsSync(u)&&ue.readFileSync(u,"utf-8").includes("testng")?"testng":"junit5"}case"csharp":{let u=s6u(e,"*.csproj");for(let a of u)try{if(ue.readFileSync(a,"utf-8").includes("NUnit"))return"nunit"}catch{}return"xunit"}case"swift":return"swift-testing";default:return}}catch{return}}function s6u(s,e){try{let u=e.replace(/\*/g,"");return ue.readdirSync(s).filter(a=>a.endsWith(u)).map(a=>h0.join(s,a))}catch{return[]}}function ac(s){let e=s.language;if(!e&&s.sourceFiles?.length&&(e=i6u(s.sourceFiles)),!e)return;let u=s.framework;return u||(u=n6u(e,s.projectRoot)),{language:e,framework:u}}import{execSync as l6u}from"child_process";import*as pe from"fs";import*as Io from"path";import*as tc from"os";var c6u={typescript:{check:"npx tsc --noEmit --strict",fileExt:".ts"},java:{check:"javac -d /dev/null",fileExt:".java"},csharp:{check:"dotnet build --no-restore",fileExt:".cs"},go:{check:"go vet",fileExt:"_test.go"},rust:{check:"cargo check",fileExt:".rs"},kotlin:{check:"kotlinc -script",fileExt:".kts"},swift:{check:"swiftc -typecheck",fileExt:".swift"},dart:{check:"dart analyze",fileExt:".dart"}},Ko=class{async validate(e,u,a){let t=c6u[u];if(!t)return{compiles:!0,errors:[],suggestions:[`No compilation check available for ${u} -- syntax validation skipped`]};let r=pe.mkdtempSync(Io.join(tc.tmpdir(),"aqe-compile-")),i=Io.join(r,`test_validation${t.fileExt}`);try{pe.writeFileSync(i,e,"utf-8");let n=`${t.check} ${i}`;return l6u(n,{cwd:a||r,timeout:3e4,stdio:"pipe",encoding:"utf-8"}),{compiles:!0,errors:[],suggestions:[]}}catch(n){if(this.isCommandNotFound(n))return{compiles:!1,errors:[{message:`Compiler not found for ${u}`}],suggestions:[`Install the ${u} compiler to enable compilation validation`]};let o=this.getStderr(n),l=this.parseErrors(o,u);return{compiles:!1,errors:l.length>0?l:[{message:o||"Compilation failed"}],suggestions:this.generateSuggestions(l,u)}}finally{try{pe.unlinkSync(i),pe.rmdirSync(r)}catch{}}}isCommandNotFound(e){let u=String(e);return u.includes("ENOENT")||u.includes("not found")||u.includes("command not found")}getStderr(e){return e&&typeof e=="object"&&"stderr"in e?String(e.stderr):String(e)}parseErrors(e,u){if(!e)return[];let a=[],t=e.split(`
2018
- `).filter(r=>r.trim());for(let r of t.slice(0,10)){let i=r.match(/(?:.*?):(\d+):(\d+):\s*(?:error:\s*)?(.*)/);i?a.push({message:i[3].trim(),line:parseInt(i[1],10),column:parseInt(i[2],10)}):(r.includes("error")||r.includes("Error"))&&a.push({message:r.trim()})}return a}generateSuggestions(e,u){let a=[];for(let t of e){let r=t.message.toLowerCase();(r.includes("import")||r.includes("module"))&&a.push("Check import statements -- ensure all dependencies are available"),(r.includes("type")||r.includes("cannot find"))&&a.push("Verify type definitions match the source code signatures"),(r.includes("undefined")||r.includes("undeclared"))&&a.push("Ensure all referenced symbols are properly imported or declared")}return[...new Set(a)]}},rc=new Ko;import*as pu from"path";var E6u={typescript:{strategy:"alongside",testPrefix:"",testSuffix:".test",testExtension:".ts"},javascript:{strategy:"alongside",testPrefix:"",testSuffix:".test",testExtension:".js"},python:{strategy:"tests-directory",testPrefix:"test_",testSuffix:"",testExtension:".py",testDirectory:"tests"},java:{strategy:"maven-mirror",testPrefix:"",testSuffix:"Test",testExtension:".java",testDirectory:"src/test/java"},csharp:{strategy:"test-project",testPrefix:"",testSuffix:"Tests",testExtension:".cs",testDirectory:"tests"},go:{strategy:"alongside",testPrefix:"",testSuffix:"_test",testExtension:".go"},rust:{strategy:"inline",testPrefix:"",testSuffix:"",testExtension:".rs"},swift:{strategy:"tests-directory",testPrefix:"",testSuffix:"Tests",testExtension:".swift",testDirectory:"Tests"},kotlin:{strategy:"maven-mirror",testPrefix:"",testSuffix:"Test",testExtension:".kt",testDirectory:"src/test/kotlin"},dart:{strategy:"tests-directory",testPrefix:"",testSuffix:"_test",testExtension:".dart",testDirectory:"test"}};function ic(s,e,u){let a=E6u[e],t=pu.parse(s),r=t.name,i=t.dir;switch(a.strategy){case"alongside":{let n=`${a.testPrefix}${r}${a.testSuffix}${a.testExtension}`;return pu.join(i,n)}case"tests-directory":{let n=a.testDirectory||"tests",o=u||".",l;try{l=pu.relative(o,i)}catch{l=i}let c=l.replace(/^src[\/\\]?/,"").replace(/^lib[\/\\]?/,"").replace(/^Sources[\/\\]?/,""),E=`${a.testPrefix}${r}${a.testSuffix}${a.testExtension}`;return pu.join(o,n,c,E)}case"maven-mirror":{let n=u||".",o=a.testDirectory||"src/test/java",l;try{l=pu.relative(n,s)}catch{l=s}let c=l.replace(/^src[\/\\]main[\/\\]java[\/\\]?/,`${o}${pu.sep}`).replace(/^src[\/\\]main[\/\\]kotlin[\/\\]?/,`${o}${pu.sep}`),E=pu.parse(c),d=`${a.testPrefix}${E.name}${a.testSuffix}${a.testExtension}`;return pu.join(n,E.dir,d)}case"test-project":{let n=u||".",o=a.testDirectory||"tests",l;try{l=pu.relative(n,i)}catch{l=i}let c=l.replace(/^src[\/\\]?/,""),E=`${a.testPrefix}${r}${a.testSuffix}${a.testExtension}`;return pu.join(n,o,c,E)}case"inline":return s;default:return pu.join(i,`${r}.test${t.ext}`)}}var d6u={typescript:{systemContext:"TypeScript with strict typing, ESM modules, and modern ES2022+ features.",conventions:["Use strict TypeScript types \u2014 avoid `any`","Use `import type` for type-only imports","Prefer `const` assertions and branded types","Use async/await over raw Promises"],assertionStyle:"expect(value).toBe(expected) \u2014 Vitest/Jest matchers",mockingStyle:"vi.mock() / jest.mock() with typed mocks",codeFenceLanguage:"typescript"},javascript:{systemContext:"JavaScript with ES2022+ features, CommonJS or ESM modules.",conventions:["Use const/let, never var","Use arrow functions for callbacks","Prefer template literals for string interpolation"],assertionStyle:"expect(value).toBe(expected) \u2014 Jest matchers",mockingStyle:"jest.mock() with manual mock implementations",codeFenceLanguage:"javascript"},python:{systemContext:"Python 3.10+ with type hints, dataclasses, and async support.",conventions:["Follow PEP 8 naming (snake_case for functions, PascalCase for classes)","Use type hints on all function signatures","Use `pytest` fixtures for setup/teardown","Use `@pytest.mark.asyncio` for async tests"],assertionStyle:"assert value == expected \u2014 plain assert with pytest",mockingStyle:"unittest.mock.patch / pytest-mock fixtures",codeFenceLanguage:"python"},java:{systemContext:"Java 17+ with records, sealed classes, and pattern matching.",conventions:["Use JUnit 5 @Test and @DisplayName annotations","Use AssertJ fluent assertions (assertThat)","Follow given-when-then structure in test methods","Use @ExtendWith(MockitoExtension.class) for dependency injection"],assertionStyle:"assertThat(value).isEqualTo(expected) \u2014 AssertJ",mockingStyle:"Mockito @Mock, @InjectMocks, when().thenReturn()",codeFenceLanguage:"java"},csharp:{systemContext:"C# 11+ with nullable reference types, records, and async streams.",conventions:["Use xUnit [Fact] and [Theory] attributes","Use FluentAssertions for readable assertions","Follow Arrange-Act-Assert pattern","Use Moq for interface mocking"],assertionStyle:"value.Should().Be(expected) \u2014 FluentAssertions",mockingStyle:"new Mock<IService>().Setup(x => x.Method()).Returns(value)",codeFenceLanguage:"csharp"},go:{systemContext:"Go 1.21+ with generics, error wrapping, and context propagation.",conventions:["Use table-driven tests with t.Run subtests","Always check both value and error returns","Use testify/assert for assertions (or standard testing)","Mock interfaces with struct implementations"],assertionStyle:"assert.Equal(t, expected, actual) \u2014 testify",mockingStyle:"Interface-based mock structs",codeFenceLanguage:"go"},rust:{systemContext:"Rust with ownership, borrowing, lifetimes, and trait-based generics.",conventions:["Place tests in #[cfg(test)] mod tests { use super::*; }","Use assert!, assert_eq!, assert_ne! macros",'Use #[should_panic(expected = "...")] for panic tests',"Use #[tokio::test] for async tests"],assertionStyle:"assert_eq!(value, expected) \u2014 standard macros",mockingStyle:"mockall crate with #[automock] on traits",codeFenceLanguage:"rust"},swift:{systemContext:"Swift 5.10+ with Swift Testing framework, actors, and structured concurrency.",conventions:["Use @Test attribute with description strings","Use #expect() macro for assertions","Use @Suite for grouping related tests","Protocol-based mocking (manual stubs)"],assertionStyle:"#expect(value == expected) \u2014 Swift Testing macros",mockingStyle:"Protocol conformance with manual mock implementations",codeFenceLanguage:"swift"},kotlin:{systemContext:"Kotlin with coroutines, null safety, extension functions, and sealed classes.",conventions:["Use backtick test names: `should return user when id is valid`","Use MockK @MockK and coEvery for coroutine mocking","Use runTest { } for coroutine test wrappers","Use Turbine for Flow testing"],assertionStyle:"value shouldBe expected \u2014 Kotest matchers or JUnit assertEquals",mockingStyle:"MockK coEvery { service.call() } returns result",codeFenceLanguage:"kotlin"},dart:{systemContext:"Dart 3+ with null safety, records, and sealed classes. Flutter widgets.",conventions:["Use test() for unit tests, testWidgets() for widget tests","Use group() for test organization","Use @GenerateMocks for mockito code generation","Route Widget subclasses to testWidgets with pumpWidget"],assertionStyle:"expect(value, equals(expected)) \u2014 matcher-based",mockingStyle:"@GenerateMocks([ServiceClass]) + when(mock.method()).thenReturn(value)",codeFenceLanguage:"dart"}};function nc(s){return d6u[s]}function m6u(s,e=0){let u=(2166136261^e)>>>0;for(let a=0;a<s.length;a++)u^=s.charCodeAt(a),u=Math.imul(u,16777619),u=u>>>0;return u}function D6u(s,e=0){return m6u(s,e)%100<10}var h6u={defaultFramework:"vitest",maxTestsPerFile:50,coverageTargetDefault:80,enableAIGeneration:!0,enableLLMEnhancement:!0,llmModelTier:2,llmMaxTokens:2048,enableTestQualityGate:!0,enableEdgeCaseInjection:!0},jo=B.create("test-generation/test-generator"),Ht=class{config;memory;generatorFactory;tddGenerator;propertyTestGenerator;testDataGenerator;llmRouter;qualityGate;edgeCaseInjector;constructor(e,u={}){this.config={...h6u,...u},this.memory=e.memory,this.generatorFactory=e.generatorFactory||new ma,this.tddGenerator=e.tddGenerator||new Tt,this.propertyTestGenerator=e.propertyTestGenerator||new Mt,this.testDataGenerator=e.testDataGenerator||new jt,this.llmRouter=e.llmRouter,this.qualityGate=this.config.enableTestQualityGate?new ha:null,this.edgeCaseInjector=this.config.enableEdgeCaseInjection?new pa(this.memory):null}isLLMEnhancementAvailable(){return this.config.enableLLMEnhancement&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async enhanceTestWithLLM(e,u,a,t){if(!this.llmRouter)return e;try{let r=this.buildTestEnhancementPrompt(e,u,a);if(this.edgeCaseInjector)try{let o=t?.dependencies?"test-generation":void 0,l=await this.edgeCaseInjector.getInjectionContext(u,o);l.promptContext&&(r=l.promptContext+`
2018
+ `).filter(r=>r.trim());for(let r of t.slice(0,10)){let i=r.match(/(?:.*?):(\d+):(\d+):\s*(?:error:\s*)?(.*)/);i?a.push({message:i[3].trim(),line:parseInt(i[1],10),column:parseInt(i[2],10)}):(r.includes("error")||r.includes("Error"))&&a.push({message:r.trim()})}return a}generateSuggestions(e,u){let a=[];for(let t of e){let r=t.message.toLowerCase();(r.includes("import")||r.includes("module"))&&a.push("Check import statements -- ensure all dependencies are available"),(r.includes("type")||r.includes("cannot find"))&&a.push("Verify type definitions match the source code signatures"),(r.includes("undefined")||r.includes("undeclared"))&&a.push("Ensure all referenced symbols are properly imported or declared")}return[...new Set(a)]}},rc=new Ko;import*as pu from"path";var E6u={typescript:{strategy:"alongside",testPrefix:"",testSuffix:".test",testExtension:".ts"},javascript:{strategy:"alongside",testPrefix:"",testSuffix:".test",testExtension:".js"},python:{strategy:"tests-directory",testPrefix:"test_",testSuffix:"",testExtension:".py",testDirectory:"tests"},java:{strategy:"maven-mirror",testPrefix:"",testSuffix:"Test",testExtension:".java",testDirectory:"src/test/java"},csharp:{strategy:"test-project",testPrefix:"",testSuffix:"Tests",testExtension:".cs",testDirectory:"tests"},go:{strategy:"alongside",testPrefix:"",testSuffix:"_test",testExtension:".go"},rust:{strategy:"inline",testPrefix:"",testSuffix:"",testExtension:".rs"},swift:{strategy:"tests-directory",testPrefix:"",testSuffix:"Tests",testExtension:".swift",testDirectory:"Tests"},kotlin:{strategy:"maven-mirror",testPrefix:"",testSuffix:"Test",testExtension:".kt",testDirectory:"src/test/kotlin"},dart:{strategy:"tests-directory",testPrefix:"",testSuffix:"_test",testExtension:".dart",testDirectory:"test"}};function ic(s,e,u){let a=E6u[e],t=pu.parse(s),r=t.name,i=t.dir;switch(a.strategy){case"alongside":{let n=`${a.testPrefix}${r}${a.testSuffix}${a.testExtension}`;return pu.join(i,n)}case"tests-directory":{let n=a.testDirectory||"tests",o=u||".",l;try{l=pu.relative(o,i)}catch{l=i}let c=l.replace(/^src[\/\\]?/,"").replace(/^lib[\/\\]?/,"").replace(/^Sources[\/\\]?/,""),E=`${a.testPrefix}${r}${a.testSuffix}${a.testExtension}`;return pu.join(o,n,c,E)}case"maven-mirror":{let n=u||".",o=a.testDirectory||"src/test/java",l;try{l=pu.relative(n,s)}catch{l=s}let c=l.replace(/^src[\/\\]main[\/\\]java[\/\\]?/,`${o}${pu.sep}`).replace(/^src[\/\\]main[\/\\]kotlin[\/\\]?/,`${o}${pu.sep}`),E=pu.parse(c),d=`${a.testPrefix}${E.name}${a.testSuffix}${a.testExtension}`;return pu.join(n,E.dir,d)}case"test-project":{let n=u||".",o=a.testDirectory||"tests",l;try{l=pu.relative(n,i)}catch{l=i}let c=l.replace(/^src[\/\\]?/,""),E=`${a.testPrefix}${r}${a.testSuffix}${a.testExtension}`;return pu.join(n,o,c,E)}case"inline":return s;default:return pu.join(i,`${r}.test${t.ext}`)}}var d6u={typescript:{systemContext:"TypeScript with strict typing, ESM modules, and modern ES2022+ features.",conventions:["Use strict TypeScript types \u2014 avoid `any`","Use `import type` for type-only imports","Prefer `const` assertions and branded types","Use async/await over raw Promises"],assertionStyle:"expect(value).toBe(expected) \u2014 Vitest/Jest matchers",mockingStyle:"vi.mock() / jest.mock() with typed mocks",codeFenceLanguage:"typescript"},javascript:{systemContext:"JavaScript with ES2022+ features, CommonJS or ESM modules.",conventions:["Use const/let, never var","Use arrow functions for callbacks","Prefer template literals for string interpolation"],assertionStyle:"expect(value).toBe(expected) \u2014 Jest matchers",mockingStyle:"jest.mock() with manual mock implementations",codeFenceLanguage:"javascript"},python:{systemContext:"Python 3.10+ with type hints, dataclasses, and async support.",conventions:["Follow PEP 8 naming (snake_case for functions, PascalCase for classes)","Use type hints on all function signatures","Use `pytest` fixtures for setup/teardown","Use `@pytest.mark.asyncio` for async tests"],assertionStyle:"assert value == expected \u2014 plain assert with pytest",mockingStyle:"unittest.mock.patch / pytest-mock fixtures",codeFenceLanguage:"python"},java:{systemContext:"Java 17+ with records, sealed classes, and pattern matching.",conventions:["Use JUnit 5 @Test and @DisplayName annotations","Use AssertJ fluent assertions (assertThat)","Follow given-when-then structure in test methods","Use @ExtendWith(MockitoExtension.class) for dependency injection"],assertionStyle:"assertThat(value).isEqualTo(expected) \u2014 AssertJ",mockingStyle:"Mockito @Mock, @InjectMocks, when().thenReturn()",codeFenceLanguage:"java"},csharp:{systemContext:"C# 11+ with nullable reference types, records, and async streams.",conventions:["Use xUnit [Fact] and [Theory] attributes","Use FluentAssertions for readable assertions","Follow Arrange-Act-Assert pattern","Use Moq for interface mocking"],assertionStyle:"value.Should().Be(expected) \u2014 FluentAssertions",mockingStyle:"new Mock<IService>().Setup(x => x.Method()).Returns(value)",codeFenceLanguage:"csharp"},go:{systemContext:"Go 1.21+ with generics, error wrapping, and context propagation.",conventions:["Use table-driven tests with t.Run subtests","Always check both value and error returns","Use testify/assert for assertions (or standard testing)","Mock interfaces with struct implementations"],assertionStyle:"assert.Equal(t, expected, actual) \u2014 testify",mockingStyle:"Interface-based mock structs",codeFenceLanguage:"go"},rust:{systemContext:"Rust with ownership, borrowing, lifetimes, and trait-based generics.",conventions:["Place tests in #[cfg(test)] mod tests { use super::*; }","Use assert!, assert_eq!, assert_ne! macros",'Use #[should_panic(expected = "...")] for panic tests',"Use #[tokio::test] for async tests"],assertionStyle:"assert_eq!(value, expected) \u2014 standard macros",mockingStyle:"mockall crate with #[automock] on traits",codeFenceLanguage:"rust"},swift:{systemContext:"Swift 5.10+ with Swift Testing framework, actors, and structured concurrency.",conventions:["Use @Test attribute with description strings","Use #expect() macro for assertions","Use @Suite for grouping related tests","Protocol-based mocking (manual stubs)"],assertionStyle:"#expect(value == expected) \u2014 Swift Testing macros",mockingStyle:"Protocol conformance with manual mock implementations",codeFenceLanguage:"swift"},kotlin:{systemContext:"Kotlin with coroutines, null safety, extension functions, and sealed classes.",conventions:["Use backtick test names: `should return user when id is valid`","Use MockK @MockK and coEvery for coroutine mocking","Use runTest { } for coroutine test wrappers","Use Turbine for Flow testing"],assertionStyle:"value shouldBe expected \u2014 Kotest matchers or JUnit assertEquals",mockingStyle:"MockK coEvery { service.call() } returns result",codeFenceLanguage:"kotlin"},dart:{systemContext:"Dart 3+ with null safety, records, and sealed classes. Flutter widgets.",conventions:["Use test() for unit tests, testWidgets() for widget tests","Use group() for test organization","Use @GenerateMocks for mockito code generation","Route Widget subclasses to testWidgets with pumpWidget"],assertionStyle:"expect(value, equals(expected)) \u2014 matcher-based",mockingStyle:"@GenerateMocks([ServiceClass]) + when(mock.method()).thenReturn(value)",codeFenceLanguage:"dart"}};function nc(s){return d6u[s]}function m6u(s,e=0){let u=(2166136261^e)>>>0;for(let a=0;a<s.length;a++)u^=s.charCodeAt(a),u=Math.imul(u,16777619),u=u>>>0;return u}function D6u(s,e=0){return m6u(s,e)%100<10}var h6u={defaultFramework:"vitest",maxTestsPerFile:50,coverageTargetDefault:80,enableAIGeneration:!0,enableLLMEnhancement:!0,llmModelTier:2,llmMaxTokens:2048,enableTestQualityGate:!0,enableEdgeCaseInjection:!0},jo=B.create("test-generation/test-generator"),Ht=class{config;memory;generatorFactory;tddGenerator;propertyTestGenerator;testDataGenerator;llmRouter;qualityGate;edgeCaseInjector;constructor(e,u={}){this.config={...h6u,...u},this.memory=e.memory,this.generatorFactory=e.generatorFactory||new ma,this.tddGenerator=e.tddGenerator||new Tt,this.propertyTestGenerator=e.propertyTestGenerator||new Mt,this.testDataGenerator=e.testDataGenerator||new jt,this.llmRouter=e.llmRouter,this.qualityGate=this.config.enableTestQualityGate?new ha:null,this.edgeCaseInjector=this.config.enableEdgeCaseInjection?new pa(this.memory):null}isLLMEnhancementAvailable(){return this.config.enableLLMEnhancement&&this.llmRouter!==void 0}getModelForTier(e){switch(e){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 enhanceTestWithLLM(e,u,a,t){if(!this.llmRouter)return e;try{let r=this.buildTestEnhancementPrompt(e,u,a);if(this.edgeCaseInjector)try{let o=t?.dependencies?"test-generation":void 0,l=await this.edgeCaseInjector.getInjectionContext(u,o);l.promptContext&&(r=l.promptContext+`
2019
2019
 
2020
2020
  `+r)}catch{jo.warn("Edge case injection failed, continuing without it")}if(t?.dependencies&&(r+=`
2021
2021
  ## Dependency Context (from Knowledge Graph):
@@ -2059,7 +2059,7 @@ ${e}
2059
2059
  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 ${a} code and suggest test cases:
2060
2060
  \`\`\`${this.getCodeFenceLanguage(a)}
2061
2061
  ${e}
2062
- \`\`\``}],model:t,maxTokens:1024,temperature:.5});if(r.content)try{let i=r.content.match(/\[[\s\S]*\]/);if(i)return T(i[0]).map(o=>o.name)}catch{}return[]}catch{return jo.warn("LLM suggestion generation failed:"),[]}}async generateTests(e){try{let u=ac({sourceFiles:e.sourceFiles,language:e.language,framework:e.framework,projectRoot:e.projectRoot}),a=e.framework||u?.framework||"vitest",t=e.language||u?.language,{sourceFiles:r,testType:i,coverageTarget:n=this.config.coverageTargetDefault,patterns:o=[]}=e;if(r.length===0)return m(new Error("No source files provided"));let l=[],c=[];for(let d of r){let D=await this.generateTestsForFile(d,i,a,o,t,e);D.success&&(l.push(...D.value.tests),c.push(...D.value.patternsUsed))}if(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true")for(let d of l)D6u(d.id)&&(d.holdout=!0);let E=this.estimateCoverage(l,n);return await this.storeGenerationMetadata(l,c),p({tests:l,coverageEstimate:E,patternsUsed:Array.from(new Set(c))})}catch(u){return m(g(u))}}async generateForCoverageGap(e,u,a){try{if(u.length===0)return p([]);let t=[],r=this.groupConsecutiveLines(u),i=this.generatorFactory.supports(a)?a:this.config.defaultFramework;for(let n of r){let o=await this.generateTestForLines(e,n,i);o&&t.push(o)}return p(t)}catch(t){return m(g(t))}}async generateTDDTests(e){try{let u=await this.tddGenerator.generateTDDTests(e);return p(u)}catch(u){return m(g(u))}}async generatePropertyTests(e){try{let u=await this.propertyTestGenerator.generatePropertyTests(e);return p(u)}catch(u){return m(g(u))}}async generateTestData(e){try{let u=await this.testDataGenerator.generateTestData(e);return p(u)}catch(u){return m(g(u))}}async generateTestsForFile(e,u,a,t,r,i){let n=this.getTestFilePath(e,a),o=[],l=await this.findApplicablePatterns(e,t);o.push(...l.map(w=>w.name));let c=null,E="";try{E=oc.readFileSync(e,"utf-8"),c=await this.analyzeSourceCode(E,e)}catch{}let d,D;this.memory&&E&&await this.hasKGVectors()&&(d=await this.queryKGDependencies(e,E),D=await this.queryKGSimilarCode(E));let h=this.generatorFactory.create(a),C=this.extractModuleName(e),y=this.getImportPath(e),x={moduleName:C,importPath:y,testType:u,patterns:l,analysis:c??void 0,dependencies:d,similarCode:D},b=h.generateTests(x);this.isLLMEnhancementAvailable()&&E&&(b=await this.enhanceTestWithLLM(b,E,c,x));let R={id:A(),name:`${C} tests`,sourceFile:e,testFile:n,testCode:b,type:u,assertions:this.countAssertions(b),language:r,framework:a,llmEnhanced:this.isLLMEnhancementAvailable()};if(i?.compileValidation&&r)try{let w=await rc.validate(b,r,i.projectRoot);R.compilationValidated=w.compiles,w.compiles||(R.compilationErrors=w.errors.map(P=>P.message))}catch{}return this.qualityGate&&(R.qualityGateResult=this.qualityGate.validate(b,e,E||void 0)),p({tests:[R],patternsUsed:o})}async generateTestForLines(e,u,a){if(u.length===0)return null;let t=A(),r=this.getTestFilePath(e,a),i=this.extractModuleName(e),n=this.getImportPath(e),l=this.generatorFactory.create(a).generateCoverageTests(i,n,u);return{id:t,name:`Coverage test for lines ${u[0]}-${u[u.length-1]}`,sourceFile:e,testFile:r,testCode:l,type:"unit",assertions:this.countAssertions(l)}}async analyzeSourceCode(e,u){let a=ga.extname(u),t=de(a);if(t&&t!=="typescript"&&t!=="javascript"){let l=await Z0.parseFile(e,u,t);if(l)return De.convertParsedFile(l)}let r=M.createSourceFile(ga.basename(u),e,M.ScriptTarget.Latest,!0,M.ScriptKind.TS),i=[],n=[],o=l=>{if(M.isFunctionDeclaration(l)&&l.name)i.push(this.extractFunctionInfo(l,r));else if(M.isVariableStatement(l)){for(let c of l.declarationList.declarations)if(M.isVariableDeclaration(c)&&c.initializer&&(M.isArrowFunction(c.initializer)||M.isFunctionExpression(c.initializer))){let E=c.name.getText(r);i.push(this.extractArrowFunctionInfo(E,c.initializer,r,l))}}else M.isClassDeclaration(l)&&l.name&&n.push(this.extractClassInfo(l,r));M.forEachChild(l,o)};return M.forEachChild(r,o),{functions:i,classes:n}}extractFunctionInfo(e,u){let a=e.name?.getText(u)||"anonymous",t=this.extractParameters(e.parameters,u),r=e.type?.getText(u),i=e.modifiers?.some(c=>c.kind===M.SyntaxKind.AsyncKeyword)??!1,n=e.modifiers?.some(c=>c.kind===M.SyntaxKind.ExportKeyword)??!1,{line:o}=u.getLineAndCharacterOfPosition(e.getStart(u)),{line:l}=u.getLineAndCharacterOfPosition(e.getEnd());return{name:a,parameters:t,returnType:r,isAsync:i,isExported:n,complexity:this.calculateComplexity(e),startLine:o+1,endLine:l+1,body:e.body?.getText(u)}}extractArrowFunctionInfo(e,u,a,t){let r=this.extractParameters(u.parameters,a),i=u.type?.getText(a),n=u.modifiers?.some(E=>E.kind===M.SyntaxKind.AsyncKeyword)??!1,o=M.isVariableStatement(t)&&(t.modifiers?.some(E=>E.kind===M.SyntaxKind.ExportKeyword)??!1),{line:l}=a.getLineAndCharacterOfPosition(u.getStart(a)),{line:c}=a.getLineAndCharacterOfPosition(u.getEnd());return{name:e,parameters:r,returnType:i,isAsync:n,isExported:o,complexity:this.calculateComplexity(u),startLine:l+1,endLine:c+1,body:u.body?.getText(a)}}extractClassInfo(e,u){let a=e.name?.getText(u)||"AnonymousClass",t=[],r=[],i=!1,n,o=e.modifiers?.some(l=>l.kind===M.SyntaxKind.ExportKeyword)??!1;for(let l of e.members)if(M.isMethodDeclaration(l)){let c=l.name.getText(u),E=this.extractParameters(l.parameters,u),d=l.type?.getText(u),D=l.modifiers?.some(y=>y.kind===M.SyntaxKind.AsyncKeyword)??!1,{line:h}=u.getLineAndCharacterOfPosition(l.getStart(u)),{line:C}=u.getLineAndCharacterOfPosition(l.getEnd());t.push({name:c,parameters:E,returnType:d,isAsync:D,isExported:!1,complexity:this.calculateComplexity(l),startLine:h+1,endLine:C+1,body:l.body?.getText(u)})}else if(M.isConstructorDeclaration(l))i=!0,n=this.extractParameters(l.parameters,u);else if(M.isPropertyDeclaration(l)){let c=l.name.getText(u),E=l.type?.getText(u),d=l.modifiers?.some(h=>h.kind===M.SyntaxKind.PrivateKeyword)??!1,D=l.modifiers?.some(h=>h.kind===M.SyntaxKind.ReadonlyKeyword)??!1;r.push({name:c,type:E,isPrivate:d,isReadonly:D})}return{name:a,methods:t,properties:r,isExported:o,hasConstructor:i,constructorParams:n}}extractParameters(e,u){let a=0,t=0;return e.map(r=>{let i=r.name.getText(u),n=r.type?.getText(u);return M.isObjectBindingPattern(r.name)?(a++,i=a>1?`options${a}`:"options",n||(n=`{ ${r.name.elements.map(l=>`${l.name.getText(u)}: unknown`).join(", ")} }`)):M.isArrayBindingPattern(r.name)&&(t++,i=t>1?`items${t}`:"items",n||(n="unknown[]")),{name:i,type:n,optional:r.questionToken!==void 0,defaultValue:r.initializer?.getText(u)}})}calculateComplexity(e){let u=1,a=t=>{switch(t.kind){case M.SyntaxKind.IfStatement:case M.SyntaxKind.ForStatement:case M.SyntaxKind.ForInStatement:case M.SyntaxKind.ForOfStatement:case M.SyntaxKind.WhileStatement:case M.SyntaxKind.DoStatement:case M.SyntaxKind.CaseClause:case M.SyntaxKind.CatchClause:case M.SyntaxKind.ConditionalExpression:u++;break;case M.SyntaxKind.BinaryExpression:{let r=t;(r.operatorToken.kind===M.SyntaxKind.AmpersandAmpersandToken||r.operatorToken.kind===M.SyntaxKind.BarBarToken)&&u++;break}}M.forEachChild(t,a)};return M.forEachChild(e,a),u}async hasKGVectors(){try{let e=new Array(384).fill(0);return e[0]=1,(await this.memory.vectorSearch(e,1)).length>0}catch{return!1}}async queryKGDependencies(e,u){try{let a=[],t=[],r=[],i=[],n=u.matchAll(/(?:import|from)\s+['"]([^'"]+)['"]/g);for(let d of n)a.push(d[1]);if(e.endsWith(".py")){let d=u.matchAll(/(?:^|\n)\s*(?:from\s+(\S+)\s+import|import\s+(\S+))/g);for(let D of d){let h=D[1]||D[2];h&&/^[a-zA-Z_][\w.]*$/.test(h)&&a.push(h)}}let c=e.replace(/\\/g,"/").split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/,"")||"",E=await this.memory.search(`code-intelligence:kg:node:*${c}*`,50);for(let d of E){if(!d.includes(c))continue;let D=d.split(":"),h=D[D.length-2],C=D[D.length-1];h==="function"&&r.push(C)}return a.length===0&&t.length===0&&r.length===0&&i.length===0?void 0:{imports:a,importedBy:t,callees:r,callers:i}}catch{return}}async queryKGSimilarCode(e){try{let u=this.generatePseudoEmbedding(e),a=await this.memory.vectorSearch(u,5);if(a.length===0)return;let t=[];for(let r of a){if(r.score<.1)continue;let i=r.metadata,n=i?.file||r.key,o=i?.name||i?.type||r.key.split(":").pop()||"";t.push({file:n,snippet:o,score:r.score})}return t.length>0?{snippets:t}:void 0}catch{return}}generatePseudoEmbedding(e){let a=new Array(384).fill(0),t=e.split(/[^a-zA-Z0-9_$]+/).filter(i=>i.length>1);for(let i=0;i<t.length;i++){let n=t[i];for(let o=0;o<n.length&&o<a.length;o++)a[(i+o)%384]+=n.charCodeAt(o)/1e3}let r=Math.sqrt(a.reduce((i,n)=>i+n*n,0));if(r>0)for(let i=0;i<384;i++)a[i]/=r;return a}getCodeFenceLanguage(e){try{let{FRAMEWORK_TO_LANGUAGE:u}=(d0(),l0(f4)),a=u?.[e];if(a){let t=nc(a);if(t)return t.codeFenceLanguage}}catch{}return"typescript"}convertParsedToCodeAnalysis(e){return De.convertParsedFile(e)}async findApplicablePatterns(e,u){let a=[];try{let{getUnifiedMemory:t}=await import("./unified-memory-H55OLMCH.js"),r=t().getDatabase();for(let o of u){let l=r.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2062
+ \`\`\``}],model:t,maxTokens:1024,temperature:.5});if(r.content)try{let i=r.content.match(/\[[\s\S]*\]/);if(i)return T(i[0]).map(o=>o.name)}catch{}return[]}catch{return jo.warn("LLM suggestion generation failed:"),[]}}async generateTests(e){try{let u=ac({sourceFiles:e.sourceFiles,language:e.language,framework:e.framework,projectRoot:e.projectRoot}),a=e.framework||u?.framework||"vitest",t=e.language||u?.language,{sourceFiles:r,testType:i,coverageTarget:n=this.config.coverageTargetDefault,patterns:o=[]}=e;if(r.length===0)return m(new Error("No source files provided"));let l=[],c=[];for(let d of r){let D=await this.generateTestsForFile(d,i,a,o,t,e);D.success&&(l.push(...D.value.tests),c.push(...D.value.patternsUsed))}if(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true")for(let d of l)D6u(d.id)&&(d.holdout=!0);let E=this.estimateCoverage(l,n);return await this.storeGenerationMetadata(l,c),p({tests:l,coverageEstimate:E,patternsUsed:Array.from(new Set(c))})}catch(u){return m(g(u))}}async generateForCoverageGap(e,u,a){try{if(u.length===0)return p([]);let t=[],r=this.groupConsecutiveLines(u),i=this.generatorFactory.supports(a)?a:this.config.defaultFramework;for(let n of r){let o=await this.generateTestForLines(e,n,i);o&&t.push(o)}return p(t)}catch(t){return m(g(t))}}async generateTDDTests(e){try{let u=await this.tddGenerator.generateTDDTests(e);return p(u)}catch(u){return m(g(u))}}async generatePropertyTests(e){try{let u=await this.propertyTestGenerator.generatePropertyTests(e);return p(u)}catch(u){return m(g(u))}}async generateTestData(e){try{let u=await this.testDataGenerator.generateTestData(e);return p(u)}catch(u){return m(g(u))}}async generateTestsForFile(e,u,a,t,r,i){let n=this.getTestFilePath(e,a),o=[],l=await this.findApplicablePatterns(e,t);o.push(...l.map(w=>w.name));let c=null,E="";try{E=oc.readFileSync(e,"utf-8"),c=await this.analyzeSourceCode(E,e)}catch{}let d,D;this.memory&&E&&await this.hasKGVectors()&&(d=await this.queryKGDependencies(e,E),D=await this.queryKGSimilarCode(E));let h=this.generatorFactory.create(a),C=this.extractModuleName(e),y=this.getImportPath(e),x={moduleName:C,importPath:y,testType:u,patterns:l,analysis:c??void 0,dependencies:d,similarCode:D},b=h.generateTests(x);this.isLLMEnhancementAvailable()&&E&&(b=await this.enhanceTestWithLLM(b,E,c,x));let R={id:A(),name:`${C} tests`,sourceFile:e,testFile:n,testCode:b,type:u,assertions:this.countAssertions(b),language:r,framework:a,llmEnhanced:this.isLLMEnhancementAvailable()};if(i?.compileValidation&&r)try{let w=await rc.validate(b,r,i.projectRoot);R.compilationValidated=w.compiles,w.compiles||(R.compilationErrors=w.errors.map(P=>P.message))}catch{}return this.qualityGate&&(R.qualityGateResult=this.qualityGate.validate(b,e,E||void 0)),p({tests:[R],patternsUsed:o})}async generateTestForLines(e,u,a){if(u.length===0)return null;let t=A(),r=this.getTestFilePath(e,a),i=this.extractModuleName(e),n=this.getImportPath(e),l=this.generatorFactory.create(a).generateCoverageTests(i,n,u);return{id:t,name:`Coverage test for lines ${u[0]}-${u[u.length-1]}`,sourceFile:e,testFile:r,testCode:l,type:"unit",assertions:this.countAssertions(l)}}async analyzeSourceCode(e,u){let a=ga.extname(u),t=de(a);if(t&&t!=="typescript"&&t!=="javascript"){let l=await Z0.parseFile(e,u,t);if(l)return De.convertParsedFile(l)}let r=M.createSourceFile(ga.basename(u),e,M.ScriptTarget.Latest,!0,M.ScriptKind.TS),i=[],n=[],o=l=>{if(M.isFunctionDeclaration(l)&&l.name)i.push(this.extractFunctionInfo(l,r));else if(M.isVariableStatement(l)){for(let c of l.declarationList.declarations)if(M.isVariableDeclaration(c)&&c.initializer&&(M.isArrowFunction(c.initializer)||M.isFunctionExpression(c.initializer))){let E=c.name.getText(r);i.push(this.extractArrowFunctionInfo(E,c.initializer,r,l))}}else M.isClassDeclaration(l)&&l.name&&n.push(this.extractClassInfo(l,r));M.forEachChild(l,o)};return M.forEachChild(r,o),{functions:i,classes:n}}extractFunctionInfo(e,u){let a=e.name?.getText(u)||"anonymous",t=this.extractParameters(e.parameters,u),r=e.type?.getText(u),i=e.modifiers?.some(c=>c.kind===M.SyntaxKind.AsyncKeyword)??!1,n=e.modifiers?.some(c=>c.kind===M.SyntaxKind.ExportKeyword)??!1,{line:o}=u.getLineAndCharacterOfPosition(e.getStart(u)),{line:l}=u.getLineAndCharacterOfPosition(e.getEnd());return{name:a,parameters:t,returnType:r,isAsync:i,isExported:n,complexity:this.calculateComplexity(e),startLine:o+1,endLine:l+1,body:e.body?.getText(u)}}extractArrowFunctionInfo(e,u,a,t){let r=this.extractParameters(u.parameters,a),i=u.type?.getText(a),n=u.modifiers?.some(E=>E.kind===M.SyntaxKind.AsyncKeyword)??!1,o=M.isVariableStatement(t)&&(t.modifiers?.some(E=>E.kind===M.SyntaxKind.ExportKeyword)??!1),{line:l}=a.getLineAndCharacterOfPosition(u.getStart(a)),{line:c}=a.getLineAndCharacterOfPosition(u.getEnd());return{name:e,parameters:r,returnType:i,isAsync:n,isExported:o,complexity:this.calculateComplexity(u),startLine:l+1,endLine:c+1,body:u.body?.getText(a)}}extractClassInfo(e,u){let a=e.name?.getText(u)||"AnonymousClass",t=[],r=[],i=!1,n,o=e.modifiers?.some(l=>l.kind===M.SyntaxKind.ExportKeyword)??!1;for(let l of e.members)if(M.isMethodDeclaration(l)){let c=l.name.getText(u),E=this.extractParameters(l.parameters,u),d=l.type?.getText(u),D=l.modifiers?.some(y=>y.kind===M.SyntaxKind.AsyncKeyword)??!1,{line:h}=u.getLineAndCharacterOfPosition(l.getStart(u)),{line:C}=u.getLineAndCharacterOfPosition(l.getEnd());t.push({name:c,parameters:E,returnType:d,isAsync:D,isExported:!1,complexity:this.calculateComplexity(l),startLine:h+1,endLine:C+1,body:l.body?.getText(u)})}else if(M.isConstructorDeclaration(l))i=!0,n=this.extractParameters(l.parameters,u);else if(M.isPropertyDeclaration(l)){let c=l.name.getText(u),E=l.type?.getText(u),d=l.modifiers?.some(h=>h.kind===M.SyntaxKind.PrivateKeyword)??!1,D=l.modifiers?.some(h=>h.kind===M.SyntaxKind.ReadonlyKeyword)??!1;r.push({name:c,type:E,isPrivate:d,isReadonly:D})}return{name:a,methods:t,properties:r,isExported:o,hasConstructor:i,constructorParams:n}}extractParameters(e,u){let a=0,t=0;return e.map(r=>{let i=r.name.getText(u),n=r.type?.getText(u);return M.isObjectBindingPattern(r.name)?(a++,i=a>1?`options${a}`:"options",n||(n=`{ ${r.name.elements.map(l=>`${l.name.getText(u)}: unknown`).join(", ")} }`)):M.isArrayBindingPattern(r.name)&&(t++,i=t>1?`items${t}`:"items",n||(n="unknown[]")),{name:i,type:n,optional:r.questionToken!==void 0,defaultValue:r.initializer?.getText(u)}})}calculateComplexity(e){let u=1,a=t=>{switch(t.kind){case M.SyntaxKind.IfStatement:case M.SyntaxKind.ForStatement:case M.SyntaxKind.ForInStatement:case M.SyntaxKind.ForOfStatement:case M.SyntaxKind.WhileStatement:case M.SyntaxKind.DoStatement:case M.SyntaxKind.CaseClause:case M.SyntaxKind.CatchClause:case M.SyntaxKind.ConditionalExpression:u++;break;case M.SyntaxKind.BinaryExpression:{let r=t;(r.operatorToken.kind===M.SyntaxKind.AmpersandAmpersandToken||r.operatorToken.kind===M.SyntaxKind.BarBarToken)&&u++;break}}M.forEachChild(t,a)};return M.forEachChild(e,a),u}async hasKGVectors(){try{let e=new Array(384).fill(0);return e[0]=1,(await this.memory.vectorSearch(e,1)).length>0}catch{return!1}}async queryKGDependencies(e,u){try{let a=[],t=[],r=[],i=[],n=u.matchAll(/(?:import|from)\s+['"]([^'"]+)['"]/g);for(let d of n)a.push(d[1]);if(e.endsWith(".py")){let d=u.matchAll(/(?:^|\n)\s*(?:from\s+(\S+)\s+import|import\s+(\S+))/g);for(let D of d){let h=D[1]||D[2];h&&/^[a-zA-Z_][\w.]*$/.test(h)&&a.push(h)}}let c=e.replace(/\\/g,"/").split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/,"")||"",E=await this.memory.search(`code-intelligence:kg:node:*${c}*`,50);for(let d of E){if(!d.includes(c))continue;let D=d.split(":"),h=D[D.length-2],C=D[D.length-1];h==="function"&&r.push(C)}return a.length===0&&t.length===0&&r.length===0&&i.length===0?void 0:{imports:a,importedBy:t,callees:r,callers:i}}catch{return}}async queryKGSimilarCode(e){try{let u=this.generatePseudoEmbedding(e),a=await this.memory.vectorSearch(u,5);if(a.length===0)return;let t=[];for(let r of a){if(r.score<.1)continue;let i=r.metadata,n=i?.file||r.key,o=i?.name||i?.type||r.key.split(":").pop()||"";t.push({file:n,snippet:o,score:r.score})}return t.length>0?{snippets:t}:void 0}catch{return}}generatePseudoEmbedding(e){let a=new Array(384).fill(0),t=e.split(/[^a-zA-Z0-9_$]+/).filter(i=>i.length>1);for(let i=0;i<t.length;i++){let n=t[i];for(let o=0;o<n.length&&o<a.length;o++)a[(i+o)%384]+=n.charCodeAt(o)/1e3}let r=Math.sqrt(a.reduce((i,n)=>i+n*n,0));if(r>0)for(let i=0;i<384;i++)a[i]/=r;return a}getCodeFenceLanguage(e){try{let{FRAMEWORK_TO_LANGUAGE:u}=(d0(),l0(f4)),a=u?.[e];if(a){let t=nc(a);if(t)return t.codeFenceLanguage}}catch{}return"typescript"}convertParsedToCodeAnalysis(e){return De.convertParsedFile(e)}async findApplicablePatterns(e,u){let a=[];try{let{getUnifiedMemory:t}=await import("./unified-memory-CZCWZUFP.js"),r=t().getDatabase();for(let o of u){let l=r.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2063
2063
  FROM qe_patterns WHERE id = ? OR name = ? LIMIT 1`).get(o,o);l&&a.push({id:l.id,name:l.name,structure:l.pattern_type,examples:l.usage_count,applicability:l.quality_score})}let i=e.split(".").pop()||"",n=r.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2064
2064
  FROM qe_patterns
2065
2065
  WHERE qe_domain = 'test-generation'
@@ -2149,7 +2149,7 @@ Individual assessments:`),e.forEach(i=>{let n=this.countsAsAgreement(i)?"\u2713
2149
2149
  created_at TEXT DEFAULT (datetime('now')),
2150
2150
  updated_at TEXT DEFAULT (datetime('now'))
2151
2151
  );
2152
- `,hs={loadOnInit:!0,autoSaveInterval:0,maxPatternsToLoad:1e4,enableCrossProcessSharing:!0},Zt=class{baseEngine;config;persistence=null;db=null;prepared=new Map;initialized=!1;initPromise=null;pendingSaves=new Map;saveTimer=null;serverClient=null;constructor(e){this.config={...hs,...e},this.baseEngine=new n4(e),this.serverClient=e.serverClient??null}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{this.persistence=Et(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureSchema(),this.prepareStatements(),this.config.loadOnInit&&await this.loadPatterns();let{isSONAThreeLoopEnabled:e}=await import("./feature-flags-NQHRPIUT.js");if(e()){this.baseEngine.initThreeLoopEngine(),this.baseEngine.setFisherPersistence((a,t,r,i,n)=>{this.saveFisherMatrix(a,t,r,i,n)},this.config.domain);let u=this._loadFisherMatrixUnsafe(this.config.domain);if(u){let a=this.baseEngine.getThreeLoopEngine();a&&(a.restoreFisher({fisherDiagonal:u.fisherDiagonal,optimalParams:u.optimalParams,baseWeights:u.baseWeights,requestCount:u.requestCount}),Ut.info("Three-loop engine restored Fisher state from SQLite",{domain:this.config.domain,requestCount:u.requestCount,taskBoundaries:u.taskBoundaries}))}Ut.info("Three-loop engine initialized with Fisher persistence",{domain:this.config.domain})}this.initialized=!0,console.log(`[PersistentSONAEngine] Initialized: domain=${this.config.domain}`)}catch(e){throw this.initPromise=null,new Error(`Failed to initialize PersistentSONAEngine: ${k(e)}`)}}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(vc)),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(Fc))}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(`
2152
+ `,hs={loadOnInit:!0,autoSaveInterval:0,maxPatternsToLoad:1e4,enableCrossProcessSharing:!0},Zt=class{baseEngine;config;persistence=null;db=null;prepared=new Map;initialized=!1;initPromise=null;pendingSaves=new Map;saveTimer=null;serverClient=null;constructor(e){this.config={...hs,...e},this.baseEngine=new n4(e),this.serverClient=e.serverClient??null}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{this.persistence=Et(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureSchema(),this.prepareStatements(),this.config.loadOnInit&&await this.loadPatterns();let{isSONAThreeLoopEnabled:e}=await import("./feature-flags-V34UZPHG.js");if(e()){this.baseEngine.initThreeLoopEngine(),this.baseEngine.setFisherPersistence((a,t,r,i,n)=>{this.saveFisherMatrix(a,t,r,i,n)},this.config.domain);let u=this._loadFisherMatrixUnsafe(this.config.domain);if(u){let a=this.baseEngine.getThreeLoopEngine();a&&(a.restoreFisher({fisherDiagonal:u.fisherDiagonal,optimalParams:u.optimalParams,baseWeights:u.baseWeights,requestCount:u.requestCount}),Ut.info("Three-loop engine restored Fisher state from SQLite",{domain:this.config.domain,requestCount:u.requestCount,taskBoundaries:u.taskBoundaries}))}Ut.info("Three-loop engine initialized with Fisher persistence",{domain:this.config.domain})}this.initialized=!0,console.log(`[PersistentSONAEngine] Initialized: domain=${this.config.domain}`)}catch(e){throw this.initPromise=null,new Error(`Failed to initialize PersistentSONAEngine: ${k(e)}`)}}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(vc)),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(Fc))}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(`
2153
2153
  SELECT * FROM sona_patterns
2154
2154
  WHERE domain = ?
2155
2155
  ORDER BY confidence DESC, updated_at DESC
@@ -2274,7 +2274,7 @@ Individual assessments:`),e.forEach(i=>{let n=this.countsAsAgreement(i)?"\u2713
2274
2274
  MIN(created_at) as oldest_entry,
2275
2275
  MAX(created_at) as newest_entry
2276
2276
  FROM rl_q_values
2277
- `))}async getQValue(e,u,a,t){this.ensureInitialized();let r=this.prepared.get("getQValue");if(!r)throw new Error("Statement not prepared");let i=t??this.config.defaultAlgorithm;return r.get(e,u,a,i)?.q_value??0}async setQValue(e,u,a,t,r,i){this.ensureInitialized();let n=this.prepared.get("upsertQValue");if(!n)throw new Error("Statement not prepared");let o=A(),l=i?.algorithm??this.config.defaultAlgorithm;n.run(o,l,e,u,a,t,r??null,i?.domain??null)}async incrementVisits(e,u,a,t){this.ensureInitialized();let r=this.prepared.get("incrementVisits");if(!r)throw new Error("Statement not prepared");let i=t??this.config.defaultAlgorithm;r.run(e,u,a,i)}async getTopActions(e,u,a=10,t){this.ensureInitialized();let r=this.prepared.get("getTopActions");if(!r)throw new Error("Statement not prepared");let i=t??this.config.defaultAlgorithm;return r.all(e,u,i,a).map(o=>this.rowToEntry(o))}async exportForAgent(e,u){this.ensureInitialized();let a=this.prepared.get("getAllForAgent");if(!a)throw new Error("Statement not prepared");let t=u??this.config.defaultAlgorithm,r=a.all(e,t),i=new Map;for(let n of r){let o=n.state_key,l=n.action_key,c=n.q_value;i.has(o)||i.set(o,new Map),i.get(o).set(l,c)}return i}async importFromMap(e,u,a){if(this.ensureInitialized(),!this.db)throw new Error("Database not initialized");let t=this.prepared.get("upsertQValue");if(!t)throw new Error("Statement not prepared");let r=a?.algorithm??this.config.defaultAlgorithm;this.db.transaction(()=>{for(let[n,o]of u)for(let[l,c]of o){let E=A();t.run(E,r,e,n,l,c,null,a?.domain??null)}})()}async pruneOldEntries(e){this.ensureInitialized();let u=this.prepared.get("pruneOld");if(!u)throw new Error("Statement not prepared");return u.run(e).changes}async getStats(){this.ensureInitialized();let e=this.prepared.get("getStats"),u=this.prepared.get("countByAlgorithm"),a=this.prepared.get("countByDomain");if(!e||!u||!a)throw new Error("Statements not prepared");let t=e.get(),r=u.all(),i=a.all(),n={};for(let l of r)n[l.algorithm]=l.count;let o={};for(let l of i)l.domain&&(o[l.domain]=l.count);return{totalEntries:t.total_entries,uniqueAgents:t.unique_agents,uniqueStates:t.unique_states,byAlgorithm:n,byDomain:o,averageVisits:t.avg_visits??0,averageQValue:t.avg_q_value??0,oldestEntry:t.oldest_entry?new Date(t.oldest_entry):null,newestEntry:t.newest_entry?new Date(t.newest_entry):null}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}async getEntry(e,u,a,t){this.ensureInitialized();let r=this.prepared.get("getEntry");if(!r)throw new Error("Statement not prepared");let i=t??this.config.defaultAlgorithm,n=r.get(e,u,a,i);return n?this.rowToEntry(n):null}async deleteEntry(e,u,a,t){this.ensureInitialized();let r=this.prepared.get("deleteEntry");if(!r)throw new Error("Statement not prepared");let i=t??this.config.defaultAlgorithm;return r.run(e,u,a,i).changes>0}isInitialized(){return this.initialized}getDbPath(){return this.persistence?.getDbPath()??""}ensureInitialized(){if(!this.initialized)throw new Error("QValueStore not initialized. Call initialize() first.")}rowToEntry(e){return{id:e.id,algorithm:e.algorithm,agentId:e.agent_id,stateKey:e.state_key,actionKey:e.action_key,qValue:e.q_value,visits:e.visits,lastReward:e.last_reward,domain:e.domain,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}};J();N();var kc=B.create("rl-base-algorithm"),Sc={learningRate:.001,discountFactor:.99,episodes:1e3,maxSteps:1e3,batchSize:32,replayBufferSize:1e4,targetUpdateFrequency:100,explorationRate:.3,explorationDecay:.995,minExplorationRate:.01},I6u={enabled:!1,autoSaveInterval:10},Eu=class{constructor(e,u,a={},t=[],r={}){this.type=e;this.category=u;this.config={...Sc,...a},this.rewardSignals=t,this.persistenceConfig={...I6u,...r},this.stats=this.createInitialStats()}config;stats;replayBuffer=[];episodeCount=0;totalReward=0;rewardHistory=[];initialized=!1;rewardSignals=[];persistenceConfig;qValueStore=null;lastSaveEpisode=0;enablePersistence(e,u){this.persistenceConfig.enabled=!0,this.persistenceConfig.agentId=e,u&&(this.persistenceConfig.dbPath=u)}isPersistenceEnabled(){return this.persistenceConfig.enabled&&!!this.persistenceConfig.agentId}getPersistenceAgentId(){return this.persistenceConfig.agentId}async train(e){if(this.addToReplayBuffer(e),this.replayBuffer.length>=this.config.batchSize){let u=this.sampleBatch();return this.trainBatch(u)}return this.getStats()}async trainBatch(e){this.initialized||await this.initialize();let u=Date.now();try{this.episodeCount++;let a=e.reduce((r,i)=>r+i.reward,0);this.totalReward+=a,this.rewardHistory.push(a),this.rewardHistory.length>1e3&&this.rewardHistory.shift();let t=await this.trainCore(e);return this.stats={...t,episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((r,i)=>r+i,0)/this.rewardHistory.length,trainingTimeMs:Date.now()-u,timestamp:new Date},this.config.explorationRate=Math.max(this.config.minExplorationRate,this.config.explorationRate*this.config.explorationDecay),this.stats.explorationRate=this.config.explorationRate,await this.autoSaveToPersistence(),this.stats}catch(a){throw new Yt(`Training failed for ${this.type}: ${a.message}`,this.type,a)}}async autoSaveToPersistence(){if(!this.isPersistenceEnabled()||this.persistenceConfig.autoSaveInterval<=0)return;if(this.episodeCount-this.lastSaveEpisode>=this.persistenceConfig.autoSaveInterval)try{await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.lastSaveEpisode=this.episodeCount}catch(u){console.warn(`[${this.type}] Auto-save failed:`,u.message)}}async update(e){let u={...this.config};if(this.config={...this.config,...e},this.config.learningRate<=0||this.config.learningRate>1)throw new ge(`Invalid learning rate: ${this.config.learningRate}`,this.type);if(this.config.discountFactor<0||this.config.discountFactor>1)throw new ge(`Invalid discount factor: ${this.config.discountFactor}`,this.type);if(this.config.explorationRate<0||this.config.explorationRate>1)throw new ge(`Invalid exploration rate: ${this.config.explorationRate}`,this.type);await this.handleConfigUpdate(u,this.config)}getStats(){return{...this.stats}}async reset(){this.isPersistenceEnabled()&&this.episodeCount>0&&await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.replayBuffer=[],this.episodeCount=0,this.totalReward=0,this.rewardHistory=[],this.lastSaveEpisode=0,this.config.explorationRate=Sc.explorationRate,this.stats=this.createInitialStats(),await this.resetAlgorithm()}async close(){this.isPersistenceEnabled()&&this.episodeCount>this.lastSaveEpisode&&await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.qValueStore&&(await this.qValueStore.close(),this.qValueStore=null)}async exportModel(){return{type:this.type,category:this.category,version:this.getVersion(),config:this.config,stats:this.stats,replayBufferSize:this.replayBuffer.length,exportedAt:new Date().toISOString(),customData:await this.exportCustomData()}}async importModel(e){if(e.type!==this.type)throw new ge(`Model type mismatch: expected ${this.type}, got ${e.type}`,this.type);if(e.category!==this.category)throw new ge(`Algorithm category mismatch: expected ${this.category}, got ${e.category}`,this.type);e.config&&(this.config={...this.config,...e.config}),e.stats&&(this.stats={...this.stats,...e.stats}),e.customData&&await this.importCustomData(e.customData),this.initialized=!0}getInfo(){let e=this.getAlgorithmInfo();return{...e,stats:this.stats,hyperparameters:{...e.hyperparameters,learningRate:this.config.learningRate,discountFactor:this.config.discountFactor,explorationRate:this.config.explorationRate,batchSize:this.config.batchSize}}}async saveToStore(e,u){let a=u??new Ce;await a.initialize();let t=await this.exportModel();await a.setQValue(e,"__model_state__","__weights__",0,void 0,{algorithm:this.type,domain:JSON.stringify(t)})}async loadFromStore(e,u){let a=u??new Ce;await a.initialize();try{let t=await a.getQValue(e,"__model_state__","__weights__",this.type),r=await a.getEntry(e,"__model_state__","__weights__",this.type);if(!r?.domain)return!1;let i=T(r.domain);return await this.importModel(i),!0}catch(t){return kc.debug("Model load from store failed",{algorithm:this.type,error:t instanceof Error?t.message:String(t)}),!1}}async storeQValue(e,u,a,t,r,i){let n=i??new Ce;await n.initialize(),await n.setQValue(e,u,a,t,r,{algorithm:this.type})}async retrieveQValue(e,u,a,t){let r=t??new Ce;await r.initialize();try{return await r.getQValue(e,u,a,this.type)}catch(i){return kc.debug("Q-value retrieval failed",{agentId:e,stateKey:u,actionKey:a,error:i instanceof Error?i.message:String(i)}),null}}calculateReward(e){let u={},a=0,t=[];for(let r of this.rewardSignals){let i=r.calculate(e);u[r.name]=i,a+=i,i!==0&&t.push(`${r.name}: ${i.toFixed(3)} (${r.description})`)}return{totalReward:Math.max(-1,Math.min(1,a)),components:u,reasoning:t.join("; ")||"No reward signals triggered",timestamp:new Date}}addToReplayBuffer(e){this.replayBuffer.push(e),this.replayBuffer.length>this.config.replayBufferSize&&this.replayBuffer.shift()}sampleBatch(e){let u=e||this.config.batchSize,a=this.replayBuffer;if(a.length===0)return[];if(a.length<=u)return[...a];let t=new Set;for(;t.size<Math.min(u,a.length);)t.add(Du(0,a.length));return Array.from(t).map(r=>a[r])}epsilonGreedy(e,u){return K()<this.config.explorationRate?e():u()}normalizeFeatures(e){if(e.length===0)return[];let u=Math.max(...e.map(Math.abs));return u===0?e:e.map(a=>a/u)}stateToKey(e){let u=e.features.map((a,t)=>`${t}:${Math.round(a*100)/100}`).join(",");return`${e.id}|${u}`}async initialize(){this.isPersistenceEnabled()&&(await this.initializePersistence(),await this.loadFromStore(this.persistenceConfig.agentId)&&console.log(`[${this.type}] Loaded persisted state for agent: ${this.persistenceConfig.agentId}`)),this.initialized=!0}async initializePersistence(){this.qValueStore||(this.qValueStore=new Ce,await this.qValueStore.initialize())}async resetAlgorithm(){}async handleConfigUpdate(e,u){}async exportCustomData(){return{}}async importCustomData(e){}getVersion(){return"1.0.0"}createInitialStats(){return{episode:0,totalReward:0,averageReward:0,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}};ct();var K6u={contextLength:10,embeddingDim:384,numHeads:4,numLayers:3,feedForwardDim:256,maxReturn:100},A0=class extends Eu{trajectories=[];dtConfig;stateEmbeddings=new Map;actionEmbeddings=new Map;constructor(e={}){super("decision-transformer","offline-rl"),this.dtConfig={...K6u,...e}}async predict(e){this.initialized||await this.initialize();let u=this.retrieveContext(e),a=this.calculateReturnToGo(u),t=this.generateAction(e,u,a),r=this.calculateConfidence(u,a);return{action:t,confidence:r,value:a,reasoning:this.generateReasoning(e,t,u,a)}}async trainCore(e){let u=this.groupIntoTrajectories(e);for(let t of u)this.calculateReturns(t);this.trajectories.push(...u),this.trajectories.length>1e3&&(this.trajectories=this.trajectories.slice(-1e3)),this.updateEmbeddings(u);let a=u.reduce((t,r)=>t+r.returns[r.returns.length-1],0)/u.length;return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((t,r)=>t+r,0)/this.rewardHistory.length,loss:Math.abs(a-this.targetReturn()),explorationRate:0,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"1.0.0",description:"Decision Transformer for Test Case Prioritization",capabilities:["Offline RL from historical data","Attention-based sequence modeling","Return-to-go conditioning","Context-aware decisions"],hyperparameters:{contextLength:this.dtConfig.contextLength,embeddingDim:this.dtConfig.embeddingDim,numHeads:this.dtConfig.numHeads,numLayers:this.dtConfig.numLayers},stats:this.stats}}retrieveContext(e){let u=this.trajectories.map(a=>{let t=this.calculateSimilarity(e,a);return{traj:a,similarity:t}});return u.sort((a,t)=>t.similarity-a.similarity),u.slice(0,this.dtConfig.contextLength).map(a=>a.traj)}calculateSimilarity(e,u){for(let a of u.states)if(this.statesMatch(e,a))return 1;if(u.states.length>0){let a=u.states[u.states.length-1];return ce(e.features,a.features)}return 0}statesMatch(e,u){return e.id===u.id||Math.abs(e.features[0]-u.features[0])<.1}calculateReturnToGo(e){if(e.length===0)return 0;let u=e.flatMap(a=>a.returns);return u.reduce((a,t)=>a+t,0)/u.length}calculateReturns(e){let u=[],a=0;for(let t=e.rewards.length-1;t>=0;t--)a=e.rewards[t]+this.config.discountFactor*a,u.unshift(a);e.returns=u}targetReturn(){return this.dtConfig.maxReturn*.8}generateAction(e,u,a){for(let t of u)for(let r=0;r<t.states.length;r++)if(this.statesMatch(e,t.states[r])&&t.returns[r]>a*.8)return{...t.actions[r]};return this.getHeuristicAction(e)}getHeuristicAction(e){return{type:"prioritize",value:e.features[0]>.7?"high":"standard",metadata:{heuristic:!0}}}updateEmbeddings(e){for(let u of e){for(let a of u.states)this.stateEmbeddings.has(a.id)||this.stateEmbeddings.set(a.id,this.hashEmbedding(a.id));for(let a of u.actions){let t=this.actionToKey(a);this.actionEmbeddings.has(t)||this.actionEmbeddings.set(t,this.hashEmbedding(t))}}}hashEmbedding(e){let u=[],a=this.dtConfig.embeddingDim;for(let t=0;t<a;t++){let r=this.simpleHash(e+t);u.push((r%200-100)/100)}return u}simpleHash(e){let u=0;for(let a=0;a<e.length;a++){let t=e.charCodeAt(a);u=(u<<5)-u+t,u=u&u}return Math.abs(u)}actionToKey(e){return`${e.type}:${JSON.stringify(e.value)}`}groupIntoTrajectories(e){let u=[],a=null;for(let t of e)t.done||!a?(a&&u.push(a),a={states:[t.state],actions:[t.action],rewards:[t.reward],returns:[]}):(a.states.push(t.state),a.actions.push(t.action),a.rewards.push(t.reward));return a&&u.push(a),u}calculateConfidence(e,u){if(e.length===0)return .3;let a=Math.min(1,e.length/this.dtConfig.contextLength),t=Math.min(1,u/this.targetReturn());return .3+a*.4+t*.3}generateReasoning(e,u,a,t){if(a.length===0)return"Decision Transformer: No similar historical contexts, using heuristic";let r=a.reduce((i,n)=>i+n.returns[n.returns.length-1]||0,0)/a.length;return`Decision Transformer: Found ${a.length} similar contexts (avg return: ${r.toFixed(2)}), selecting ${u.type} action with return-to-go ${t.toFixed(2)}`}async exportCustomData(){return{trajectories:this.trajectories,stateEmbeddings:Object.fromEntries(this.stateEmbeddings),actionEmbeddings:Object.fromEntries(this.actionEmbeddings),dtConfig:this.dtConfig}}async importCustomData(e){e.trajectories&&(this.trajectories=e.trajectories),e.stateEmbeddings&&(this.stateEmbeddings=new Map(Object.entries(e.stateEmbeddings))),e.actionEmbeddings&&(this.actionEmbeddings=new Map(Object.entries(e.actionEmbeddings))),e.dtConfig&&(this.dtConfig={...this.dtConfig,...e.dtConfig})}async resetAlgorithm(){this.trajectories=[],this.stateEmbeddings.clear(),this.actionEmbeddings.clear()}};Qu();N();var wc={enabled:!0,coherenceThreshold:.1,blockOnHumanLane:!0,enrichOnRetrievalLane:!0,embeddingDimension:384},j6u=B.create("test-generation/coherence-gate"),Xt=class extends Error{constructor(u,a,t){super(u);this.contradictions=a;this.lane=t;this.name="CoherenceError"}},ps=class{constructor(e=384){this.dimension=e}async embed(e){let u=new Array(this.dimension).fill(0),a=e.toLowerCase().trim();for(let r=0;r<a.length;r++){let i=a.charCodeAt(r),n=r%this.dimension;u[n]+=Math.sin(i*(r+1)*.1),u[(n+1)%this.dimension]+=Math.cos(i*(r+1)*.1)}let t=Math.sqrt(u.reduce((r,i)=>r+i*i,0));if(t>0)for(let r=0;r<u.length;r++)u[r]/=t;return u}},ur=class{constructor(e,u,a={}){this.coherenceService=e;this.config={...wc,...a},this.embeddingService=u||new ps(this.config.embeddingDimension)}config;embeddingService;async checkRequirementCoherence(e){let u=Date.now();if(!this.config.enabled||!this.coherenceService)return this.createPassingResult(u,!0);if(e.length===0)return this.createPassingResult(u,!1);if(e.length===1)return this.createPassingResult(u,!1);try{let a=await this.requirementsToNodes(e),t=await this.coherenceService.checkCoherence(a);return this.transformCoherenceResult(t,e,Date.now()-u)}catch(a){return j6u.error("Coherence check failed:",a instanceof Error?a:void 0),{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[{type:"add-context",requirementId:"",description:"Coherence check failed. Manual review recommended.",suggestedResolution:"Review requirements manually before proceeding."}],durationMs:Date.now()-u,usedFallback:!0}}}async enrichSpecification(e,u){if(u.length===0)return e;let a={...e,requirements:[...e.requirements],context:{...e.context}},t=new Map;for(let r of u)switch(r.type){case"clarify":this.addClarificationNote(t,r);break;case"add-context":a.context={...a.context,coherenceRecommendations:[...a.context?.coherenceRecommendations||[],r.description]};break;case"resolve-ambiguity":this.addDisambiguationNote(t,r);break;case"split-requirement":a.context={...a.context,requirementsSuggestedForSplit:[...a.context?.requirementsSuggestedForSplit||[],r.requirementId]};break}return a.requirements=a.requirements.map(r=>{let i=t.get(r.id);return i?{...r,metadata:{...r.metadata,...i.metadata}}:r}),a.context={...a.context,enrichedAt:new Date().toISOString(),enrichmentCount:u.length},a}async validateAndEnrich(e){let u=await this.checkRequirementCoherence(e.requirements);if(this.config.blockOnHumanLane&&u.lane==="human")return m(new Xt("Requirements contain unresolvable contradictions that require human review",u.contradictions,u.lane));if(this.config.enrichOnRetrievalLane&&u.lane==="retrieval"){let a=await this.enrichSpecification(e,u.recommendations);return p(a)}return p(e)}isAvailable(){return this.coherenceService?.isInitialized()??!1}async requirementsToNodes(e){let u=[];for(let a of e){let t=await this.embeddingService.embed(a.description);u.push({id:a.id,embedding:t,weight:this.priorityToWeight(a.priority),metadata:{description:a.description,source:a.source,...a.metadata}})}return u}transformCoherenceResult(e,u,a){let t=new Map(u.map(n=>[n.id,n])),r=e.contradictions.map(n=>({requirementId1:n.nodeIds[0],requirementId2:n.nodeIds[1],severity:this.mapSeverity(n.severity),description:n.description,confidence:n.confidence,suggestedResolution:n.resolution||this.generateResolutionSuggestion(t.get(n.nodeIds[0]),t.get(n.nodeIds[1]),n.severity)})),i=this.generateRecommendations(e,r,u);return{isCoherent:e.isCoherent,energy:e.energy,lane:e.lane,contradictions:r,recommendations:i,durationMs:a,usedFallback:e.usedFallback}}generateRecommendations(e,u,a){let t=[];for(let i of e.recommendations)t.push({type:"add-context",requirementId:"",description:i});for(let i of u)i.severity==="critical"||i.severity==="high"?t.push({type:"resolve-ambiguity",requirementId:i.requirementId1,description:`Potential conflict with requirement ${i.requirementId2}: ${i.description}`,suggestedResolution:i.suggestedResolution}):t.push({type:"clarify",requirementId:i.requirementId1,description:`Minor tension with requirement ${i.requirementId2}: ${i.description}`});let r=a.filter(i=>i.description.length>200||i.description.includes(" and ")&&i.description.includes(" or "));for(let i of r)t.push({type:"split-requirement",requirementId:i.id,description:"Complex requirement may benefit from splitting into smaller, focused requirements"});return t}generateResolutionSuggestion(e,u,a){return!e||!u?"Review and reconcile conflicting requirements.":a==="critical"?`Requirements "${e.id}" and "${u.id}" appear to be mutually exclusive. Consider removing one or explicitly documenting the conditions under which each applies.`:a==="high"?`Requirements "${e.id}" and "${u.id}" may conflict. Add clarification about their relationship and precedence.`:`Minor tension between "${e.id}" and "${u.id}". Consider adding context to clarify their relationship.`}createPassingResult(e,u){return{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:Date.now()-e,usedFallback:u}}priorityToWeight(e){switch(e){case"high":return 1;case"medium":return .7;case"low":return .4;default:return .5}}mapSeverity(e){switch(e){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}addClarificationNote(e,u){let a=e.get(u.requirementId)||{metadata:{}},t=a.metadata?.clarificationNotes||[];t.push(u.description),e.set(u.requirementId,{...a,metadata:{...a.metadata,clarificationNotes:t,needsClarification:!0}})}addDisambiguationNote(e,u){let a=e.get(u.requirementId)||{metadata:{}},t=a.metadata?.disambiguationNotes||[];t.push(u.description),e.set(u.requirementId,{...a,metadata:{...a.metadata,disambiguationNotes:t,needsDisambiguation:!0,suggestedResolution:u.suggestedResolution}})}};function gs(s,e,u){return new ur(s,e,u)}var H6u={maxConcurrentWorkflows:5,defaultTimeout:6e4,enablePatternLearning:!0,publishEvents:!0,enableQESONA:!0,enableFlashAttention:!0,enableDecisionTransformer:!0,sonaPatternType:"test-generation",flashAttentionWorkload:"test-similarity",enableCoherenceGate:!0,blockOnIncoherentRequirements:!0,enrichOnRetrievalLane:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Q=B.create("test-generation"),Sa=class extends Y{constructor(u,a,t,r={},i,n){let o={...H6u,...r};super(u,"test-generation",o,{verifyFindingTypes:["test-pattern-selection","mock-strategy","edge-case-generation","assertion-strategy"],...o.consensusConfig});this.memory=a;this.agentCoordinator=t;this.coherenceService=i;this.hookRegistry=n;this.testGenerator=Ie(a),this.patternMatcher=new Ke(a),this.config.enableCoherenceGate&&i&&(this.coherenceGate=gs(i,void 0,{enabled:!0,blockOnHumanLane:this.config.blockOnIncoherentRequirements,enrichOnRetrievalLane:this.config.enrichOnRetrievalLane}))}testGenerator;patternMatcher;qesona=null;flashAttention=null;decisionTransformer=null;testEmbeddings=new Map;recentDreamInsights=[];coherenceGate=null;async onInitialize(){if(this.config.enableQESONA)try{this.qesona=await gu({domain:"test-generation",loadOnInit:!0,autoSaveInterval:6e4,patternClusters:50,minConfidence:.5}),Q.info("PersistentSONAEngine initialized for test-generation domain")}catch(u){Q.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),Q.warn("Continuing without SONA pattern persistence"),this.qesona=null}if(this.config.enableFlashAttention)try{this.flashAttention=await Ku(this.config.flashAttentionWorkload,{dim:384,strategy:"flash",blockSize:64}),Q.info("QEFlashAttention initialized for test-similarity")}catch{Q.warn("QEFlashAttention unavailable (optional native module), continuing without it"),this.flashAttention=null}if(this.config.enableDecisionTransformer)try{this.decisionTransformer=new A0({contextLength:10,embeddingDim:384}),Q.info("DecisionTransformer created for test case selection")}catch{Q.warn("DecisionTransformer unavailable (optional native module), continuing without it"),this.decisionTransformer=null}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null),this.decisionTransformer&&(await this.decisionTransformer.reset(),this.decisionTransformer=null),this.qesona&&(await this.qesona.close(),this.qesona=null),this.testEmbeddings.clear()}getActiveWorkflows(){return super.getActiveWorkflows()}async generateTests(u){let a=A();try{if(this.startWorkflow(a,"generate"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Q.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Test generation paused: topology is in critical state"));let t=[];if(this.hookRegistry)try{let l=u.sourceFiles?.[0]||"",c=await this.hookRegistry.emit(i4.PreTestGeneration,{targetFile:l,testType:u.testType,framework:u.framework,language:l.split(".").pop()||"typescript"});for(let E of c)E.success&&E.data?.patterns&&t.push(...E.data.patterns),E.guidance&&Q.info(`Hook guidance: ${E.guidance.join("; ")}`)}catch{Q.debug("PreTestGeneration hook failed:")}if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn test generation agents"));let r=await this.spawnTestGeneratorAgent(a,u);if(!r.success)return this.failWorkflow(a,r.error.message),m(r.error);this.addAgentToWorkflow(a,r.value);let i=[...u.patterns||[],...t];if(this.config.enableQESONA&&this.qesona){let l=await this.adaptTestGenerationPatterns(u);l.length>0&&(i=l,Q.info(`Adapted ${l.length} patterns using QESONA`))}let n=i;if(this.config.enablePatternLearning&&n.length===0){let l=await this.patternMatcher.findMatchingPatterns({testType:u.testType,framework:u.framework});l.success&&l.value.length>0&&(n=l.value.map(c=>c.pattern.id))}let o=await this.testGenerator.generateTests({...u,patterns:n});if(o.success){if(this.completeWorkflow(a),this.config.enableFlashAttention&&this.flashAttention){let l=await this.findSimilarTests(o.value.tests);l.length>0&&Q.info(`Found ${l.length} similar tests using Flash Attention`)}if(this.config.enableDecisionTransformer&&this.decisionTransformer){let l=await this.prioritizeTestCases(o.value.tests,u);Q.info(`Prioritized ${l.length} tests using DecisionTransformer`)}if(this.config.publishEvents){await this.publishTestSuiteCreated(o.value,u);for(let l of o.value.tests)await this.publishTestGenerated(l,u.framework??"vitest")}if(Me()&&this.qesona?.isThreeLoopEnabled()){let l=o.value;this.qesona.instantAdapt([l.tests.length/20,l.coverageEstimate/100,l.patternsUsed.length/10,u.sourceFiles.length/20,(u.coverageTarget??80)/100,l.tests.filter(c=>c.type==="unit").length/20]);try{if(this.qesona.recordOutcome(1),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableQESONA&&this.qesona&&await this.storeTestGenerationPattern(o.value,u),this.config.enablePatternLearning&&await this.learnFromGeneration(o.value)}else this.failWorkflow(a,o.error.message),this.config.publishEvents&&await this.publishGenerationFailed(o.error,"generateTests");return await this.agentCoordinator.stop(r.value),o}catch(t){let r=g(t);return this.failWorkflow(a,r.message),this.config.publishEvents&&await this.publishGenerationFailed(r,"generateTests"),{success:!1,error:r}}}async generateTDDTests(u){let a=A();try{this.startWorkflow(a,"tdd");let t=await this.spawnTDDAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=await this.testGenerator.generateTDDTests(u);return r.success?(this.completeWorkflow(a),this.updateWorkflowProgress(a,this.getTDDProgress(u.phase))):this.failWorkflow(a,r.error.message),await this.agentCoordinator.stop(t.value),r}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async generatePropertyTests(u){let a=A();try{this.startWorkflow(a,"property");let t=await this.spawnPropertyTestAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=await this.testGenerator.generatePropertyTests(u);return r.success?this.completeWorkflow(a):this.failWorkflow(a,r.error.message),await this.agentCoordinator.stop(t.value),r}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async generateTestData(u){let a=A();try{this.startWorkflow(a,"data");let t=await this.testGenerator.generateTestData(u);return t.success?this.completeWorkflow(a):this.failWorkflow(a,t.error.message),t}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async learnPatterns(u){let a=A();try{this.startWorkflow(a,"learn");let t=await this.patternMatcher.learnPatterns(u);return t.success?(this.completeWorkflow(a),this.config.publishEvents&&await this.publishPatternLearned(t.value)):this.failWorkflow(a,t.error.message),t}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async spawnTestGeneratorAgent(u,a){let t={name:`test-generator-${u.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["test-generation",a.testType,a.framework??"vitest"],config:{workflowId:u,sourceFiles:a.sourceFiles,coverageTarget:a.coverageTarget}};return this.agentCoordinator.spawn(t)}async spawnTDDAgent(u,a){let t={name:`tdd-agent-${u.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["tdd",a.framework,a.phase],config:{workflowId:u,feature:a.feature,behavior:a.behavior}};return this.agentCoordinator.spawn(t)}async spawnPropertyTestAgent(u,a){let t={name:`property-test-agent-${u.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["property-testing","fast-check"],config:{workflowId:u,function:a.function,properties:a.properties}};return this.agentCoordinator.spawn(t)}async publishTestGenerated(u,a){let t={testId:u.id,testFile:u.testFile,framework:a,sourceFile:u.sourceFile,testType:u.type},r=L(U0.TestGenerated,"test-generation",t);await this.eventBus.publish(r)}async publishTestSuiteCreated(u,a){let t={suiteId:A(),testCount:u.tests.length,sourceFiles:a.sourceFiles,coverageEstimate:u.coverageEstimate},r=L(U0.TestSuiteCreated,"test-generation",t);await this.eventBus.publish(r)}async publishPatternLearned(u){let a=L(U0.PatternLearned,"test-generation",{patternCount:u.patterns.length,confidence:u.confidence,patternIds:u.patterns.map(t=>t.id)});await this.eventBus.publish(a)}async publishGenerationFailed(u,a){let t=L(U0.GenerationFailed,"test-generation",{error:u.message,context:a,timestamp:new Date().toISOString()});await this.eventBus.publish(t)}getTDDProgress(u){switch(u){case"red":return 33;case"green":return 66;case"refactor":return 100;default:return 0}}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGapDetected.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.subscribeToDreamEvents()}subscribeToDreamEvents(){this.eventBus.subscribe(Yu.DreamCycleCompleted,this.handleDreamCycleCompleted.bind(this))}async handleDreamCycleCompleted(u){let{insights:a,cycleId:t}=u.payload;if(!a||a.length===0)return;let r=a.filter(i=>{let n=i.suggestedAction?.toLowerCase().includes(this.domainName)||i.suggestedAction?.toLowerCase().includes("test")||i.suggestedAction?.toLowerCase().includes("coverage"),o=i.sourceConcepts.some(c=>c.toLowerCase().includes("test")||c.toLowerCase().includes(this.domainName)||c.toLowerCase().includes("coverage")||c.toLowerCase().includes("edge-case")),l=i.type==="optimization"||i.type==="gap_detection"||i.type==="novel_association";return n||o||l&&i.actionable});if(r.length!==0){Q.info(`[${this.domainName}] Received ${r.length} relevant dream insights from cycle ${t}`);for(let i of r)i.confidenceScore>.7&&i.actionable&&await this.applyDreamInsight(i,t),this.recentDreamInsights.push({...i,receivedAt:new Date});this.recentDreamInsights.length>50&&(this.recentDreamInsights=this.recentDreamInsights.slice(-50))}}async applyDreamInsight(u,a){if(Q.info(`[${this.domainName}] Applying dream insight: ${u.description.slice(0,100)}...`),this.qesona)try{let t={id:`dream-insight-${u.id}`,features:this.encodeInsightAsFeatures(u),metadata:{insightType:u.type,cycleId:a,sourceConcepts:u.sourceConcepts}},r={type:"dream-insight",value:u.suggestedAction||u.description},i=this.qesona.createPattern(t,r,{reward:u.confidenceScore,success:!0,quality:u.noveltyScore},"dream-derived",this.domainName,{insightId:u.id,cycleId:a,description:u.description,suggestedAction:u.suggestedAction});Q.info(`[${this.domainName}] Created SONA pattern ${i.id} from dream insight`)}catch(t){Q.error(`[${this.domainName}] Failed to store dream insight pattern`,t instanceof Error?t:void 0)}await this.memory.set(`${this.domainName}:dream-insight:${u.id}`,{insight:u,cycleId:a,appliedAt:new Date().toISOString()},{namespace:this.domainName,ttl:86400*7})}getRecentDreamInsights(u){let a=Date.now()-864e5;return this.recentDreamInsights.filter(t=>{let r=t.receivedAt.getTime()>a,i=!u||t.type===u;return r&&i})}async enhanceWithDreamInsights(u){let a=[],r=this.getRecentDreamInsights().filter(i=>(i.type==="novel_association"||i.type==="gap_detection")&&i.actionable&&i.confidenceScore>.6);for(let i of r)i.suggestedAction&&(u.sourceFiles.some(o=>i.sourceConcepts.some(l=>o.toLowerCase().includes(l.toLowerCase())))||i.suggestedAction.toLowerCase().includes(u.testType))&&a.push(i.suggestedAction);return a.slice(0,5)}encodeInsightAsFeatures(u){let a=[],t={pattern_merge:.2,novel_association:.4,optimization:.6,gap_detection:.8};for(a.push(t[u.type]||.5),a.push(u.confidenceScore),a.push(u.noveltyScore),a.push(u.actionable?1:0),a.push(Math.min(1,u.sourceConcepts.length/10));a.length<384;)a.push(0);return a.slice(0,384)}async handleCoverageGapDetected(u){let a=u.payload,t=await this.testGenerator.generateForCoverageGap(a.file,a.uncoveredLines,"jest");if(t.success&&t.value.length>0)for(let r of t.value)await this.publishTestGenerated(r,"jest")}async handleTestRunCompleted(u){}async learnFromGeneration(u){for(let a of u.patternsUsed){let t=await this.patternMatcher.getPattern(a)}}async adaptTestGenerationPatterns(u){if(!this.qesona)return[];try{let a={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(u),metadata:{testType:u.testType,framework:u.framework,sourceFileCount:u.sourceFiles.length}},t=await this.qesona.adaptPattern(a,this.config.sonaPatternType,"test-generation");return t.success&&t.pattern?(Q.info(`QESONA adapted pattern with ${t.similarity.toFixed(3)} similarity in ${t.adaptationTimeMs.toFixed(2)}ms`),[t.pattern.id]):[]}catch(a){return Q.error("QESONA pattern adaptation failed:",a instanceof Error?a:void 0),[]}}async storeTestGenerationPattern(u,a){if(this.qesona)try{let t={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(a),metadata:{testCount:u.tests.length,coverageEstimate:u.coverageEstimate,success:!0}},r={type:"generate-tests",value:{testType:a.testType,framework:a.framework,patternsUsed:u.patternsUsed}},i=this.qesona.createPattern(t,r,{reward:u.coverageEstimate/100,success:!0,quality:u.coverageEstimate/100},this.config.sonaPatternType,"test-generation",{testCount:u.tests.length,framework:a.framework,testType:a.testType});Q.info(`Stored test generation pattern ${i.id} in QESONA`)}catch(t){Q.error("Failed to store pattern in QESONA:",t instanceof Error?t:void 0)}}async findSimilarTests(u){if(!this.flashAttention)return[];let a=[];try{for(let r of u){let i=this.generateTestEmbedding(r);this.testEmbeddings.set(r.id,i)}let t=await this.loadExistingTestEmbeddings();if(t.length===0)return[];for(let r of u){let i=this.testEmbeddings.get(r.id);if(!i)continue;let o=(await this.flashAttention.computeTestSimilarity(i,t.map(l=>l.embedding),5)).filter(l=>l.similarity>.7).map(l=>({testId:t[l.index].testId,similarity:l.similarity}));o.length>0&&a.push({test:r,similarTests:o})}return a}catch(t){return Q.error("Flash Attention similarity detection failed:",t instanceof Error?t:void 0),[]}}async prioritizeTestCases(u,a){if(!this.decisionTransformer)return u;try{let t={id:`prioritize-${Date.now()}`,features:[u.length/100,(a.coverageTarget||80)/100,a.testType==="unit"?.2:a.testType==="integration"?.5:.8,a.framework==="jest"?.3:a.framework==="vitest"?.4:.5],metadata:{testCount:u.length,framework:a.framework,testType:a.testType}},r=await this.decisionTransformer.predict(t);return Q.info(`DecisionTransformer prediction: ${r.reasoning}`),r.confidence>.7?u.sort((i,n)=>n.assertions-i.assertions):u}catch(t){return Q.error("DecisionTransformer prioritization failed:",t instanceof Error?t:void 0),u}}getQESONAStats(){return this.qesona?this.qesona.getStats():null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():null}async checkRequirementCoherence(u){return this.coherenceGate?this.coherenceGate.checkRequirementCoherence(u):{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:0,usedFallback:!0}}isCoherenceGateAvailable(){return this.coherenceGate?.isAvailable()??!1}async verifyAndEnrichSpec(u){if(!this.coherenceGate||!this.config.enableCoherenceGate)return u;let a=await this.coherenceGate.validateAndEnrich(u);if(a.success)return a.value;throw a.error}async verifyTestPatternSelection(u,a){let t=O({id:A(),type:"test-pattern-selection",confidence:a,description:`Verify test pattern: ${u.name} (${u.type})`,payload:u,detectedBy:"test-generation-coordinator",severity:a>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(Q.info(`Test pattern '${u.name}' verified by consensus`),!0):(Q.warn(`Test pattern '${u.name}' NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async verifyMockStrategy(u,a){let t=O({id:A(),type:"mock-strategy",confidence:a,description:`Verify mock strategy for ${u.target}: ${u.mockType}`,payload:u,detectedBy:"test-generation-coordinator",severity:a>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(Q.info(`Mock strategy for '${u.target}' verified by consensus`),!0):(Q.warn(`Mock strategy for '${u.target}' NOT verified`),!1)}return!0}async verifyEdgeCaseGeneration(u,a){let t=O({id:A(),type:"edge-case-generation",confidence:a,description:`Verify edge case: ${u.description}`,payload:u,detectedBy:"test-generation-coordinator",severity:"high"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(Q.info(`Edge case '${u.description.slice(0,50)}...' verified by consensus`),!0):(Q.warn(`Edge case NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}encodeRequestAsFeatures(u){let a=[];for(a.push(u.testType==="unit"?.2:u.testType==="integration"?.5:.8),a.push(u.framework==="jest"?.25:u.framework==="vitest"?.5:u.framework==="mocha"?.75:.9),a.push(Math.min(1,u.sourceFiles.length/50)),a.push((u.coverageTarget||80)/100);a.length<384;)a.push(0);return a.slice(0,384)}generateTestEmbedding(u){let a=[],t=this.simpleHash(u.name);for(let r=0;r<64;r++)a.push((t>>r%32&1)*2-1);for(a.push(u.type==="unit"?.2:u.type==="integration"?.5:.8),a.push(Math.min(1,u.assertions/20));a.length<384;)a.push(0);return new Float32Array(a.slice(0,384))}async loadExistingTestEmbeddings(){try{let u=await this.memory.search("test-embedding:*",1e3),a=[];for(let t of u){let r=await this.memory.get(t);r&&a.push({testId:r.testId,embedding:new Float32Array(r.embedding)})}return a}catch{return[]}}simpleHash(u){let a=0;for(let t=0;t<u.length;t++){let r=u.charCodeAt(t);a=(a<<5)-a+r,a=a|0}return Math.abs(a)}async loadWorkflowState(){let u=await this.memory.get("test-generation:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("test-generation:coordinator:workflows",u,{namespace:"test-generation",persist:!0})}};S();var er=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}coordinator=null;testGenerator=null;patternMatcher=null;pluginConfig;get name(){return"test-generation"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{generateTests:this.generateTests.bind(this),generateTDDTests:this.generateTDDTests.bind(this),generatePropertyTests:this.generatePropertyTests.bind(this),generateTestData:this.generateTestData.bind(this),learnPatterns:this.learnPatterns.bind(this),getCoordinator:()=>this.coordinator,getTestGenerator:()=>this.testGenerator,getPatternMatcher:()=>this.patternMatcher}}getTaskHandlers(){return new Map([["generate-tests",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.sourceFiles,t=u.testType,r=u.framework;if(!a||a.length===0)return m(new Error("Invalid generate-tests payload: missing sourceFiles"));let i={sourceFiles:a,testType:t??"unit",framework:r??"vitest",coverageTarget:u.coverageTarget,patterns:u.patterns};return this.coordinator.generateTests(i)}],["generate-tdd-tests",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.feature,t=u.behavior,r=u.framework,i=u.phase;return!a||!t?m(new Error("Invalid generate-tdd-tests payload: missing feature or behavior")):this.coordinator.generateTDDTests({feature:a,behavior:t,framework:r??"vitest",phase:i??"red"})}],["generate-property-tests",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.function,t=u.properties;return!a||!t||t.length===0?m(new Error("Invalid generate-property-tests payload: missing function or properties")):this.coordinator.generatePropertyTests({function:a,properties:t,constraints:u.constraints})}],["generate-test-data",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.schema,t=u.count;return a?this.coordinator.generateTestData({schema:a,count:t??10,locale:u.locale,preserveRelationships:u.preserveRelationships}):m(new Error("Invalid generate-test-data payload: missing schema"))}]])}async onInitialize(){this.testGenerator=Ie(this.memory,this.pluginConfig.testGenerator),this.patternMatcher=new Ke(this.memory,this.pluginConfig.patternMatcher),this.coordinator=new Sa(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.testGenerator=null,this.patternMatcher=null}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("learning-optimization.PatternConsolidated",this.handlePatternConsolidation.bind(this))}async onEvent(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(u);break;case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(u);break;default:break}}async generateTests(u){this.ensureInitialized();try{let a=await this.coordinator.generateTests(u);return a.success?this.trackSuccessfulGeneration(a.value):this.trackFailedGeneration(a.error),a}catch(a){return this.handleError(a)}}async generateTDDTests(u){this.ensureInitialized();try{return await this.coordinator.generateTDDTests(u)}catch(a){return this.handleError(a)}}async generatePropertyTests(u){this.ensureInitialized();try{return await this.coordinator.generatePropertyTests(u)}catch(a){return this.handleError(a)}}async generateTestData(u){this.ensureInitialized();try{return await this.coordinator.generateTestData(u)}catch(a){return this.handleError(a)}}async learnPatterns(u){this.ensureInitialized();try{return await this.coordinator.learnPatterns(u)}catch(a){return this.handleError(a)}}async handleCoverageGap(u){let a=u.payload;a.riskScore>=.7&&await this.memory.set(`test-generation:pending-gaps:${a.gapId}`,a,{namespace:"test-generation",ttl:86400})}async handleImpactAnalysis(u){let a=u.payload;await this.memory.set(`test-generation:impact:${a.analysisId}`,a,{namespace:"test-generation",ttl:3600})}async handlePatternConsolidation(u){u.payload.domains.includes("test-generation")}ensureInitialized(){if(!this._initialized)throw new Error("TestGenerationPlugin is not initialized");if(!this.coordinator||!this.testGenerator||!this.patternMatcher)throw new Error("TestGenerationPlugin services are not available")}handleError(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulGeneration(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedGeneration(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}};function Cs(s,e,u,a){return new er(s,e,u,a)}N();N();import{spawn as G6u}from"node:child_process";import{existsSync as Tc,readFileSync as V6u}from"node:fs";import{join as Mc}from"node:path";var ae={DEFAULT_TEST_TIMEOUT_MS:6e4,DEFAULT_FILE_TIMEOUT_MS:3e4,DEFAULT_VIEWPORT_WIDTH:1280,DEFAULT_VIEWPORT_HEIGHT:720,MAX_RESULTS:1e3,RESULT_RETENTION_MS:864e5,MAX_TESTS_TRACKED:1e4,MAX_EXECUTION_HISTORY:100,ANALYSIS_CACHE_TTL_MS:36e5,MAX_RETRY_HISTORY:50,MAX_ACTIONS_PER_RECORDING:1e3,MAX_RECORDING_DURATION_MS:18e5,MAX_WORKERS:32},ar={DEFAULT_STEP_TIMEOUT_MS:3e4,RETRY_DELAY_MS:1e3,DEFAULT_MAX_RETRIES:3,POLLING_INTERVAL_MS:100,ELEMENT_DETECTION_TIMEOUT_MS:1e3,POST_INTERACTION_DELAY_MS:500,DEFAULT_WAIT_MS:1e3,ACCESSIBILITY_TIMEOUT_MS:6e4,SCREENSHOT_QUALITY:80,TYPE_DEBOUNCE_MS:300},y0={BASE_DELAY_MS:1e3,MAX_DELAY_MS:3e4,DEFAULT_FLAKY_RATE:.3,DEFAULT_FLAKY_PASS_RATE:.7,RETRY_PASS_RATE_VARIATION:.1,SIGKILL_GRACE_PERIOD_MS:1e3},tr={DEFAULT_TIMEOUT_MS:6e4,QUICK_TIMEOUT_MS:1e4,MAX_CACHED_VALIDATIONS:1e3,CACHE_TTL_MS:36e5,CONTRACT_TTL_SECONDS:86400,MIGRATION_TTL_SECONDS:86400*90,MAX_RECURSION_DEPTH:10,MAX_SCHEMA_DEPTH:20,MAX_MIGRATION_STEPS:50,DEFAULT_SEARCH_LIMIT:100,HIGH_IMPACT_THRESHOLD:5,BREAKING_CHANGE_THRESHOLD:10,DEFAULT_PROVIDER_LOAD:50,HIGH_PROVIDER_LOAD_THRESHOLD:80},sSu={PASSING_RATE_WARNING_THRESHOLD:95,PASSING_RATE_CRITICAL_THRESHOLD:80,MIN_COVERAGE_FOR_DEPLOY:80,PERFECT_PASSING_RATE:100,METRIC_TTL_SECONDS:86400*7,STANDARD_METRIC_TTL_SECONDS:86400,MAX_HIGH_VULN_IMPACT:.3,MEDIUM_VULN_IMPACT:.1,MAX_DUPLICATION_PERCENT:20};var lSu={CHUNK_SIZE_BYTES:1024*1024,SPIKE_INTERVAL_MS:3e4,SPIKE_DURATION_MS:5e3};var cSu={MAX_DURATION_MS:6e4,MAX_AGE_MS:10080*60*1e3,DAYS_IN_YEAR:365,MAX_DEPENDENCY_COUNT:10},rr={MAX_TOKENS:2048,ERROR_TRUNCATION_LENGTH:200,OUTPUT_TRUNCATION_LENGTH:500,DETAILED_OUTPUT_TRUNCATION_LENGTH:1e3,MODEL_TIERS:{1:"claude-3-haiku-20240307",2:"claude-sonnet-4-20250514",3:"claude-sonnet-4-20250514",4:"claude-opus-4-20250514"}};S();J();cu();var O6u={simulateForTesting:!1,simulatedTestsPerFile:5,simulatedFailureRate:.2,simulatedSkipRate:.1,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:rr.MAX_TOKENS},_6u=B.create("test-execution/test-executor"),ir=class{runResults=new Map;runStats=new Map;config;memory;llmRouter;MAX_RESULTS=ae.MAX_RESULTS;RESULT_RETENTION_MS=ae.RESULT_RETENTION_MS;constructor(e,u={}){this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...O6u,...u}}async execute(e){let u=A(),a=new Date;try{let t=this.validateRequest(e);if(t.success===!1)return m(t.error);let r=await this.runTests(e),i=new Date,n=i.getTime()-a.getTime(),o={runId:u,status:r.failed>0?"failed":"passed",total:r.total,passed:r.passed,failed:r.failed,skipped:r.skipped,duration:n,failedTests:r.failedTests,coverage:r.coverage,fileCoverages:r.fileCoverages};this.runResults.set(u,o),await this.storeResults(u,o);let l={runId:u,startTime:a,endTime:i,duration:n,testsPerSecond:r.total/(n/1e3),workers:1,memoryUsage:process.memoryUsage?.().heapUsed??0};return this.runStats.set(u,l),p(o)}catch(t){return m(g(t))}}async executeParallel(e){let u=A(),a=new Date;try{let t=this.validateParallelRequest(e);if(t.success===!1)return m(t.error);let{workers:r,sharding:i="file",isolation:n="process"}=e,o=this.shardTests(e.testFiles,r,i),l=await Promise.all(o.map((C,y)=>this.executeWorker(C,y,n,e))),c=this.aggregateResults(l),E=new Date,d=E.getTime()-a.getTime(),D={runId:u,status:c.failed>0?"failed":"passed",total:c.total,passed:c.passed,failed:c.failed,skipped:c.skipped,duration:d,failedTests:c.failedTests,coverage:c.coverage,fileCoverages:c.fileCoverages};this.runResults.set(u,D),await this.storeResults(u,D);let h={runId:u,startTime:a,endTime:E,duration:d,testsPerSecond:c.total/(d/1e3),workers:r,memoryUsage:process.memoryUsage?.().heapUsed??0};return this.runStats.set(u,h),p(D)}catch(t){return m(g(t))}}async getResults(e){let u=this.runResults.get(e);if(u)return p(u);try{let a=await this.memory.get(`test-run:${e}`);if(a)return this.runResults.set(e,a),p(a)}catch{}return m(new Error(`Test run not found: ${e}`))}async getStats(e){let u=this.runStats.get(e);if(u)return p(u);try{let a=await this.memory.get(`test-stats:${e}`);if(a)return this.runStats.set(e,a),p(a)}catch{}return m(new Error(`Test stats not found: ${e}`))}cleanupOldResults(){let e=Date.now(),u=0;for(let[a,t]of this.runResults){let r=t.duration?e-t.duration:e;e-r>this.RESULT_RETENTION_MS&&(this.runResults.delete(a),this.runStats.delete(a),u++)}if(this.runResults.size>this.MAX_RESULTS){let a=this.runResults.size-this.MAX_RESULTS,t=Array.from(this.runResults.entries());for(let r=0;r<a&&r<t.length;r++)this.runResults.delete(t[r][0]),this.runStats.delete(t[r][0]),u++}return u}destroy(){this.runResults.clear(),this.runStats.clear()}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(e){let u={1:"claude-3-haiku-20240307",2:"claude-sonnet-4-20250514",3:"claude-sonnet-4-20250514",4:"claude-opus-4-20250514"};return u[e]||u[2]}async analyzeFailuresWithLLM(e){if(!this.isLLMAnalysisAvailable()||e.length===0)return null;try{let u=e.slice(0,5).map(t=>`- ${t.testName}: ${t.error?.substring(0,200)||"Unknown error"}`).join(`
2277
+ `))}async getQValue(e,u,a,t){this.ensureInitialized();let r=this.prepared.get("getQValue");if(!r)throw new Error("Statement not prepared");let i=t??this.config.defaultAlgorithm;return r.get(e,u,a,i)?.q_value??0}async setQValue(e,u,a,t,r,i){this.ensureInitialized();let n=this.prepared.get("upsertQValue");if(!n)throw new Error("Statement not prepared");let o=A(),l=i?.algorithm??this.config.defaultAlgorithm;n.run(o,l,e,u,a,t,r??null,i?.domain??null)}async incrementVisits(e,u,a,t){this.ensureInitialized();let r=this.prepared.get("incrementVisits");if(!r)throw new Error("Statement not prepared");let i=t??this.config.defaultAlgorithm;r.run(e,u,a,i)}async getTopActions(e,u,a=10,t){this.ensureInitialized();let r=this.prepared.get("getTopActions");if(!r)throw new Error("Statement not prepared");let i=t??this.config.defaultAlgorithm;return r.all(e,u,i,a).map(o=>this.rowToEntry(o))}async exportForAgent(e,u){this.ensureInitialized();let a=this.prepared.get("getAllForAgent");if(!a)throw new Error("Statement not prepared");let t=u??this.config.defaultAlgorithm,r=a.all(e,t),i=new Map;for(let n of r){let o=n.state_key,l=n.action_key,c=n.q_value;i.has(o)||i.set(o,new Map),i.get(o).set(l,c)}return i}async importFromMap(e,u,a){if(this.ensureInitialized(),!this.db)throw new Error("Database not initialized");let t=this.prepared.get("upsertQValue");if(!t)throw new Error("Statement not prepared");let r=a?.algorithm??this.config.defaultAlgorithm;this.db.transaction(()=>{for(let[n,o]of u)for(let[l,c]of o){let E=A();t.run(E,r,e,n,l,c,null,a?.domain??null)}})()}async pruneOldEntries(e){this.ensureInitialized();let u=this.prepared.get("pruneOld");if(!u)throw new Error("Statement not prepared");return u.run(e).changes}async getStats(){this.ensureInitialized();let e=this.prepared.get("getStats"),u=this.prepared.get("countByAlgorithm"),a=this.prepared.get("countByDomain");if(!e||!u||!a)throw new Error("Statements not prepared");let t=e.get(),r=u.all(),i=a.all(),n={};for(let l of r)n[l.algorithm]=l.count;let o={};for(let l of i)l.domain&&(o[l.domain]=l.count);return{totalEntries:t.total_entries,uniqueAgents:t.unique_agents,uniqueStates:t.unique_states,byAlgorithm:n,byDomain:o,averageVisits:t.avg_visits??0,averageQValue:t.avg_q_value??0,oldestEntry:t.oldest_entry?new Date(t.oldest_entry):null,newestEntry:t.newest_entry?new Date(t.newest_entry):null}}async close(){this.prepared.clear(),this.db=null,this.persistence=null,this.initialized=!1}async getEntry(e,u,a,t){this.ensureInitialized();let r=this.prepared.get("getEntry");if(!r)throw new Error("Statement not prepared");let i=t??this.config.defaultAlgorithm,n=r.get(e,u,a,i);return n?this.rowToEntry(n):null}async deleteEntry(e,u,a,t){this.ensureInitialized();let r=this.prepared.get("deleteEntry");if(!r)throw new Error("Statement not prepared");let i=t??this.config.defaultAlgorithm;return r.run(e,u,a,i).changes>0}isInitialized(){return this.initialized}getDbPath(){return this.persistence?.getDbPath()??""}ensureInitialized(){if(!this.initialized)throw new Error("QValueStore not initialized. Call initialize() first.")}rowToEntry(e){return{id:e.id,algorithm:e.algorithm,agentId:e.agent_id,stateKey:e.state_key,actionKey:e.action_key,qValue:e.q_value,visits:e.visits,lastReward:e.last_reward,domain:e.domain,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}};J();N();var kc=B.create("rl-base-algorithm"),Sc={learningRate:.001,discountFactor:.99,episodes:1e3,maxSteps:1e3,batchSize:32,replayBufferSize:1e4,targetUpdateFrequency:100,explorationRate:.3,explorationDecay:.995,minExplorationRate:.01},I6u={enabled:!1,autoSaveInterval:10},Eu=class{constructor(e,u,a={},t=[],r={}){this.type=e;this.category=u;this.config={...Sc,...a},this.rewardSignals=t,this.persistenceConfig={...I6u,...r},this.stats=this.createInitialStats()}config;stats;replayBuffer=[];episodeCount=0;totalReward=0;rewardHistory=[];initialized=!1;rewardSignals=[];persistenceConfig;qValueStore=null;lastSaveEpisode=0;enablePersistence(e,u){this.persistenceConfig.enabled=!0,this.persistenceConfig.agentId=e,u&&(this.persistenceConfig.dbPath=u)}isPersistenceEnabled(){return this.persistenceConfig.enabled&&!!this.persistenceConfig.agentId}getPersistenceAgentId(){return this.persistenceConfig.agentId}async train(e){if(this.addToReplayBuffer(e),this.replayBuffer.length>=this.config.batchSize){let u=this.sampleBatch();return this.trainBatch(u)}return this.getStats()}async trainBatch(e){this.initialized||await this.initialize();let u=Date.now();try{this.episodeCount++;let a=e.reduce((r,i)=>r+i.reward,0);this.totalReward+=a,this.rewardHistory.push(a),this.rewardHistory.length>1e3&&this.rewardHistory.shift();let t=await this.trainCore(e);return this.stats={...t,episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((r,i)=>r+i,0)/this.rewardHistory.length,trainingTimeMs:Date.now()-u,timestamp:new Date},this.config.explorationRate=Math.max(this.config.minExplorationRate,this.config.explorationRate*this.config.explorationDecay),this.stats.explorationRate=this.config.explorationRate,await this.autoSaveToPersistence(),this.stats}catch(a){throw new Yt(`Training failed for ${this.type}: ${a.message}`,this.type,a)}}async autoSaveToPersistence(){if(!this.isPersistenceEnabled()||this.persistenceConfig.autoSaveInterval<=0)return;if(this.episodeCount-this.lastSaveEpisode>=this.persistenceConfig.autoSaveInterval)try{await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.lastSaveEpisode=this.episodeCount}catch(u){console.warn(`[${this.type}] Auto-save failed:`,u.message)}}async update(e){let u={...this.config};if(this.config={...this.config,...e},this.config.learningRate<=0||this.config.learningRate>1)throw new ge(`Invalid learning rate: ${this.config.learningRate}`,this.type);if(this.config.discountFactor<0||this.config.discountFactor>1)throw new ge(`Invalid discount factor: ${this.config.discountFactor}`,this.type);if(this.config.explorationRate<0||this.config.explorationRate>1)throw new ge(`Invalid exploration rate: ${this.config.explorationRate}`,this.type);await this.handleConfigUpdate(u,this.config)}getStats(){return{...this.stats}}async reset(){this.isPersistenceEnabled()&&this.episodeCount>0&&await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.replayBuffer=[],this.episodeCount=0,this.totalReward=0,this.rewardHistory=[],this.lastSaveEpisode=0,this.config.explorationRate=Sc.explorationRate,this.stats=this.createInitialStats(),await this.resetAlgorithm()}async close(){this.isPersistenceEnabled()&&this.episodeCount>this.lastSaveEpisode&&await this.saveToStore(this.persistenceConfig.agentId,this.qValueStore??void 0),this.qValueStore&&(await this.qValueStore.close(),this.qValueStore=null)}async exportModel(){return{type:this.type,category:this.category,version:this.getVersion(),config:this.config,stats:this.stats,replayBufferSize:this.replayBuffer.length,exportedAt:new Date().toISOString(),customData:await this.exportCustomData()}}async importModel(e){if(e.type!==this.type)throw new ge(`Model type mismatch: expected ${this.type}, got ${e.type}`,this.type);if(e.category!==this.category)throw new ge(`Algorithm category mismatch: expected ${this.category}, got ${e.category}`,this.type);e.config&&(this.config={...this.config,...e.config}),e.stats&&(this.stats={...this.stats,...e.stats}),e.customData&&await this.importCustomData(e.customData),this.initialized=!0}getInfo(){let e=this.getAlgorithmInfo();return{...e,stats:this.stats,hyperparameters:{...e.hyperparameters,learningRate:this.config.learningRate,discountFactor:this.config.discountFactor,explorationRate:this.config.explorationRate,batchSize:this.config.batchSize}}}async saveToStore(e,u){let a=u??new Ce;await a.initialize();let t=await this.exportModel();await a.setQValue(e,"__model_state__","__weights__",0,void 0,{algorithm:this.type,domain:JSON.stringify(t)})}async loadFromStore(e,u){let a=u??new Ce;await a.initialize();try{let t=await a.getQValue(e,"__model_state__","__weights__",this.type),r=await a.getEntry(e,"__model_state__","__weights__",this.type);if(!r?.domain)return!1;let i=T(r.domain);return await this.importModel(i),!0}catch(t){return kc.debug("Model load from store failed",{algorithm:this.type,error:t instanceof Error?t.message:String(t)}),!1}}async storeQValue(e,u,a,t,r,i){let n=i??new Ce;await n.initialize(),await n.setQValue(e,u,a,t,r,{algorithm:this.type})}async retrieveQValue(e,u,a,t){let r=t??new Ce;await r.initialize();try{return await r.getQValue(e,u,a,this.type)}catch(i){return kc.debug("Q-value retrieval failed",{agentId:e,stateKey:u,actionKey:a,error:i instanceof Error?i.message:String(i)}),null}}calculateReward(e){let u={},a=0,t=[];for(let r of this.rewardSignals){let i=r.calculate(e);u[r.name]=i,a+=i,i!==0&&t.push(`${r.name}: ${i.toFixed(3)} (${r.description})`)}return{totalReward:Math.max(-1,Math.min(1,a)),components:u,reasoning:t.join("; ")||"No reward signals triggered",timestamp:new Date}}addToReplayBuffer(e){this.replayBuffer.push(e),this.replayBuffer.length>this.config.replayBufferSize&&this.replayBuffer.shift()}sampleBatch(e){let u=e||this.config.batchSize,a=this.replayBuffer;if(a.length===0)return[];if(a.length<=u)return[...a];let t=new Set;for(;t.size<Math.min(u,a.length);)t.add(Du(0,a.length));return Array.from(t).map(r=>a[r])}epsilonGreedy(e,u){return K()<this.config.explorationRate?e():u()}normalizeFeatures(e){if(e.length===0)return[];let u=Math.max(...e.map(Math.abs));return u===0?e:e.map(a=>a/u)}stateToKey(e){let u=e.features.map((a,t)=>`${t}:${Math.round(a*100)/100}`).join(",");return`${e.id}|${u}`}async initialize(){this.isPersistenceEnabled()&&(await this.initializePersistence(),await this.loadFromStore(this.persistenceConfig.agentId)&&console.log(`[${this.type}] Loaded persisted state for agent: ${this.persistenceConfig.agentId}`)),this.initialized=!0}async initializePersistence(){this.qValueStore||(this.qValueStore=new Ce,await this.qValueStore.initialize())}async resetAlgorithm(){}async handleConfigUpdate(e,u){}async exportCustomData(){return{}}async importCustomData(e){}getVersion(){return"1.0.0"}createInitialStats(){return{episode:0,totalReward:0,averageReward:0,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}};ct();var K6u={contextLength:10,embeddingDim:384,numHeads:4,numLayers:3,feedForwardDim:256,maxReturn:100},A0=class extends Eu{trajectories=[];dtConfig;stateEmbeddings=new Map;actionEmbeddings=new Map;constructor(e={}){super("decision-transformer","offline-rl"),this.dtConfig={...K6u,...e}}async predict(e){this.initialized||await this.initialize();let u=this.retrieveContext(e),a=this.calculateReturnToGo(u),t=this.generateAction(e,u,a),r=this.calculateConfidence(u,a);return{action:t,confidence:r,value:a,reasoning:this.generateReasoning(e,t,u,a)}}async trainCore(e){let u=this.groupIntoTrajectories(e);for(let t of u)this.calculateReturns(t);this.trajectories.push(...u),this.trajectories.length>1e3&&(this.trajectories=this.trajectories.slice(-1e3)),this.updateEmbeddings(u);let a=u.reduce((t,r)=>t+r.returns[r.returns.length-1],0)/u.length;return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((t,r)=>t+r,0)/this.rewardHistory.length,loss:Math.abs(a-this.targetReturn()),explorationRate:0,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"1.0.0",description:"Decision Transformer for Test Case Prioritization",capabilities:["Offline RL from historical data","Attention-based sequence modeling","Return-to-go conditioning","Context-aware decisions"],hyperparameters:{contextLength:this.dtConfig.contextLength,embeddingDim:this.dtConfig.embeddingDim,numHeads:this.dtConfig.numHeads,numLayers:this.dtConfig.numLayers},stats:this.stats}}retrieveContext(e){let u=this.trajectories.map(a=>{let t=this.calculateSimilarity(e,a);return{traj:a,similarity:t}});return u.sort((a,t)=>t.similarity-a.similarity),u.slice(0,this.dtConfig.contextLength).map(a=>a.traj)}calculateSimilarity(e,u){for(let a of u.states)if(this.statesMatch(e,a))return 1;if(u.states.length>0){let a=u.states[u.states.length-1];return ce(e.features,a.features)}return 0}statesMatch(e,u){return e.id===u.id||Math.abs(e.features[0]-u.features[0])<.1}calculateReturnToGo(e){if(e.length===0)return 0;let u=e.flatMap(a=>a.returns);return u.reduce((a,t)=>a+t,0)/u.length}calculateReturns(e){let u=[],a=0;for(let t=e.rewards.length-1;t>=0;t--)a=e.rewards[t]+this.config.discountFactor*a,u.unshift(a);e.returns=u}targetReturn(){return this.dtConfig.maxReturn*.8}generateAction(e,u,a){for(let t of u)for(let r=0;r<t.states.length;r++)if(this.statesMatch(e,t.states[r])&&t.returns[r]>a*.8)return{...t.actions[r]};return this.getHeuristicAction(e)}getHeuristicAction(e){return{type:"prioritize",value:e.features[0]>.7?"high":"standard",metadata:{heuristic:!0}}}updateEmbeddings(e){for(let u of e){for(let a of u.states)this.stateEmbeddings.has(a.id)||this.stateEmbeddings.set(a.id,this.hashEmbedding(a.id));for(let a of u.actions){let t=this.actionToKey(a);this.actionEmbeddings.has(t)||this.actionEmbeddings.set(t,this.hashEmbedding(t))}}}hashEmbedding(e){let u=[],a=this.dtConfig.embeddingDim;for(let t=0;t<a;t++){let r=this.simpleHash(e+t);u.push((r%200-100)/100)}return u}simpleHash(e){let u=0;for(let a=0;a<e.length;a++){let t=e.charCodeAt(a);u=(u<<5)-u+t,u=u&u}return Math.abs(u)}actionToKey(e){return`${e.type}:${JSON.stringify(e.value)}`}groupIntoTrajectories(e){let u=[],a=null;for(let t of e)t.done||!a?(a&&u.push(a),a={states:[t.state],actions:[t.action],rewards:[t.reward],returns:[]}):(a.states.push(t.state),a.actions.push(t.action),a.rewards.push(t.reward));return a&&u.push(a),u}calculateConfidence(e,u){if(e.length===0)return .3;let a=Math.min(1,e.length/this.dtConfig.contextLength),t=Math.min(1,u/this.targetReturn());return .3+a*.4+t*.3}generateReasoning(e,u,a,t){if(a.length===0)return"Decision Transformer: No similar historical contexts, using heuristic";let r=a.reduce((i,n)=>i+n.returns[n.returns.length-1]||0,0)/a.length;return`Decision Transformer: Found ${a.length} similar contexts (avg return: ${r.toFixed(2)}), selecting ${u.type} action with return-to-go ${t.toFixed(2)}`}async exportCustomData(){return{trajectories:this.trajectories,stateEmbeddings:Object.fromEntries(this.stateEmbeddings),actionEmbeddings:Object.fromEntries(this.actionEmbeddings),dtConfig:this.dtConfig}}async importCustomData(e){e.trajectories&&(this.trajectories=e.trajectories),e.stateEmbeddings&&(this.stateEmbeddings=new Map(Object.entries(e.stateEmbeddings))),e.actionEmbeddings&&(this.actionEmbeddings=new Map(Object.entries(e.actionEmbeddings))),e.dtConfig&&(this.dtConfig={...this.dtConfig,...e.dtConfig})}async resetAlgorithm(){this.trajectories=[],this.stateEmbeddings.clear(),this.actionEmbeddings.clear()}};Qu();N();var wc={enabled:!0,coherenceThreshold:.1,blockOnHumanLane:!0,enrichOnRetrievalLane:!0,embeddingDimension:384},j6u=B.create("test-generation/coherence-gate"),Xt=class extends Error{constructor(u,a,t){super(u);this.contradictions=a;this.lane=t;this.name="CoherenceError"}},ps=class{constructor(e=384){this.dimension=e}async embed(e){let u=new Array(this.dimension).fill(0),a=e.toLowerCase().trim();for(let r=0;r<a.length;r++){let i=a.charCodeAt(r),n=r%this.dimension;u[n]+=Math.sin(i*(r+1)*.1),u[(n+1)%this.dimension]+=Math.cos(i*(r+1)*.1)}let t=Math.sqrt(u.reduce((r,i)=>r+i*i,0));if(t>0)for(let r=0;r<u.length;r++)u[r]/=t;return u}},ur=class{constructor(e,u,a={}){this.coherenceService=e;this.config={...wc,...a},this.embeddingService=u||new ps(this.config.embeddingDimension)}config;embeddingService;async checkRequirementCoherence(e){let u=Date.now();if(!this.config.enabled||!this.coherenceService)return this.createPassingResult(u,!0);if(e.length===0)return this.createPassingResult(u,!1);if(e.length===1)return this.createPassingResult(u,!1);try{let a=await this.requirementsToNodes(e),t=await this.coherenceService.checkCoherence(a);return this.transformCoherenceResult(t,e,Date.now()-u)}catch(a){return j6u.error("Coherence check failed:",a instanceof Error?a:void 0),{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[{type:"add-context",requirementId:"",description:"Coherence check failed. Manual review recommended.",suggestedResolution:"Review requirements manually before proceeding."}],durationMs:Date.now()-u,usedFallback:!0}}}async enrichSpecification(e,u){if(u.length===0)return e;let a={...e,requirements:[...e.requirements],context:{...e.context}},t=new Map;for(let r of u)switch(r.type){case"clarify":this.addClarificationNote(t,r);break;case"add-context":a.context={...a.context,coherenceRecommendations:[...a.context?.coherenceRecommendations||[],r.description]};break;case"resolve-ambiguity":this.addDisambiguationNote(t,r);break;case"split-requirement":a.context={...a.context,requirementsSuggestedForSplit:[...a.context?.requirementsSuggestedForSplit||[],r.requirementId]};break}return a.requirements=a.requirements.map(r=>{let i=t.get(r.id);return i?{...r,metadata:{...r.metadata,...i.metadata}}:r}),a.context={...a.context,enrichedAt:new Date().toISOString(),enrichmentCount:u.length},a}async validateAndEnrich(e){let u=await this.checkRequirementCoherence(e.requirements);if(this.config.blockOnHumanLane&&u.lane==="human")return m(new Xt("Requirements contain unresolvable contradictions that require human review",u.contradictions,u.lane));if(this.config.enrichOnRetrievalLane&&u.lane==="retrieval"){let a=await this.enrichSpecification(e,u.recommendations);return p(a)}return p(e)}isAvailable(){return this.coherenceService?.isInitialized()??!1}async requirementsToNodes(e){let u=[];for(let a of e){let t=await this.embeddingService.embed(a.description);u.push({id:a.id,embedding:t,weight:this.priorityToWeight(a.priority),metadata:{description:a.description,source:a.source,...a.metadata}})}return u}transformCoherenceResult(e,u,a){let t=new Map(u.map(n=>[n.id,n])),r=e.contradictions.map(n=>({requirementId1:n.nodeIds[0],requirementId2:n.nodeIds[1],severity:this.mapSeverity(n.severity),description:n.description,confidence:n.confidence,suggestedResolution:n.resolution||this.generateResolutionSuggestion(t.get(n.nodeIds[0]),t.get(n.nodeIds[1]),n.severity)})),i=this.generateRecommendations(e,r,u);return{isCoherent:e.isCoherent,energy:e.energy,lane:e.lane,contradictions:r,recommendations:i,durationMs:a,usedFallback:e.usedFallback}}generateRecommendations(e,u,a){let t=[];for(let i of e.recommendations)t.push({type:"add-context",requirementId:"",description:i});for(let i of u)i.severity==="critical"||i.severity==="high"?t.push({type:"resolve-ambiguity",requirementId:i.requirementId1,description:`Potential conflict with requirement ${i.requirementId2}: ${i.description}`,suggestedResolution:i.suggestedResolution}):t.push({type:"clarify",requirementId:i.requirementId1,description:`Minor tension with requirement ${i.requirementId2}: ${i.description}`});let r=a.filter(i=>i.description.length>200||i.description.includes(" and ")&&i.description.includes(" or "));for(let i of r)t.push({type:"split-requirement",requirementId:i.id,description:"Complex requirement may benefit from splitting into smaller, focused requirements"});return t}generateResolutionSuggestion(e,u,a){return!e||!u?"Review and reconcile conflicting requirements.":a==="critical"?`Requirements "${e.id}" and "${u.id}" appear to be mutually exclusive. Consider removing one or explicitly documenting the conditions under which each applies.`:a==="high"?`Requirements "${e.id}" and "${u.id}" may conflict. Add clarification about their relationship and precedence.`:`Minor tension between "${e.id}" and "${u.id}". Consider adding context to clarify their relationship.`}createPassingResult(e,u){return{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:Date.now()-e,usedFallback:u}}priorityToWeight(e){switch(e){case"high":return 1;case"medium":return .7;case"low":return .4;default:return .5}}mapSeverity(e){switch(e){case"critical":return"critical";case"high":return"high";case"medium":return"medium";default:return"low"}}addClarificationNote(e,u){let a=e.get(u.requirementId)||{metadata:{}},t=a.metadata?.clarificationNotes||[];t.push(u.description),e.set(u.requirementId,{...a,metadata:{...a.metadata,clarificationNotes:t,needsClarification:!0}})}addDisambiguationNote(e,u){let a=e.get(u.requirementId)||{metadata:{}},t=a.metadata?.disambiguationNotes||[];t.push(u.description),e.set(u.requirementId,{...a,metadata:{...a.metadata,disambiguationNotes:t,needsDisambiguation:!0,suggestedResolution:u.suggestedResolution}})}};function gs(s,e,u){return new ur(s,e,u)}var H6u={maxConcurrentWorkflows:5,defaultTimeout:6e4,enablePatternLearning:!0,publishEvents:!0,enableQESONA:!0,enableFlashAttention:!0,enableDecisionTransformer:!0,sonaPatternType:"test-generation",flashAttentionWorkload:"test-similarity",enableCoherenceGate:!0,blockOnIncoherentRequirements:!0,enrichOnRetrievalLane:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Q=B.create("test-generation"),Sa=class extends Y{constructor(u,a,t,r={},i,n){let o={...H6u,...r};super(u,"test-generation",o,{verifyFindingTypes:["test-pattern-selection","mock-strategy","edge-case-generation","assertion-strategy"],...o.consensusConfig});this.memory=a;this.agentCoordinator=t;this.coherenceService=i;this.hookRegistry=n;this.testGenerator=Ie(a),this.patternMatcher=new Ke(a),this.config.enableCoherenceGate&&i&&(this.coherenceGate=gs(i,void 0,{enabled:!0,blockOnHumanLane:this.config.blockOnIncoherentRequirements,enrichOnRetrievalLane:this.config.enrichOnRetrievalLane}))}testGenerator;patternMatcher;qesona=null;flashAttention=null;decisionTransformer=null;testEmbeddings=new Map;recentDreamInsights=[];coherenceGate=null;async onInitialize(){if(this.config.enableQESONA)try{this.qesona=await gu({domain:"test-generation",loadOnInit:!0,autoSaveInterval:6e4,patternClusters:50,minConfidence:.5}),Q.info("PersistentSONAEngine initialized for test-generation domain")}catch(u){Q.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),Q.warn("Continuing without SONA pattern persistence"),this.qesona=null}if(this.config.enableFlashAttention)try{this.flashAttention=await Ku(this.config.flashAttentionWorkload,{dim:384,strategy:"flash",blockSize:64}),Q.info("QEFlashAttention initialized for test-similarity")}catch{Q.warn("QEFlashAttention unavailable (optional native module), continuing without it"),this.flashAttention=null}if(this.config.enableDecisionTransformer)try{this.decisionTransformer=new A0({contextLength:10,embeddingDim:384}),Q.info("DecisionTransformer created for test case selection")}catch{Q.warn("DecisionTransformer unavailable (optional native module), continuing without it"),this.decisionTransformer=null}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null),this.decisionTransformer&&(await this.decisionTransformer.reset(),this.decisionTransformer=null),this.qesona&&(await this.qesona.close(),this.qesona=null),this.testEmbeddings.clear()}getActiveWorkflows(){return super.getActiveWorkflows()}async generateTests(u){let a=A();try{if(this.startWorkflow(a,"generate"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Q.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Test generation paused: topology is in critical state"));let t=[];if(this.hookRegistry)try{let l=u.sourceFiles?.[0]||"",c=await this.hookRegistry.emit(i4.PreTestGeneration,{targetFile:l,testType:u.testType,framework:u.framework,language:l.split(".").pop()||"typescript"});for(let E of c)E.success&&E.data?.patterns&&t.push(...E.data.patterns),E.guidance&&Q.info(`Hook guidance: ${E.guidance.join("; ")}`)}catch{Q.debug("PreTestGeneration hook failed:")}if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn test generation agents"));let r=await this.spawnTestGeneratorAgent(a,u);if(!r.success)return this.failWorkflow(a,r.error.message),m(r.error);this.addAgentToWorkflow(a,r.value);let i=[...u.patterns||[],...t];if(this.config.enableQESONA&&this.qesona){let l=await this.adaptTestGenerationPatterns(u);l.length>0&&(i=l,Q.info(`Adapted ${l.length} patterns using QESONA`))}let n=i;if(this.config.enablePatternLearning&&n.length===0){let l=await this.patternMatcher.findMatchingPatterns({testType:u.testType,framework:u.framework});l.success&&l.value.length>0&&(n=l.value.map(c=>c.pattern.id))}let o=await this.testGenerator.generateTests({...u,patterns:n});if(o.success){if(this.completeWorkflow(a),this.config.enableFlashAttention&&this.flashAttention){let l=await this.findSimilarTests(o.value.tests);l.length>0&&Q.info(`Found ${l.length} similar tests using Flash Attention`)}if(this.config.enableDecisionTransformer&&this.decisionTransformer){let l=await this.prioritizeTestCases(o.value.tests,u);Q.info(`Prioritized ${l.length} tests using DecisionTransformer`)}if(this.config.publishEvents){await this.publishTestSuiteCreated(o.value,u);for(let l of o.value.tests)await this.publishTestGenerated(l,u.framework??"vitest")}if(Me()&&this.qesona?.isThreeLoopEnabled()){let l=o.value;this.qesona.instantAdapt([l.tests.length/20,l.coverageEstimate/100,l.patternsUsed.length/10,u.sourceFiles.length/20,(u.coverageTarget??80)/100,l.tests.filter(c=>c.type==="unit").length/20]);try{if(this.qesona.recordOutcome(1),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}this.config.enableQESONA&&this.qesona&&await this.storeTestGenerationPattern(o.value,u),this.config.enablePatternLearning&&await this.learnFromGeneration(o.value)}else this.failWorkflow(a,o.error.message),this.config.publishEvents&&await this.publishGenerationFailed(o.error,"generateTests");return await this.agentCoordinator.stop(r.value),o}catch(t){let r=g(t);return this.failWorkflow(a,r.message),this.config.publishEvents&&await this.publishGenerationFailed(r,"generateTests"),{success:!1,error:r}}}async generateTDDTests(u){let a=A();try{this.startWorkflow(a,"tdd");let t=await this.spawnTDDAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=await this.testGenerator.generateTDDTests(u);return r.success?(this.completeWorkflow(a),this.updateWorkflowProgress(a,this.getTDDProgress(u.phase))):this.failWorkflow(a,r.error.message),await this.agentCoordinator.stop(t.value),r}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async generatePropertyTests(u){let a=A();try{this.startWorkflow(a,"property");let t=await this.spawnPropertyTestAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=await this.testGenerator.generatePropertyTests(u);return r.success?this.completeWorkflow(a):this.failWorkflow(a,r.error.message),await this.agentCoordinator.stop(t.value),r}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async generateTestData(u){let a=A();try{this.startWorkflow(a,"data");let t=await this.testGenerator.generateTestData(u);return t.success?this.completeWorkflow(a):this.failWorkflow(a,t.error.message),t}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async learnPatterns(u){let a=A();try{this.startWorkflow(a,"learn");let t=await this.patternMatcher.learnPatterns(u);return t.success?(this.completeWorkflow(a),this.config.publishEvents&&await this.publishPatternLearned(t.value)):this.failWorkflow(a,t.error.message),t}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async spawnTestGeneratorAgent(u,a){let t={name:`test-generator-${u.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["test-generation",a.testType,a.framework??"vitest"],config:{workflowId:u,sourceFiles:a.sourceFiles,coverageTarget:a.coverageTarget}};return this.agentCoordinator.spawn(t)}async spawnTDDAgent(u,a){let t={name:`tdd-agent-${u.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["tdd",a.framework,a.phase],config:{workflowId:u,feature:a.feature,behavior:a.behavior}};return this.agentCoordinator.spawn(t)}async spawnPropertyTestAgent(u,a){let t={name:`property-test-agent-${u.slice(0,8)}`,domain:"test-generation",type:"generator",capabilities:["property-testing","fast-check"],config:{workflowId:u,function:a.function,properties:a.properties}};return this.agentCoordinator.spawn(t)}async publishTestGenerated(u,a){let t={testId:u.id,testFile:u.testFile,framework:a,sourceFile:u.sourceFile,testType:u.type},r=L(U0.TestGenerated,"test-generation",t);await this.eventBus.publish(r)}async publishTestSuiteCreated(u,a){let t={suiteId:A(),testCount:u.tests.length,sourceFiles:a.sourceFiles,coverageEstimate:u.coverageEstimate},r=L(U0.TestSuiteCreated,"test-generation",t);await this.eventBus.publish(r)}async publishPatternLearned(u){let a=L(U0.PatternLearned,"test-generation",{patternCount:u.patterns.length,confidence:u.confidence,patternIds:u.patterns.map(t=>t.id)});await this.eventBus.publish(a)}async publishGenerationFailed(u,a){let t=L(U0.GenerationFailed,"test-generation",{error:u.message,context:a,timestamp:new Date().toISOString()});await this.eventBus.publish(t)}getTDDProgress(u){switch(u){case"red":return 33;case"green":return 66;case"refactor":return 100;default:return 0}}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGapDetected.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.subscribeToDreamEvents()}subscribeToDreamEvents(){this.eventBus.subscribe(Yu.DreamCycleCompleted,this.handleDreamCycleCompleted.bind(this))}async handleDreamCycleCompleted(u){let{insights:a,cycleId:t}=u.payload;if(!a||a.length===0)return;let r=a.filter(i=>{let n=i.suggestedAction?.toLowerCase().includes(this.domainName)||i.suggestedAction?.toLowerCase().includes("test")||i.suggestedAction?.toLowerCase().includes("coverage"),o=i.sourceConcepts.some(c=>c.toLowerCase().includes("test")||c.toLowerCase().includes(this.domainName)||c.toLowerCase().includes("coverage")||c.toLowerCase().includes("edge-case")),l=i.type==="optimization"||i.type==="gap_detection"||i.type==="novel_association";return n||o||l&&i.actionable});if(r.length!==0){Q.info(`[${this.domainName}] Received ${r.length} relevant dream insights from cycle ${t}`);for(let i of r)i.confidenceScore>.7&&i.actionable&&await this.applyDreamInsight(i,t),this.recentDreamInsights.push({...i,receivedAt:new Date});this.recentDreamInsights.length>50&&(this.recentDreamInsights=this.recentDreamInsights.slice(-50))}}async applyDreamInsight(u,a){if(Q.info(`[${this.domainName}] Applying dream insight: ${u.description.slice(0,100)}...`),this.qesona)try{let t={id:`dream-insight-${u.id}`,features:this.encodeInsightAsFeatures(u),metadata:{insightType:u.type,cycleId:a,sourceConcepts:u.sourceConcepts}},r={type:"dream-insight",value:u.suggestedAction||u.description},i=this.qesona.createPattern(t,r,{reward:u.confidenceScore,success:!0,quality:u.noveltyScore},"dream-derived",this.domainName,{insightId:u.id,cycleId:a,description:u.description,suggestedAction:u.suggestedAction});Q.info(`[${this.domainName}] Created SONA pattern ${i.id} from dream insight`)}catch(t){Q.error(`[${this.domainName}] Failed to store dream insight pattern`,t instanceof Error?t:void 0)}await this.memory.set(`${this.domainName}:dream-insight:${u.id}`,{insight:u,cycleId:a,appliedAt:new Date().toISOString()},{namespace:this.domainName,ttl:86400*7})}getRecentDreamInsights(u){let a=Date.now()-864e5;return this.recentDreamInsights.filter(t=>{let r=t.receivedAt.getTime()>a,i=!u||t.type===u;return r&&i})}async enhanceWithDreamInsights(u){let a=[],r=this.getRecentDreamInsights().filter(i=>(i.type==="novel_association"||i.type==="gap_detection")&&i.actionable&&i.confidenceScore>.6);for(let i of r)i.suggestedAction&&(u.sourceFiles.some(o=>i.sourceConcepts.some(l=>o.toLowerCase().includes(l.toLowerCase())))||i.suggestedAction.toLowerCase().includes(u.testType))&&a.push(i.suggestedAction);return a.slice(0,5)}encodeInsightAsFeatures(u){let a=[],t={pattern_merge:.2,novel_association:.4,optimization:.6,gap_detection:.8};for(a.push(t[u.type]||.5),a.push(u.confidenceScore),a.push(u.noveltyScore),a.push(u.actionable?1:0),a.push(Math.min(1,u.sourceConcepts.length/10));a.length<384;)a.push(0);return a.slice(0,384)}async handleCoverageGapDetected(u){let a=u.payload,t=await this.testGenerator.generateForCoverageGap(a.file,a.uncoveredLines,"jest");if(t.success&&t.value.length>0)for(let r of t.value)await this.publishTestGenerated(r,"jest")}async handleTestRunCompleted(u){}async learnFromGeneration(u){for(let a of u.patternsUsed){let t=await this.patternMatcher.getPattern(a)}}async adaptTestGenerationPatterns(u){if(!this.qesona)return[];try{let a={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(u),metadata:{testType:u.testType,framework:u.framework,sourceFileCount:u.sourceFiles.length}},t=await this.qesona.adaptPattern(a,this.config.sonaPatternType,"test-generation");return t.success&&t.pattern?(Q.info(`QESONA adapted pattern with ${t.similarity.toFixed(3)} similarity in ${t.adaptationTimeMs.toFixed(2)}ms`),[t.pattern.id]):[]}catch(a){return Q.error("QESONA pattern adaptation failed:",a instanceof Error?a:void 0),[]}}async storeTestGenerationPattern(u,a){if(this.qesona)try{let t={id:`test-gen-${Date.now()}`,features:this.encodeRequestAsFeatures(a),metadata:{testCount:u.tests.length,coverageEstimate:u.coverageEstimate,success:!0}},r={type:"generate-tests",value:{testType:a.testType,framework:a.framework,patternsUsed:u.patternsUsed}},i=this.qesona.createPattern(t,r,{reward:u.coverageEstimate/100,success:!0,quality:u.coverageEstimate/100},this.config.sonaPatternType,"test-generation",{testCount:u.tests.length,framework:a.framework,testType:a.testType});Q.info(`Stored test generation pattern ${i.id} in QESONA`)}catch(t){Q.error("Failed to store pattern in QESONA:",t instanceof Error?t:void 0)}}async findSimilarTests(u){if(!this.flashAttention)return[];let a=[];try{for(let r of u){let i=this.generateTestEmbedding(r);this.testEmbeddings.set(r.id,i)}let t=await this.loadExistingTestEmbeddings();if(t.length===0)return[];for(let r of u){let i=this.testEmbeddings.get(r.id);if(!i)continue;let o=(await this.flashAttention.computeTestSimilarity(i,t.map(l=>l.embedding),5)).filter(l=>l.similarity>.7).map(l=>({testId:t[l.index].testId,similarity:l.similarity}));o.length>0&&a.push({test:r,similarTests:o})}return a}catch(t){return Q.error("Flash Attention similarity detection failed:",t instanceof Error?t:void 0),[]}}async prioritizeTestCases(u,a){if(!this.decisionTransformer)return u;try{let t={id:`prioritize-${Date.now()}`,features:[u.length/100,(a.coverageTarget||80)/100,a.testType==="unit"?.2:a.testType==="integration"?.5:.8,a.framework==="jest"?.3:a.framework==="vitest"?.4:.5],metadata:{testCount:u.length,framework:a.framework,testType:a.testType}},r=await this.decisionTransformer.predict(t);return Q.info(`DecisionTransformer prediction: ${r.reasoning}`),r.confidence>.7?u.sort((i,n)=>n.assertions-i.assertions):u}catch(t){return Q.error("DecisionTransformer prioritization failed:",t instanceof Error?t:void 0),u}}getQESONAStats(){return this.qesona?this.qesona.getStats():null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():null}async checkRequirementCoherence(u){return this.coherenceGate?this.coherenceGate.checkRequirementCoherence(u):{isCoherent:!0,energy:0,lane:"reflex",contradictions:[],recommendations:[],durationMs:0,usedFallback:!0}}isCoherenceGateAvailable(){return this.coherenceGate?.isAvailable()??!1}async verifyAndEnrichSpec(u){if(!this.coherenceGate||!this.config.enableCoherenceGate)return u;let a=await this.coherenceGate.validateAndEnrich(u);if(a.success)return a.value;throw a.error}async verifyTestPatternSelection(u,a){let t=O({id:A(),type:"test-pattern-selection",confidence:a,description:`Verify test pattern: ${u.name} (${u.type})`,payload:u,detectedBy:"test-generation-coordinator",severity:a>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(Q.info(`Test pattern '${u.name}' verified by consensus`),!0):(Q.warn(`Test pattern '${u.name}' NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async verifyMockStrategy(u,a){let t=O({id:A(),type:"mock-strategy",confidence:a,description:`Verify mock strategy for ${u.target}: ${u.mockType}`,payload:u,detectedBy:"test-generation-coordinator",severity:a>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(Q.info(`Mock strategy for '${u.target}' verified by consensus`),!0):(Q.warn(`Mock strategy for '${u.target}' NOT verified`),!1)}return!0}async verifyEdgeCaseGeneration(u,a){let t=O({id:A(),type:"edge-case-generation",confidence:a,description:`Verify edge case: ${u.description}`,payload:u,detectedBy:"test-generation-coordinator",severity:"high"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(Q.info(`Edge case '${u.description.slice(0,50)}...' verified by consensus`),!0):(Q.warn(`Edge case NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}encodeRequestAsFeatures(u){let a=[];for(a.push(u.testType==="unit"?.2:u.testType==="integration"?.5:.8),a.push(u.framework==="jest"?.25:u.framework==="vitest"?.5:u.framework==="mocha"?.75:.9),a.push(Math.min(1,u.sourceFiles.length/50)),a.push((u.coverageTarget||80)/100);a.length<384;)a.push(0);return a.slice(0,384)}generateTestEmbedding(u){let a=[],t=this.simpleHash(u.name);for(let r=0;r<64;r++)a.push((t>>r%32&1)*2-1);for(a.push(u.type==="unit"?.2:u.type==="integration"?.5:.8),a.push(Math.min(1,u.assertions/20));a.length<384;)a.push(0);return new Float32Array(a.slice(0,384))}async loadExistingTestEmbeddings(){try{let u=await this.memory.search("test-embedding:*",1e3),a=[];for(let t of u){let r=await this.memory.get(t);r&&a.push({testId:r.testId,embedding:new Float32Array(r.embedding)})}return a}catch{return[]}}simpleHash(u){let a=0;for(let t=0;t<u.length;t++){let r=u.charCodeAt(t);a=(a<<5)-a+r,a=a|0}return Math.abs(a)}async loadWorkflowState(){let u=await this.memory.get("test-generation:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("test-generation:coordinator:workflows",u,{namespace:"test-generation",persist:!0})}};S();var er=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}coordinator=null;testGenerator=null;patternMatcher=null;pluginConfig;get name(){return"test-generation"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{generateTests:this.generateTests.bind(this),generateTDDTests:this.generateTDDTests.bind(this),generatePropertyTests:this.generatePropertyTests.bind(this),generateTestData:this.generateTestData.bind(this),learnPatterns:this.learnPatterns.bind(this),getCoordinator:()=>this.coordinator,getTestGenerator:()=>this.testGenerator,getPatternMatcher:()=>this.patternMatcher}}getTaskHandlers(){return new Map([["generate-tests",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.sourceFiles,t=u.testType,r=u.framework;if(!a||a.length===0)return m(new Error("Invalid generate-tests payload: missing sourceFiles"));let i={sourceFiles:a,testType:t??"unit",framework:r??"vitest",coverageTarget:u.coverageTarget,patterns:u.patterns};return this.coordinator.generateTests(i)}],["generate-tdd-tests",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.feature,t=u.behavior,r=u.framework,i=u.phase;return!a||!t?m(new Error("Invalid generate-tdd-tests payload: missing feature or behavior")):this.coordinator.generateTDDTests({feature:a,behavior:t,framework:r??"vitest",phase:i??"red"})}],["generate-property-tests",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.function,t=u.properties;return!a||!t||t.length===0?m(new Error("Invalid generate-property-tests payload: missing function or properties")):this.coordinator.generatePropertyTests({function:a,properties:t,constraints:u.constraints})}],["generate-test-data",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.schema,t=u.count;return a?this.coordinator.generateTestData({schema:a,count:t??10,locale:u.locale,preserveRelationships:u.preserveRelationships}):m(new Error("Invalid generate-test-data payload: missing schema"))}]])}async onInitialize(){this.testGenerator=Ie(this.memory,this.pluginConfig.testGenerator),this.patternMatcher=new Ke(this.memory,this.pluginConfig.patternMatcher),this.coordinator=new Sa(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.testGenerator=null,this.patternMatcher=null}subscribeToEvents(){this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("learning-optimization.PatternConsolidated",this.handlePatternConsolidation.bind(this))}async onEvent(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(u);break;case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(u);break;default:break}}async generateTests(u){this.ensureInitialized();try{let a=await this.coordinator.generateTests(u);return a.success?this.trackSuccessfulGeneration(a.value):this.trackFailedGeneration(a.error),a}catch(a){return this.handleError(a)}}async generateTDDTests(u){this.ensureInitialized();try{return await this.coordinator.generateTDDTests(u)}catch(a){return this.handleError(a)}}async generatePropertyTests(u){this.ensureInitialized();try{return await this.coordinator.generatePropertyTests(u)}catch(a){return this.handleError(a)}}async generateTestData(u){this.ensureInitialized();try{return await this.coordinator.generateTestData(u)}catch(a){return this.handleError(a)}}async learnPatterns(u){this.ensureInitialized();try{return await this.coordinator.learnPatterns(u)}catch(a){return this.handleError(a)}}async handleCoverageGap(u){let a=u.payload;a.riskScore>=.7&&await this.memory.set(`test-generation:pending-gaps:${a.gapId}`,a,{namespace:"test-generation",ttl:86400})}async handleImpactAnalysis(u){let a=u.payload;await this.memory.set(`test-generation:impact:${a.analysisId}`,a,{namespace:"test-generation",ttl:3600})}async handlePatternConsolidation(u){u.payload.domains.includes("test-generation")}ensureInitialized(){if(!this._initialized)throw new Error("TestGenerationPlugin is not initialized");if(!this.coordinator||!this.testGenerator||!this.patternMatcher)throw new Error("TestGenerationPlugin services are not available")}handleError(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulGeneration(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedGeneration(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}};function Cs(s,e,u,a){return new er(s,e,u,a)}N();N();import{spawn as G6u}from"node:child_process";import{existsSync as Tc,readFileSync as V6u}from"node:fs";import{join as Mc}from"node:path";var ae={DEFAULT_TEST_TIMEOUT_MS:6e4,DEFAULT_FILE_TIMEOUT_MS:3e4,DEFAULT_VIEWPORT_WIDTH:1280,DEFAULT_VIEWPORT_HEIGHT:720,MAX_RESULTS:1e3,RESULT_RETENTION_MS:864e5,MAX_TESTS_TRACKED:1e4,MAX_EXECUTION_HISTORY:100,ANALYSIS_CACHE_TTL_MS:36e5,MAX_RETRY_HISTORY:50,MAX_ACTIONS_PER_RECORDING:1e3,MAX_RECORDING_DURATION_MS:18e5,MAX_WORKERS:32},ar={DEFAULT_STEP_TIMEOUT_MS:3e4,RETRY_DELAY_MS:1e3,DEFAULT_MAX_RETRIES:3,POLLING_INTERVAL_MS:100,ELEMENT_DETECTION_TIMEOUT_MS:1e3,POST_INTERACTION_DELAY_MS:500,DEFAULT_WAIT_MS:1e3,ACCESSIBILITY_TIMEOUT_MS:6e4,SCREENSHOT_QUALITY:80,TYPE_DEBOUNCE_MS:300},y0={BASE_DELAY_MS:1e3,MAX_DELAY_MS:3e4,DEFAULT_FLAKY_RATE:.3,DEFAULT_FLAKY_PASS_RATE:.7,RETRY_PASS_RATE_VARIATION:.1,SIGKILL_GRACE_PERIOD_MS:1e3},tr={DEFAULT_TIMEOUT_MS:6e4,QUICK_TIMEOUT_MS:1e4,MAX_CACHED_VALIDATIONS:1e3,CACHE_TTL_MS:36e5,CONTRACT_TTL_SECONDS:86400,MIGRATION_TTL_SECONDS:86400*90,MAX_RECURSION_DEPTH:10,MAX_SCHEMA_DEPTH:20,MAX_MIGRATION_STEPS:50,DEFAULT_SEARCH_LIMIT:100,HIGH_IMPACT_THRESHOLD:5,BREAKING_CHANGE_THRESHOLD:10,DEFAULT_PROVIDER_LOAD:50,HIGH_PROVIDER_LOAD_THRESHOLD:80},sSu={PASSING_RATE_WARNING_THRESHOLD:95,PASSING_RATE_CRITICAL_THRESHOLD:80,MIN_COVERAGE_FOR_DEPLOY:80,PERFECT_PASSING_RATE:100,METRIC_TTL_SECONDS:86400*7,STANDARD_METRIC_TTL_SECONDS:86400,MAX_HIGH_VULN_IMPACT:.3,MEDIUM_VULN_IMPACT:.1,MAX_DUPLICATION_PERCENT:20};var lSu={CHUNK_SIZE_BYTES:1024*1024,SPIKE_INTERVAL_MS:3e4,SPIKE_DURATION_MS:5e3};var cSu={MAX_DURATION_MS:6e4,MAX_AGE_MS:10080*60*1e3,DAYS_IN_YEAR:365,MAX_DEPENDENCY_COUNT:10},rr={MAX_TOKENS:2048,ERROR_TRUNCATION_LENGTH:200,OUTPUT_TRUNCATION_LENGTH:500,DETAILED_OUTPUT_TRUNCATION_LENGTH:1e3,MODEL_TIERS:{1:"claude-3-haiku-20240307",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"}};S();J();cu();var O6u={simulateForTesting:!1,simulatedTestsPerFile:5,simulatedFailureRate:.2,simulatedSkipRate:.1,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:rr.MAX_TOKENS},_6u=B.create("test-execution/test-executor"),ir=class{runResults=new Map;runStats=new Map;config;memory;llmRouter;MAX_RESULTS=ae.MAX_RESULTS;RESULT_RETENTION_MS=ae.RESULT_RETENTION_MS;constructor(e,u={}){this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...O6u,...u}}async execute(e){let u=A(),a=new Date;try{let t=this.validateRequest(e);if(t.success===!1)return m(t.error);let r=await this.runTests(e),i=new Date,n=i.getTime()-a.getTime(),o={runId:u,status:r.failed>0?"failed":"passed",total:r.total,passed:r.passed,failed:r.failed,skipped:r.skipped,duration:n,failedTests:r.failedTests,coverage:r.coverage,fileCoverages:r.fileCoverages};this.runResults.set(u,o),await this.storeResults(u,o);let l={runId:u,startTime:a,endTime:i,duration:n,testsPerSecond:r.total/(n/1e3),workers:1,memoryUsage:process.memoryUsage?.().heapUsed??0};return this.runStats.set(u,l),p(o)}catch(t){return m(g(t))}}async executeParallel(e){let u=A(),a=new Date;try{let t=this.validateParallelRequest(e);if(t.success===!1)return m(t.error);let{workers:r,sharding:i="file",isolation:n="process"}=e,o=this.shardTests(e.testFiles,r,i),l=await Promise.all(o.map((C,y)=>this.executeWorker(C,y,n,e))),c=this.aggregateResults(l),E=new Date,d=E.getTime()-a.getTime(),D={runId:u,status:c.failed>0?"failed":"passed",total:c.total,passed:c.passed,failed:c.failed,skipped:c.skipped,duration:d,failedTests:c.failedTests,coverage:c.coverage,fileCoverages:c.fileCoverages};this.runResults.set(u,D),await this.storeResults(u,D);let h={runId:u,startTime:a,endTime:E,duration:d,testsPerSecond:c.total/(d/1e3),workers:r,memoryUsage:process.memoryUsage?.().heapUsed??0};return this.runStats.set(u,h),p(D)}catch(t){return m(g(t))}}async getResults(e){let u=this.runResults.get(e);if(u)return p(u);try{let a=await this.memory.get(`test-run:${e}`);if(a)return this.runResults.set(e,a),p(a)}catch{}return m(new Error(`Test run not found: ${e}`))}async getStats(e){let u=this.runStats.get(e);if(u)return p(u);try{let a=await this.memory.get(`test-stats:${e}`);if(a)return this.runStats.set(e,a),p(a)}catch{}return m(new Error(`Test stats not found: ${e}`))}cleanupOldResults(){let e=Date.now(),u=0;for(let[a,t]of this.runResults){let r=t.duration?e-t.duration:e;e-r>this.RESULT_RETENTION_MS&&(this.runResults.delete(a),this.runStats.delete(a),u++)}if(this.runResults.size>this.MAX_RESULTS){let a=this.runResults.size-this.MAX_RESULTS,t=Array.from(this.runResults.entries());for(let r=0;r<a&&r<t.length;r++)this.runResults.delete(t[r][0]),this.runStats.delete(t[r][0]),u++}return u}destroy(){this.runResults.clear(),this.runStats.clear()}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(e){let u={1:"claude-3-haiku-20240307",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return u[e]||u[2]}async analyzeFailuresWithLLM(e){if(!this.isLLMAnalysisAvailable()||e.length===0)return null;try{let u=e.slice(0,5).map(t=>`- ${t.testName}: ${t.error?.substring(0,200)||"Unknown error"}`).join(`
2278
2278
  `);return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze these test failures and provide insights:
2279
2279
  ${u}
2280
2280
 
@@ -2420,7 +2420,7 @@ expect(result).toBeDefined();`,effort:"medium"}),u.push({action:"Add error bound
2420
2420
  return JSON.stringify(results);
2421
2421
  })()
2422
2422
  `,l=await n.evaluate(o);if(!l.success)throw l.error;let c=T(l.value),E=Ps(c);if(e.options?.failOnSeverity){let d={critical:0,high:1,medium:2,low:3,info:4},D=d[e.options.failOnSeverity],h=c.violations.filter(C=>d[C.impact]<=D);if(h.length>0)throw new te(`Accessibility violations found: ${h.length} at or above ${e.options.failOnSeverity}`,e.id,0,h.length)}return{accessibilityResult:E}}let r=await u.checkAccessibility({selector:e.target,wcagLevel:e.options?.wcagLevel??"AA",rules:e.options?.rules?{include:e.options.tags,exclude:e.options.context?.exclude}:void 0});if(!r.success)throw r.error;let i=r.value;if(e.options?.failOnSeverity){let n={critical:0,high:1,medium:2,low:3,info:4},o=n[e.options.failOnSeverity],l=i.violations.filter(c=>n[c.impact]<=o);if(l.length>0)throw new te(`Accessibility violations found: ${l.length} violations at or above ${e.options.failOnSeverity} severity`,e.id,0,l.length)}if(e.options?.maxViolations!==void 0&&i.violations.length>e.options.maxViolations)throw new te(`Too many accessibility violations: ${i.violations.length} (max: ${e.options.maxViolations})`,e.id,e.options.maxViolations,i.violations.length);return{accessibilityResult:i}}getCurrentPageUrl(e){for(let u=e.previousResults.length-1;u>=0;u--){let a=e.previousResults[u];if(a.data?.url&&typeof a.data.url=="string")return a.data.url}return e.baseUrl}resolveUrl(e,u){return e.startsWith("http://")||e.startsWith("https://")?e:new URL(e,u).toString()}delay(e){return new Promise(u=>setTimeout(u,e))}};function Is(s,e,u){return new Sr(s,e,u)}S();var wr=class{config;stepExecutors;log;constructor(e,u,a){this.config=e,this.stepExecutors=u,this.log=a}async executeStepWithRetry(e,u){let a=(e.retries??this.config.defaultRetries)+1,t=e.timeout??this.config.defaultStepTimeout,r,i=0;for(let o=1;o<=a;o++){let l=new Date;try{let c=await this.withTimeout(this.executeStepInternal(e,u),t,e.id),E=new Date,d=E.getTime()-l.getTime();return i+=d,{stepId:e.id,stepType:e.type,success:!0,durationMs:d,data:c.data,screenshot:c.screenshot,accessibilityResult:c.accessibilityResult,startedAt:l,completedAt:E,retryInfo:o>1?{attempts:o,totalDurationMs:i}:void 0}}catch(c){r=g(c),i+=Date.now()-l.getTime(),o<a&&(this.log(`Step "${e.id}" failed (attempt ${o}/${a}), retrying...`),await this.delay(this.config.retryDelay))}}let n=new Date;return{stepId:e.id,stepType:e.type,success:!1,durationMs:i,error:{message:r?.message??"Unknown error",code:r instanceof Lu?r.code:"UNKNOWN",stack:r?.stack},startedAt:new Date(n.getTime()-i),completedAt:n,retryInfo:{attempts:a,totalDurationMs:i}}}async executeStepInternal(e,u){return e.condition&&!this.evaluateCondition(e.condition,u)?{data:{}}:this.stepExecutors.executeStep(e,u)}evaluateCondition(e,u){let a={...u.variables};return o4(e,a,!0)}async withTimeout(e,u,a){return new Promise((t,r)=>{let i=setTimeout(()=>{r(new _e(a,u))},u);e.then(n=>{clearTimeout(i),t(n)}).catch(n=>{clearTimeout(i),r(n)})})}delay(e){return new Promise(u=>setTimeout(u,e))}};function Ks(s,e,u){return new wr(s,e,u)}var Tr=class{createSkippedResult(e,u){return{testCaseId:e.id,testCaseName:e.name,success:!0,status:"skipped",stepResults:[],totalDurationMs:0,startedAt:u,completedAt:new Date}}createErrorResult(e,u,a,t=[]){return{testCaseId:e.id,testCaseName:e.name,success:!1,status:"error",stepResults:t,totalDurationMs:Date.now()-u.getTime(),startedAt:u,completedAt:new Date,errorSummary:{failedStep:t.length>0?t[t.length-1].stepId:"setup",errorMessage:a}}}createResult(e,u,a,t,r){let i=new Date,o=a.some(c=>!c.success&&e.steps.find(E=>E.id===c.stepId)?.required&&!e.steps.find(E=>E.id===c.stepId)?.continueOnFailure)?"failed":"passed",l=a.find(c=>!c.success);return{testCaseId:e.id,testCaseName:e.name,success:o==="passed",status:o,stepResults:a,totalDurationMs:i.getTime()-u.getTime(),screenshots:t.length>0?t:void 0,accessibilityResults:r.length>0?r:void 0,startedAt:u,completedAt:i,browserInfo:e.viewport?{browserType:"chromium",viewport:e.viewport,userAgent:e.browserContext?.userAgent??""}:void 0,errorSummary:l?{failedStep:l.stepId,errorMessage:l.error?.message??"Unknown error",errorCode:l.error?.code,screenshot:l.error?.failureScreenshot}:void 0}}hasFailure(e){return e.some(u=>!u.success)}calculateSummary(e){return{total:e.length,passed:e.filter(u=>u.status==="passed").length,failed:e.filter(u=>u.status==="failed"||u.status==="error").length,skipped:e.filter(u=>u.status==="skipped").length}}createSuiteResult(e,u,a,t){let r=new Date,i=this.calculateSummary(a);return{suiteId:e,suiteName:u,success:i.failed===0,testResults:a,summary:{...i,totalDurationMs:r.getTime()-t.getTime()},startedAt:t,completedAt:r}}};function js(){return new Tr}S();var Lhu=B.create("test-execution/e2e-coordinator"),Mr=class{constructor(e,u={}){this.client=e;this.config={...vs,...u};let a=t=>this.log(t);this.orchestrator=zs(e,this.config,a),this.stepExecutors=Is(this.config,this.orchestrator,a),this.retryHandler=Ks(this.config,this.stepExecutors,a),this.resultCollector=js(),this.log(`E2E Runner initialized with ${this.orchestrator.isUsingAgentBrowser()?"agent-browser":"vibium"} client`)}config;orchestrator;stepExecutors;retryHandler;resultCollector;async runTestCase(e){let u=new Date,a=[],t=[],r=[];if(e.skip)return this.resultCollector.createSkippedResult(e,u);if(e.requiredEnvVars?.length){let i=e.requiredEnvVars.filter(n=>!process.env[n]);if(i.length>0)return this.resultCollector.createErrorResult(e,u,`Missing required environment variables: ${i.join(", ")}`)}try{let i=await this.orchestrator.ensureBrowserLaunched(e);if(i)return this.resultCollector.createErrorResult(e,u,i);let n={testCase:e,baseUrl:e.baseUrl,variables:e.testData??{},previousResults:a,useAgentBrowser:this.orchestrator.isUsingAgentBrowser()};if(this.orchestrator.isUsingAgentBrowser()&&(n.currentSnapshot=await this.orchestrator.refreshSnapshot()),e.hooks?.beforeAll){let o=await this.executeHooks(e.hooks.beforeAll,n,"beforeAll");if(a.push(...o),this.resultCollector.hasFailure(o)&&this.config.stopOnFirstFailure)return this.resultCollector.createResult(e,u,a,t,r)}for(let o of e.steps){if(e.hooks?.beforeEach){let c=await this.executeHooks(e.hooks.beforeEach,n,"beforeEach");a.push(...c)}o.delayBefore&&o.delayBefore>0&&await this.delay(o.delayBefore);let l=await this.retryHandler.executeStepWithRetry(o,n);if(a.push(l),l.screenshot&&t.push(l.screenshot),l.accessibilityResult&&r.push(l.accessibilityResult),o.delayAfter&&o.delayAfter>0&&await this.delay(o.delayAfter),e.hooks?.afterEach){let c=await this.executeHooks(e.hooks.afterEach,n,"afterEach");a.push(...c)}if(!l.success){if(e.hooks?.onFailure){let c=await this.executeHooks(e.hooks.onFailure,n,"onFailure");a.push(...c)}if(this.config.screenshotOnFailure&&!l.screenshot){let c=await this.orchestrator.captureFailureScreenshot(o.id);c&&(l.error={...l.error,failureScreenshot:c},t.push(c))}if(this.config.stopOnFirstFailure&&o.required&&!o.continueOnFailure)break}}if(e.hooks?.afterAll){let o=await this.executeHooks(e.hooks.afterAll,n,"afterAll");a.push(...o)}return this.resultCollector.createResult(e,u,a,t,r)}catch(i){let n=k(i);return this.resultCollector.createErrorResult(e,u,n,a)}}async runTestSuite(e,u=e.parallel?"parallel":"sequential"){let a=new Date,t=[],r=e.testCases.filter(n=>n.only),i=r.length>0?r:e.testCases;if(u==="parallel"){let n=await this.executeInParallel(i,e.maxWorkers);t.push(...n)}else for(let n of i){let o=await this.runTestCase(n);t.push(o)}return this.resultCollector.createSuiteResult(e.id,e.name,t,a)}async executeHooks(e,u,a){let t=[];for(let r of e){this.log(`Executing ${a} hook: ${r.id}`);let i=await this.retryHandler.executeStepWithRetry(r,u);if(t.push(i),!i.success&&r.required){this.log(`${a} hook "${r.id}" failed`);break}}return t}async executeInParallel(e,u){let a=u??this.config.maxParallelWorkers,t=[],r=[...e],i=async()=>{for(;r.length>0;){let o=r.shift();if(o){let l=await this.runTestCase(o);t.push(l)}}},n=[];for(let o=0;o<Math.min(a,e.length);o++)n.push(i());return await Promise.all(n),t}delay(e){return new Promise(u=>setTimeout(u,e))}log(e){this.config.verbose&&Lhu.info(`${e}`)}};function Hs(s,e){return new Mr(s,e)}S();var Gs=class{calculator;constructor(e){this.calculator=e??new s4}optimize(e,u=1){if(e.length===0)return this.emptyResult();if(e.length===1)return this.singleTestResult(e[0]);let{graph:a,testIds:t,fileIds:r,edgeCount:i}=this.buildCoverageGraph(e),n=this.calculator.approxMinCut(a),o=a.getStats(),l=new Set(n.sourceSide),c=new Set,E=new Set;for(let w of t)l.has(w)?c.add(w):E.add(w);let d=this.buildFileCoverageMap(e),D=new Set(d.keys()),h=this.findUniquelyCriticalTests(e,d);for(let w of h)c.add(w),E.delete(w);let C=new Set(c),y=new Set(E);if(u<1){let w=Math.ceil(D.size*u);this.computeCoveredFiles(e,C).size<w&&this.promoteToCritical(e,C,y,w)}else this.ensureFullCoverage(e,C,y,d);let x=this.buildExecutionOrder(e,C,y),b=new Map(e.map(w=>[w.testId,w])),R=Array.from(y).reduce((w,P)=>w+(b.get(P)?.estimatedDurationMs??0),0);return{criticalTests:Array.from(C),skippableTests:Array.from(y),executionOrder:x,estimatedTimeSavingsMs:R,graphStats:{testCount:e.length,coverageEdges:i,mincutValue:n.value,connectedComponents:o.componentCount}}}buildCoverageGraph(e){let u=new l4,a=[],t=new Set,r=new Map;for(let n of e)for(let o of n.coveredFiles)r.set(o,(r.get(o)??0)+1);for(let n of e){let o={id:n.testId,type:"agent",weight:n.coveredFiles.length,createdAt:new Date,metadata:{nodeType:"test",testFile:n.testFile}};u.addVertex(o),a.push(n.testId)}for(let[n]of r){let o=`file:${n}`,l={id:o,type:"domain",weight:1,createdAt:new Date,metadata:{nodeType:"file",filePath:n}};u.addVertex(l),t.add(o)}let i=0;for(let n of e)for(let o of n.coveredFiles){let l=`file:${o}`,E=1/(r.get(o)??1),d={source:n.testId,target:l,weight:E,type:"coordination",bidirectional:!0};u.addEdge(d),i++}return{graph:u,testIds:a,fileIds:Array.from(t),edgeCount:i}}buildFileCoverageMap(e){let u=new Map;for(let a of e)for(let t of a.coveredFiles){let r=u.get(t);r||(r=new Set,u.set(t,r)),r.add(a.testId)}return u}findUniquelyCriticalTests(e,u){let a=new Set;for(let[,t]of u)if(t.size===1){let[r]=t;a.add(r)}return a}computeCoveredFiles(e,u){let a=new Set;for(let t of e)if(u.has(t.testId))for(let r of t.coveredFiles)a.add(r);return a}promoteToCritical(e,u,a,t){let r=this.computeCoveredFiles(e,u),i=new Map(e.map(o=>[o.testId,o])),n=Array.from(a);for(;r.size<t&&n.length>0;){let o=-1,l=0;for(let d=0;d<n.length;d++){let D=i.get(n[d]);if(!D)continue;let h=D.coveredFiles.filter(C=>!r.has(C)).length;h>l&&(l=h,o=d)}if(o===-1||l===0)break;let c=n[o];n.splice(o,1),u.add(c),a.delete(c);let E=i.get(c);if(E)for(let d of E.coveredFiles)r.add(d)}}ensureFullCoverage(e,u,a,t){let r=this.computeCoveredFiles(e,u);for(let[i,n]of t)if(!r.has(i)){for(let o of n)if(a.has(o)){u.add(o),a.delete(o);let l=e.find(c=>c.testId===o);if(l)for(let c of l.coveredFiles)r.add(c);break}}}buildExecutionOrder(e,u,a){let t=new Map(e.map(o=>[o.testId,o])),r=(o,l)=>{let c=t.get(o)?.coveredFiles.length??0;return(t.get(l)?.coveredFiles.length??0)-c},i=Array.from(u).sort(r),n=Array.from(a).sort(r);return[...i,...n]}emptyResult(){return{criticalTests:[],skippableTests:[],executionOrder:[],estimatedTimeSavingsMs:0,graphStats:{testCount:0,coverageEdges:0,mincutValue:0,connectedComponents:0}}}singleTestResult(e){return{criticalTests:[e.testId],skippableTests:[],executionOrder:[e.testId],estimatedTimeSavingsMs:0,graphStats:{testCount:1,coverageEdges:e.coveredFiles.length,mincutValue:0,connectedComponents:(e.coveredFiles.length>0,1)}}}};function Jc(s){return new Gs(s)}var Nhu={simulateForTesting:!1,enablePrioritization:!0,maxConcurrentWorkflows:5,defaultTimeout:6e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Nu=B.create("test-execution"),Vs=class extends Y{memory;executor;flakyDetector;retryHandler;prioritizer;e2eRunner;activeRuns=new Set;constructor(e,u,a={}){let t={...Nhu,...a};super(e,"test-execution",t,{verifyFindingTypes:["flaky-test-detection","test-failure-analysis","retry-strategy"],...t.consensusConfig}),this.memory=u,this.executor=new ir({memory:u},{simulateForTesting:t.simulateForTesting,...t.executorConfig}),this.flakyDetector=new nr(u,{simulateForTesting:t.simulateForTesting,...t.flakyDetectorConfig}),this.retryHandler=new sr(u,{simulateForTesting:t.simulateForTesting,...t.retryHandlerConfig}),this.prioritizer=new Cr(u,t.prioritizerConfig),t.vibiumClient&&(this.e2eRunner=Hs(t.vibiumClient,t.e2eRunnerConfig))}async onInitialize(){this.config.enablePrioritization&&await this.prioritizer.initialize(),this.subscribeToEvents()}async onDispose(){for(let e of this.activeRuns)await this.cancelRun(e);this.activeRuns.clear()}getActiveRuns(){return Array.from(this.activeRuns)}async cancelRun(e){return this.activeRuns.has(e)?(this.activeRuns.delete(e),await this.publishEvent("test-execution.TestRunCancelled",{runId:e}),p(void 0)):m(new Error(`Run not found or already completed: ${e}`))}async runTests(e){let{testsToRun:u}=await this.partitionHoldoutTests(e.testFiles);if(u.length===0)return p({runId:A(),status:"passed",total:0,passed:0,failed:0,skipped:0,duration:0,failedTests:[]});let a=this.detectFramework(u),t=e.workers??Math.min(4,Math.max(1,u.length)),r=e.timeout??6e4;if(e.parallel!==!1&&u.length>1){let n=await this.executeParallel({testFiles:u,framework:a,workers:t,timeout:r});if(e.retryCount&&e.retryCount>0&&n.success&&n.value.failed>0){let o=n.value.failedTests.map(l=>l.testId);await this.retry({runId:n.value.runId,failedTests:o,maxRetries:e.retryCount,backoff:"exponential"})}return n}let i=await this.execute({testFiles:u,framework:a,timeout:r});if(e.retryCount&&e.retryCount>0&&i.success&&i.value.failed>0){let n=i.value.failedTests.map(o=>o.testId);await this.retry({runId:i.value.runId,failedTests:n,maxRetries:e.retryCount,backoff:"exponential"})}return i}detectFramework(e){let u=e.some(t=>t.includes(".test.")||t.includes(".spec.")),a=e.some(t=>t.includes("_test.")||t.includes(".mocha."));return u?"vitest":a?"mocha":"vitest"}async execute(e){let u=A();this.activeRuns.add(u),this.infraRecoveryAttempts=0;try{let{testsToRun:a}=await this.partitionHoldoutTests(e.testFiles);if(a.length===0)return this.activeRuns.delete(u),p({runId:u,status:"passed",total:0,passed:0,failed:0,skipped:0,duration:0,failedTests:[]});e={...e,testFiles:a};let t=e.testFiles,r=null;if(this.config.enablePrioritization&&e.testFiles.length>1){let o=await this.prioritizeTests(e.testFiles,u,!1,1);o.success&&(t=o.value.orderedFiles,r=o.value.prioritizationInfo)}await this.publishEvent(Pu.TestRunStarted,{runId:u,testCount:t.length,parallel:!1,workers:1});let i={...e,testFiles:t},n=await this.executor.execute(i);if(this.activeRuns.delete(u),n.success){this.config.enablePrioritization&&r&&await this.recordExecutionResults(u,t,n.value,r),await this.publishEvent(Pu.TestRunCompleted,{runId:n.value.runId,passed:n.value.passed,failed:n.value.failed,skipped:n.value.skipped,duration:n.value.duration});for(let o of n.value.failedTests)await this.flakyDetector.recordExecution(o.testId,{runId:n.value.runId,passed:!1,duration:o.duration,error:o.error,timestamp:new Date});try{this.eventBus&&await this.eventBus.publish(L("AsymmetricLearningOutcome","test-execution",{runId:n.value.runId,totalPassed:n.value.passed,totalFailed:n.value.failed,failedTests:n.value.failedTests.map(o=>({testId:o.testId,error:o.error?.substring(0,200)}))},n.value.runId))}catch{}if(this.config.infraHealing&&n.value.failedTests.length>0){this.feedInfraHealingFromFailures(n.value.failedTests);let o=await this.attemptAutoRecoveryAndRerun(n.value.failedTests,e.framework,{timeout:e.timeout,env:e.env});if(o)return o}}return n}catch(a){return this.activeRuns.delete(u),m(g(a))}}async executeParallel(e){let u=A();this.activeRuns.add(u),this.infraRecoveryAttempts=0;try{let{testsToRun:a}=await this.partitionHoldoutTests(e.testFiles);if(a.length===0)return this.activeRuns.delete(u),p({runId:u,status:"passed",total:0,passed:0,failed:0,skipped:0,duration:0,failedTests:[]});if(e={...e,testFiles:a},this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&(Nu.warn("Topology degraded, reducing parallel workers"),e={...e,workers:Math.max(1,Math.floor(e.workers/2))}),this.minCutMixin.shouldPauseOperations())return this.activeRuns.delete(u),m(new Error("Parallel test execution paused: topology is in critical state"));let t=e.testFiles,r=null;if(this.config.enablePrioritization&&e.testFiles.length>1){let o=await this.prioritizeTests(e.testFiles,u,!0,e.workers);o.success&&(t=o.value.orderedFiles,r=o.value.prioritizationInfo)}await this.publishEvent(Pu.TestRunStarted,{runId:u,testCount:t.length,parallel:!0,workers:e.workers});let i={...e,testFiles:t},n=await this.executor.executeParallel(i);if(this.activeRuns.delete(u),n.success){this.config.enablePrioritization&&r&&await this.recordExecutionResults(u,t,n.value,r),await this.publishEvent(Pu.TestRunCompleted,{runId:n.value.runId,passed:n.value.passed,failed:n.value.failed,skipped:n.value.skipped,duration:n.value.duration});for(let o of n.value.failedTests){let l=await this.flakyDetector.getFlakinessScore(o.testId);l>.3&&await this.publishEvent(Pu.FlakyTestDetected,{testId:o.testId,testFile:o.file,failureRate:l,pattern:"unknown"})}try{this.eventBus&&await this.eventBus.publish(L("AsymmetricLearningOutcome","test-execution",{runId:n.value.runId,totalPassed:n.value.passed,totalFailed:n.value.failed,failedTests:n.value.failedTests.map(o=>({testId:o.testId,error:o.error?.substring(0,200)}))},n.value.runId))}catch{}if(this.config.infraHealing&&n.value.failedTests.length>0){this.feedInfraHealingFromFailures(n.value.failedTests);let o=await this.attemptAutoRecoveryAndRerun(n.value.failedTests,e.framework,{timeout:e.timeout,env:e.env});if(o)return o}}return n}catch(a){return this.activeRuns.delete(u),m(g(a))}}async detectFlaky(e){let u=await this.flakyDetector.detectFlaky(e);if(u.success){let a=[];for(let t of u.value.flakyTests){if(this.config.enableConsensus&&t.failureRate>.3&&!await this.verifyFlakyTestDetection({testId:t.testId,testFile:t.file,failureRate:t.failureRate,pattern:t.pattern},Math.min(.9,t.failureRate+.3))){Nu.info(`Flaky test '${t.testId}' not verified, skipping publication`);continue}a.push(t),await this.publishEvent(Pu.FlakyTestDetected,{testId:t.testId,testFile:t.file,failureRate:t.failureRate,pattern:t.pattern})}return p({...u.value,flakyTests:a})}return u}async retry(e){if(this.minCutMixin.shouldPauseOperations())return m(new Error("Retry operation paused: topology is in critical state"));let u=await this.executor.getResults(e.runId);if(!u.success)return m(new Error(`Original run not found: ${e.runId}`));let a=u.value.failedTests.filter(r=>e.failedTests.includes(r.testId));if(a.length===0)return p({originalFailed:0,retried:0,nowPassing:0,stillFailing:0,flakyDetected:[]});this.config.enableConsensus&&a.length>5&&(await this.verifyRetryStrategy({runId:e.runId,testCount:a.length,maxRetries:e.maxRetries,backoffType:e.backoff??"exponential"},.7+a.length/100)||(Nu.warn("Retry strategy not verified, proceeding with reduced retries"),e={...e,maxRetries:Math.max(1,Math.floor(e.maxRetries/2))})),await this.publishEvent(Pu.RetryTriggered,{runId:e.runId,testCount:a.length});let t=await this.retryHandler.executeWithRetry({runId:e.runId,failedTests:a,maxRetries:e.maxRetries,backoff:e.backoff??"exponential",onRetry:(r,i)=>{}});if(t.success)for(let r of t.value.flakyDetected){let i=a.find(n=>n.testId===r);await this.publishEvent(Pu.FlakyTestDetected,{testId:r,testFile:i?.file??"unknown",failureRate:.5,pattern:"unknown"})}return t}async getStats(e){return this.executor.getStats(e)}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestSuiteCreated",async e=>{let u=e.payload}),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",async e=>{let u=e.payload})}async publishEvent(e,u){let a=L(e,"test-execution",u);await this.eventBus.publish(a)}feedInfraHealingFromFailures(e){if(!this.config.infraHealing)return;let u=e.map(t=>t.error).join(`
2423
- `);this.config.infraHealing.feedTestOutput(u);let a=this.config.infraHealing.getObserver().getFailingServices();if(a.size>0){let t=e.map(r=>r.testId);for(let r of a)this.config.infraHealing.recordAffectedTests(r,t)}}infraRecoveryAttempts=0;async attemptAutoRecoveryAndRerun(e,u,a){if(!this.config.infraHealing||!(this.config.infraAutoRecover??!0))return null;let r=this.config.infraMaxAutoRecoveryAttempts??1;if(this.infraRecoveryAttempts>=r||this.config.infraHealing.getObserver().getFailingServices().size===0)return null;this.infraRecoveryAttempts++;let o=(await this.config.infraHealing.runRecoveryCycle()).filter(c=>c.recovered);if(o.length===0)return null;let l=new Set;for(let c of o)for(let E of c.affectedTestIds){let d=e.find(D=>D.testId===E);d&&l.add(d.file)}return l.size===0?null:this.execute({testFiles:[...l],framework:u,timeout:a.timeout,env:a.env})}async prioritizeTests(e,u,a,t){try{let r=e.map(l=>({testId:this.generateTestId(l),filePath:l,testName:this.extractTestName(l),testType:"unit",priority:"p2",complexity:.5,domain:"test-execution",estimatedDuration:5e3,coverage:0,failureHistory:[],flakinessScore:0,executionCount:0})),i={runId:u,totalTests:e.length,availableTime:6e4,workers:t,mode:a?"parallel":"sequential",phase:"ci"},n=await this.prioritizer.prioritize(r,i);if(!n.success)return m(n.error);let o=n.value.tests.map(l=>l.filePath);return p({orderedFiles:o,prioritizationInfo:{method:n.value.method,averageConfidence:n.value.averageConfidence,learningStatus:n.value.learningStatus}})}catch(r){return m(g(r))}}async recordExecutionResults(e,u,a,t){for(let r=0;r<u.length;r++){let i=this.generateTestId(u[r]),n=t,o=a.failedTests.find(D=>D.file===u[r]),l=!o,c=o?.duration??a.duration/u.length,E=r<Math.ceil(u.length*.2)?"critical":r<Math.ceil(u.length*.5)?"high":r<Math.ceil(u.length*.8)?"standard":"low",d={runId:e,totalTests:u.length,availableTime:6e4,workers:1,mode:"sequential",phase:"ci"};await this.prioritizer.recordExecution(i,{passed:l,duration:c,priority:E,failedEarly:o!==void 0&&r<Math.ceil(u.length*.3),coverageImproved:!1,flakyDetected:!1},d)}}generateTestId(e){return`test-${e.replace(/[^a-zA-Z0-9]/g,"-")}`}extractTestName(e){let u=e.split("/");return u[u.length-1]||e}async partitionHoldoutTests(e,u){if(!(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true"))return{testsToRun:e,holdoutCount:0};try{let t=await this.memory.get("test-generation:holdout-test-files");if(!t||t.length===0)return{testsToRun:e,holdoutCount:0};let r=new Set(t),i=[],n=[];for(let l of e)r.has(l)?n.push(l):i.push(l);return u===!0||process.env.AQE_RUN_HOLDOUT_TESTS==="true"?(Nu.info(`Holdout run: executing ${n.length} holdout tests, skipping ${i.length} normal tests`),await this.memory.set(`test-execution:holdout-run:${Date.now()}`,{holdoutCount:n.length,holdoutFiles:n},{namespace:"test-execution",ttl:86400}),{testsToRun:n,holdoutCount:n.length}):(n.length>0&&(Nu.info(`Normal run: filtered out ${n.length} holdout test(s), running ${i.length} normal tests`),await this.memory.set(`test-execution:holdout-filtered:${Date.now()}`,{holdoutCount:n.length,holdoutFiles:n},{namespace:"test-execution",ttl:86400})),{testsToRun:i,holdoutCount:n.length})}catch(t){return Nu.warn("Holdout test partitioning failed (running all tests)",{error:t instanceof Error?t.message:String(t)}),{testsToRun:e,holdoutCount:0}}}async executeE2ETestCase(e){if(!this.e2eRunner)return m(new Error("E2E runner not available - Vibium client not configured"));try{await this.publishEvent("test-execution.E2ETestStarted",{testCaseId:e.id,testCaseName:e.name});let u=await this.e2eRunner.runTestCase(e);return await this.publishEvent("test-execution.E2ETestCompleted",{testCaseId:u.testCaseId,testCaseName:u.testCaseName,success:u.success,duration:u.totalDurationMs}),p(u)}catch(u){return m(g(u))}}async executeE2ETestSuite(e,u="sequential"){if(!this.e2eRunner)return m(new Error("E2E runner not available - Vibium client not configured"));try{await this.publishEvent("test-execution.E2ETestSuiteStarted",{suiteId:e.id,suiteName:e.name,testCount:e.testCases.length,strategy:u});let a=await this.e2eRunner.runTestSuite(e,u);return await this.publishEvent("test-execution.E2ETestSuiteCompleted",{suiteId:a.suiteId,suiteName:a.suiteName,success:a.success,passed:a.summary.passed,failed:a.summary.failed,total:a.summary.total,duration:a.summary.totalDurationMs}),p(a)}catch(a){return m(g(a))}}optimizeTestSuite(e,u){return Jc().optimize(e,u?.coverageThreshold)}async verifyFlakyTestDetection(e,u){let a=O({id:A(),type:"flaky-test-detection",confidence:u,description:`Verify flaky test classification: ${e.testId} (failure rate: ${(e.failureRate*100).toFixed(1)}%)`,payload:e,detectedBy:"test-execution-coordinator",severity:e.failureRate>.5?"high":"medium"});if(this.consensusMixin.requiresConsensus(a)){let t=await this.consensusMixin.verifyFinding(a);return t.success&&t.value.verdict==="verified"?(Nu.info(`Flaky test '${e.testId}' classification verified by consensus`),!0):(Nu.warn(`Flaky test '${e.testId}' classification NOT verified: ${t.success?t.value.verdict:t.error.message}`),!1)}return!0}async verifyRetryStrategy(e,u){let a=O({id:A(),type:"retry-strategy",confidence:u,description:`Verify retry strategy: ${e.testCount} tests with ${e.maxRetries} max retries (${e.backoffType})`,payload:e,detectedBy:"test-execution-coordinator",severity:e.testCount>10?"high":"medium"});if(this.consensusMixin.requiresConsensus(a)){let t=await this.consensusMixin.verifyFinding(a);return t.success&&t.value.verdict==="verified"?(Nu.info("Retry strategy verified by consensus"),!0):(Nu.warn(`Retry strategy NOT verified: ${t.success?t.value.verdict:t.error.message}`),!1)}return!0}async verifyTestFailureAnalysis(e,u){let a=O({id:A(),type:"test-failure-analysis",confidence:u,description:`Verify failure analysis for ${e.testId}: ${e.failureType} - ${e.rootCause}`,payload:e,detectedBy:"test-execution-coordinator",severity:"high"});if(this.consensusMixin.requiresConsensus(a)){let t=await this.consensusMixin.verifyFinding(a);return t.success&&t.value.verdict==="verified"?(Nu.info(`Failure analysis for '${e.testId}' verified by consensus`),!0):(Nu.warn(`Failure analysis NOT verified: ${t.success?t.value.verdict:t.error.message}`),!1)}return!0}};function Uc(s,e,u){return new Vs(s,e,u)}var Ihu=null;function Zc(){return Ihu}var Os=class extends U{coordinator=null;constructor(e,u){super(e,u)}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 e=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));if(e.testFiles&&Array.isArray(e.testFiles)){let u={testFiles:e.testFiles,parallel:e.parallel,retryCount:e.retryCount,timeout:e.timeout,workers:e.workers};return this.coordinator.runTests(u)}else if(e.framework){let u={testFiles:e.testFiles||[],framework:e.framework,timeout:e.timeout,env:e.env,reporters:e.reporters};return this.coordinator.execute(u)}return m(new Error("Invalid execute-tests payload: missing testFiles or framework"))}],["detect-flaky",async e=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let u=e.testFiles,a=e.runs,t=e.threshold;return u?this.coordinator.detectFlaky({testFiles:u,runs:a??5,threshold:t??.1}):m(new Error("Invalid detect-flaky payload: missing testFiles"))}],["retry-tests",async e=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let u=e.runId,a=e.failedTests,t=e.maxRetries;return!u||!a?m(new Error("Invalid retry-tests payload: missing runId or failedTests")):this.coordinator.retry({runId:u,failedTests:a,maxRetries:t??3,backoff:e.backoff})}]])}async onInitialize(){let e=Zc()??void 0;this.coordinator=Uc(this.eventBus,this.memory,{infraHealing:e}),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(e){switch(e.type){case"test-generation.TestSuiteCreated":await this.handleTestSuiteCreated(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGapDetected(e);break}}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestSuiteCreated",e=>this.handleEvent(e)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",e=>this.handleEvent(e)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",e=>this.handleEvent(e))}async handleTestSuiteCreated(e){let u=e.payload;this.updateHealth({lastActivity:new Date}),await this.memory.set(`suite-event:${u.suiteId}`,{eventId:e.id,timestamp:e.timestamp,sourceFiles:u.sourceFiles},{namespace:"test-execution",ttl:864e5})}async handleQualityGateEvaluated(e){let u=e.payload;u.passed||await this.memory.set(`quality-context:${u.gateId}`,{requiresRetry:!0,failedChecks:u.checks.filter(a=>!a.passed).map(a=>a.name)},{namespace:"test-execution",ttl:36e5}),this.updateHealth({lastActivity:new Date})}async handleCoverageGapDetected(e){let u=e.payload;u.riskScore>.7&&await this.memory.set(`coverage-gap:${u.gapId}`,{file:u.file,uncoveredLines:u.uncoveredLines,priority:"high"},{namespace:"test-execution",persist:!0}),this.updateHealth({lastActivity:new Date})}};function Qc(s,e){return new Os(s,e)}N();S();N();S();J();var Khu={defaultThreshold:80,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},Yc=B.create("coverage-analysis/coverage-analyzer"),ve=class s{static DEFAULT_THRESHOLD=80;static VECTOR_DIMENSION=384;memory;config;llmRouter;constructor(e,u={}){this.config={...Khu,...u},this.isMemoryBackend(e)?(this.memory=e,this.llmRouter=void 0):(this.memory=e.memory,this.llmRouter=e.llmRouter)}isMemoryBackend(e){return typeof e.get=="function"&&typeof e.set=="function"&&!("memory"in e)}async analyze(e){try{let{coverageData:u,threshold:a=this.config.defaultThreshold}=e,t=this.calculateMetrics(u),i=this.calculateOverallCoverage(t)>=a,n=await this.calculateDelta(t),o=this.generateRecommendations(u,t,a);return await this.storeCoverageSnapshot(t),e.includeFileDetails&&(await this.indexFileCoverageVectors(u.files),await this.storeFileCoverageKV(u.files)),p({summary:t,meetsThreshold:i,delta:n,recommendations:o})}catch(u){return m(g(u))}}async findGaps(e,u=this.config.defaultThreshold){try{let a=[],t=0;for(let i of e.files)if(this.calculateFileCoveragePercentage(i)<u){let o=this.calculateFileRiskScore(i),l=this.riskScoreToSeverity(o),c=await this.findSimilarGapPatterns(i);a.push({id:this.generateGapId(i.path),file:i.path,lines:i.uncoveredLines,branches:i.uncoveredBranches,riskScore:o,severity:l,recommendation:this.generateGapRecommendation(i,c)}),t+=i.uncoveredLines.length}a.sort((i,n)=>n.riskScore-i.riskScore);let r=this.estimateEffort(t);return p({gaps:a,totalUncoveredLines:t,estimatedEffort:r})}catch(a){return m(g(a))}}calculateMetrics(e){let u=e.files;if(u.length===0)return{line:0,branch:0,function:0,statement:0,files:0};let a=0,t=0,r=0,i=0,n=0,o=0,l=0,c=0;for(let E of u)a+=E.lines.total,t+=E.lines.covered,r+=E.branches.total,i+=E.branches.covered,n+=E.functions.total,o+=E.functions.covered,l+=E.statements.total,c+=E.statements.covered;return{line:a>0?t/a*100:0,branch:r>0?i/r*100:0,function:n>0?o/n*100:0,statement:l>0?c/l*100:0,files:u.length}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async analyzeCoverageWithLLM(e,u){if(!this.llmRouter)return this.getDefaultInsights();try{let a=this.buildCoverageAnalysisPrompt(e,u),t=this.getModelForTier(this.config.llmModelTier??2),r=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.
2423
+ `);this.config.infraHealing.feedTestOutput(u);let a=this.config.infraHealing.getObserver().getFailingServices();if(a.size>0){let t=e.map(r=>r.testId);for(let r of a)this.config.infraHealing.recordAffectedTests(r,t)}}infraRecoveryAttempts=0;async attemptAutoRecoveryAndRerun(e,u,a){if(!this.config.infraHealing||!(this.config.infraAutoRecover??!0))return null;let r=this.config.infraMaxAutoRecoveryAttempts??1;if(this.infraRecoveryAttempts>=r||this.config.infraHealing.getObserver().getFailingServices().size===0)return null;this.infraRecoveryAttempts++;let o=(await this.config.infraHealing.runRecoveryCycle()).filter(c=>c.recovered);if(o.length===0)return null;let l=new Set;for(let c of o)for(let E of c.affectedTestIds){let d=e.find(D=>D.testId===E);d&&l.add(d.file)}return l.size===0?null:this.execute({testFiles:[...l],framework:u,timeout:a.timeout,env:a.env})}async prioritizeTests(e,u,a,t){try{let r=e.map(l=>({testId:this.generateTestId(l),filePath:l,testName:this.extractTestName(l),testType:"unit",priority:"p2",complexity:.5,domain:"test-execution",estimatedDuration:5e3,coverage:0,failureHistory:[],flakinessScore:0,executionCount:0})),i={runId:u,totalTests:e.length,availableTime:6e4,workers:t,mode:a?"parallel":"sequential",phase:"ci"},n=await this.prioritizer.prioritize(r,i);if(!n.success)return m(n.error);let o=n.value.tests.map(l=>l.filePath);return p({orderedFiles:o,prioritizationInfo:{method:n.value.method,averageConfidence:n.value.averageConfidence,learningStatus:n.value.learningStatus}})}catch(r){return m(g(r))}}async recordExecutionResults(e,u,a,t){for(let r=0;r<u.length;r++){let i=this.generateTestId(u[r]),n=t,o=a.failedTests.find(D=>D.file===u[r]),l=!o,c=o?.duration??a.duration/u.length,E=r<Math.ceil(u.length*.2)?"critical":r<Math.ceil(u.length*.5)?"high":r<Math.ceil(u.length*.8)?"standard":"low",d={runId:e,totalTests:u.length,availableTime:6e4,workers:1,mode:"sequential",phase:"ci"};await this.prioritizer.recordExecution(i,{passed:l,duration:c,priority:E,failedEarly:o!==void 0&&r<Math.ceil(u.length*.3),coverageImproved:!1,flakyDetected:!1},d)}}generateTestId(e){return`test-${e.replace(/[^a-zA-Z0-9]/g,"-")}`}extractTestName(e){let u=e.split("/");return u[u.length-1]||e}async partitionHoldoutTests(e,u){if(!(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true"))return{testsToRun:e,holdoutCount:0};try{let t=await this.memory.get("test-generation:holdout-test-files");if(!t||t.length===0)return{testsToRun:e,holdoutCount:0};let r=new Set(t),i=[],n=[];for(let l of e)r.has(l)?n.push(l):i.push(l);return u===!0||process.env.AQE_RUN_HOLDOUT_TESTS==="true"?(Nu.info(`Holdout run: executing ${n.length} holdout tests, skipping ${i.length} normal tests`),await this.memory.set(`test-execution:holdout-run:${Date.now()}`,{holdoutCount:n.length,holdoutFiles:n},{namespace:"test-execution",ttl:86400}),{testsToRun:n,holdoutCount:n.length}):(n.length>0&&(Nu.info(`Normal run: filtered out ${n.length} holdout test(s), running ${i.length} normal tests`),await this.memory.set(`test-execution:holdout-filtered:${Date.now()}`,{holdoutCount:n.length,holdoutFiles:n},{namespace:"test-execution",ttl:86400})),{testsToRun:i,holdoutCount:n.length})}catch(t){return Nu.warn("Holdout test partitioning failed (running all tests)",{error:t instanceof Error?t.message:String(t)}),{testsToRun:e,holdoutCount:0}}}async executeE2ETestCase(e){if(!this.e2eRunner)return m(new Error("E2E runner not available - Vibium client not configured"));try{await this.publishEvent("test-execution.E2ETestStarted",{testCaseId:e.id,testCaseName:e.name});let u=await this.e2eRunner.runTestCase(e);return await this.publishEvent("test-execution.E2ETestCompleted",{testCaseId:u.testCaseId,testCaseName:u.testCaseName,success:u.success,duration:u.totalDurationMs}),p(u)}catch(u){return m(g(u))}}async executeE2ETestSuite(e,u="sequential"){if(!this.e2eRunner)return m(new Error("E2E runner not available - Vibium client not configured"));try{await this.publishEvent("test-execution.E2ETestSuiteStarted",{suiteId:e.id,suiteName:e.name,testCount:e.testCases.length,strategy:u});let a=await this.e2eRunner.runTestSuite(e,u);return await this.publishEvent("test-execution.E2ETestSuiteCompleted",{suiteId:a.suiteId,suiteName:a.suiteName,success:a.success,passed:a.summary.passed,failed:a.summary.failed,total:a.summary.total,duration:a.summary.totalDurationMs}),p(a)}catch(a){return m(g(a))}}optimizeTestSuite(e,u){return Jc().optimize(e,u?.coverageThreshold)}async verifyFlakyTestDetection(e,u){let a=O({id:A(),type:"flaky-test-detection",confidence:u,description:`Verify flaky test classification: ${e.testId} (failure rate: ${(e.failureRate*100).toFixed(1)}%)`,payload:e,detectedBy:"test-execution-coordinator",severity:e.failureRate>.5?"high":"medium"});if(this.consensusMixin.requiresConsensus(a)){let t=await this.consensusMixin.verifyFinding(a);return t.success&&t.value.verdict==="verified"?(Nu.info(`Flaky test '${e.testId}' classification verified by consensus`),!0):(Nu.warn(`Flaky test '${e.testId}' classification NOT verified: ${t.success?t.value.verdict:t.error.message}`),!1)}return!0}async verifyRetryStrategy(e,u){let a=O({id:A(),type:"retry-strategy",confidence:u,description:`Verify retry strategy: ${e.testCount} tests with ${e.maxRetries} max retries (${e.backoffType})`,payload:e,detectedBy:"test-execution-coordinator",severity:e.testCount>10?"high":"medium"});if(this.consensusMixin.requiresConsensus(a)){let t=await this.consensusMixin.verifyFinding(a);return t.success&&t.value.verdict==="verified"?(Nu.info("Retry strategy verified by consensus"),!0):(Nu.warn(`Retry strategy NOT verified: ${t.success?t.value.verdict:t.error.message}`),!1)}return!0}async verifyTestFailureAnalysis(e,u){let a=O({id:A(),type:"test-failure-analysis",confidence:u,description:`Verify failure analysis for ${e.testId}: ${e.failureType} - ${e.rootCause}`,payload:e,detectedBy:"test-execution-coordinator",severity:"high"});if(this.consensusMixin.requiresConsensus(a)){let t=await this.consensusMixin.verifyFinding(a);return t.success&&t.value.verdict==="verified"?(Nu.info(`Failure analysis for '${e.testId}' verified by consensus`),!0):(Nu.warn(`Failure analysis NOT verified: ${t.success?t.value.verdict:t.error.message}`),!1)}return!0}};function Uc(s,e,u){return new Vs(s,e,u)}var Ihu=null;function Zc(){return Ihu}var Os=class extends U{coordinator=null;constructor(e,u){super(e,u)}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 e=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));if(e.testFiles&&Array.isArray(e.testFiles)){let u={testFiles:e.testFiles,parallel:e.parallel,retryCount:e.retryCount,timeout:e.timeout,workers:e.workers};return this.coordinator.runTests(u)}else if(e.framework){let u={testFiles:e.testFiles||[],framework:e.framework,timeout:e.timeout,env:e.env,reporters:e.reporters};return this.coordinator.execute(u)}return m(new Error("Invalid execute-tests payload: missing testFiles or framework"))}],["detect-flaky",async e=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let u=e.testFiles,a=e.runs,t=e.threshold;return u?this.coordinator.detectFlaky({testFiles:u,runs:a??5,threshold:t??.1}):m(new Error("Invalid detect-flaky payload: missing testFiles"))}],["retry-tests",async e=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let u=e.runId,a=e.failedTests,t=e.maxRetries;return!u||!a?m(new Error("Invalid retry-tests payload: missing runId or failedTests")):this.coordinator.retry({runId:u,failedTests:a,maxRetries:t??3,backoff:e.backoff})}]])}async onInitialize(){let e=Zc()??void 0;this.coordinator=Uc(this.eventBus,this.memory,{infraHealing:e}),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(e){switch(e.type){case"test-generation.TestSuiteCreated":await this.handleTestSuiteCreated(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGapDetected(e);break}}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestSuiteCreated",e=>this.handleEvent(e)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",e=>this.handleEvent(e)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",e=>this.handleEvent(e))}async handleTestSuiteCreated(e){let u=e.payload;this.updateHealth({lastActivity:new Date}),await this.memory.set(`suite-event:${u.suiteId}`,{eventId:e.id,timestamp:e.timestamp,sourceFiles:u.sourceFiles},{namespace:"test-execution",ttl:864e5})}async handleQualityGateEvaluated(e){let u=e.payload;u.passed||await this.memory.set(`quality-context:${u.gateId}`,{requiresRetry:!0,failedChecks:u.checks.filter(a=>!a.passed).map(a=>a.name)},{namespace:"test-execution",ttl:36e5}),this.updateHealth({lastActivity:new Date})}async handleCoverageGapDetected(e){let u=e.payload;u.riskScore>.7&&await this.memory.set(`coverage-gap:${u.gapId}`,{file:u.file,uncoveredLines:u.uncoveredLines,priority:"high"},{namespace:"test-execution",persist:!0}),this.updateHealth({lastActivity:new Date})}};function Qc(s,e){return new Os(s,e)}N();S();N();S();J();var Khu={defaultThreshold:80,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},Yc=B.create("coverage-analysis/coverage-analyzer"),ve=class s{static DEFAULT_THRESHOLD=80;static VECTOR_DIMENSION=384;memory;config;llmRouter;constructor(e,u={}){this.config={...Khu,...u},this.isMemoryBackend(e)?(this.memory=e,this.llmRouter=void 0):(this.memory=e.memory,this.llmRouter=e.llmRouter)}isMemoryBackend(e){return typeof e.get=="function"&&typeof e.set=="function"&&!("memory"in e)}async analyze(e){try{let{coverageData:u,threshold:a=this.config.defaultThreshold}=e,t=this.calculateMetrics(u),i=this.calculateOverallCoverage(t)>=a,n=await this.calculateDelta(t),o=this.generateRecommendations(u,t,a);return await this.storeCoverageSnapshot(t),e.includeFileDetails&&(await this.indexFileCoverageVectors(u.files),await this.storeFileCoverageKV(u.files)),p({summary:t,meetsThreshold:i,delta:n,recommendations:o})}catch(u){return m(g(u))}}async findGaps(e,u=this.config.defaultThreshold){try{let a=[],t=0;for(let i of e.files)if(this.calculateFileCoveragePercentage(i)<u){let o=this.calculateFileRiskScore(i),l=this.riskScoreToSeverity(o),c=await this.findSimilarGapPatterns(i);a.push({id:this.generateGapId(i.path),file:i.path,lines:i.uncoveredLines,branches:i.uncoveredBranches,riskScore:o,severity:l,recommendation:this.generateGapRecommendation(i,c)}),t+=i.uncoveredLines.length}a.sort((i,n)=>n.riskScore-i.riskScore);let r=this.estimateEffort(t);return p({gaps:a,totalUncoveredLines:t,estimatedEffort:r})}catch(a){return m(g(a))}}calculateMetrics(e){let u=e.files;if(u.length===0)return{line:0,branch:0,function:0,statement:0,files:0};let a=0,t=0,r=0,i=0,n=0,o=0,l=0,c=0;for(let E of u)a+=E.lines.total,t+=E.lines.covered,r+=E.branches.total,i+=E.branches.covered,n+=E.functions.total,o+=E.functions.covered,l+=E.statements.total,c+=E.statements.covered;return{line:a>0?t/a*100:0,branch:r>0?i/r*100:0,function:n>0?o/n*100:0,statement:l>0?c/l*100:0,files:u.length}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){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(e,u){if(!this.llmRouter)return this.getDefaultInsights();try{let a=this.buildCoverageAnalysisPrompt(e,u),t=this.getModelForTier(this.config.llmModelTier??2),r=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.
2424
2424
 
2425
2425
  Your response MUST be valid JSON with this exact structure:
2426
2426
  {
@@ -2462,7 +2462,7 @@ ${t}
2462
2462
  `,a+=`2. Suggest specific test cases to cover the gaps, with effort estimates
2463
2463
  `,a+=`3. Assess the risk of leaving this code uncovered
2464
2464
  `,a+=`4. Provide actionable recommendations prioritized by impact
2465
- `,a}parseInsightsResponse(e){try{let u=e,a=e.match(/```(?:json)?\n?([\s\S]*?)```/);a&&(u=a[1].trim());let t=T(u);return{uncoveredReasoning:Array.isArray(t.uncoveredReasoning)?t.uncoveredReasoning:[],suggestedTestCases:Array.isArray(t.suggestedTestCases)?t.suggestedTestCases.map(this.normalizeTestCase):[],riskAssessment:this.normalizeRiskAssessment(t.riskAssessment)}}catch{return Yc.warn("Failed to parse LLM response as JSON"),this.getDefaultInsights()}}normalizeTestCase(e){return{name:e.name||"Unnamed test",description:e.description||"No description provided",type:["unit","integration","edge-case"].includes(e.type)?e.type:"unit",targetLines:Array.isArray(e.targetLines)?e.targetLines:[],estimatedEffort:["low","medium","high"].includes(e.estimatedEffort)?e.estimatedEffort:"medium"}}normalizeRiskAssessment(e){return e?{overallRisk:["low","medium","high","critical"].includes(e.overallRisk)?e.overallRisk:"medium",riskFactors:Array.isArray(e.riskFactors)?e.riskFactors:[],businessImpact:e.businessImpact||"Unknown",recommendations:Array.isArray(e.recommendations)?e.recommendations:[]}:{overallRisk:"medium",riskFactors:["Unable to determine specific risk factors"],businessImpact:"Unknown - manual review recommended",recommendations:["Review uncovered code paths manually"]}}getDefaultInsights(){return{uncoveredReasoning:["LLM analysis not available - using rule-based analysis","Consider enabling LLM analysis for deeper insights"],suggestedTestCases:[],riskAssessment:{overallRisk:"medium",riskFactors:["Unable to perform automated risk analysis"],businessImpact:"Unknown - manual review recommended",recommendations:["Enable LLM analysis for intelligent gap detection","Review high-risk files manually","Prioritize branch coverage for conditional logic"]}}}calculateOverallCoverage(e){return(e.line+e.branch+e.function+e.statement)/4}calculateFileCoveragePercentage(e){let u=[e.lines.total>0?e.lines.covered/e.lines.total*100:100,e.branches.total>0?e.branches.covered/e.branches.total*100:100,e.functions.total>0?e.functions.covered/e.functions.total*100:100,e.statements.total>0?e.statements.covered/e.statements.total*100:100];return u.reduce((a,t)=>a+t,0)/u.length}calculateFileRiskScore(e){let u=e.lines.total>0?1-e.lines.covered/e.lines.total:0,a=e.branches.total>0?1-e.branches.covered/e.branches.total:0,t=e.functions.total>0?1-e.functions.covered/e.functions.total:0,r=u*.3+a*.4+t*.3;return Math.min(1,Math.max(0,r))}riskScoreToSeverity(e){return e>=.8?"critical":e>=.6?"high":e>=.3?"medium":"low"}async calculateDelta(e){try{let u=await this.memory.get("coverage:latest");if(!u)return;let a=e.line-u.line,t=e.branch-u.branch,r=e.function-u.function,i=e.statement-u.statement,n=(a+t+r+i)/4,o;return n>.5?o="improving":n<-.5?o="declining":o="stable",{line:a,branch:t,function:r,statement:i,trend:o}}catch{return}}async storeCoverageSnapshot(e){try{let u=await this.memory.get("coverage:latest");u&&await this.memory.set("coverage:previous",u,{persist:!0}),await this.memory.set("coverage:latest",e,{persist:!0});let a=Date.now();await this.memory.set(`coverage:history:${a}`,e,{persist:!0,namespace:"coverage-history"})}catch{}}async storeFileCoverageKV(e){for(let u of e)try{let a=u.lines.total>0?Math.round(u.lines.covered/u.lines.total*1e4)/100:0,t=u.branches.total>0?Math.round(u.branches.covered/u.branches.total*1e4)/100:0,r=u.functions.total>0?Math.round(u.functions.covered/u.functions.total*1e4)/100:0,i=u.statements.total>0?Math.round(u.statements.covered/u.statements.total*1e4)/100:0;await this.memory.set(`coverage:file:${u.path}`,{line:a,branch:t,function:r,statement:i},{persist:!0})}catch{}}async indexFileCoverageVectors(e){for(let u of e)try{let a=this.createCoverageEmbedding(u);await this.memory.storeVector(`coverage:file:${u.path}`,a,{path:u.path,lineCoverage:u.lines.covered/(u.lines.total||1),branchCoverage:u.branches.covered/(u.branches.total||1),uncoveredLineCount:u.uncoveredLines.length})}catch{}}createCoverageEmbedding(e){let u=new Array(s.VECTOR_DIMENSION).fill(0);u[0]=e.lines.covered/(e.lines.total||1),u[1]=e.branches.covered/(e.branches.total||1),u[2]=e.functions.covered/(e.functions.total||1),u[3]=e.statements.covered/(e.statements.total||1);let a=e.uncoveredLines.length/(e.lines.total||1);u[4]=a,u[5]=Math.min(1,e.lines.total/1e3),u[6]=Math.min(1,e.branches.total/100),u[7]=Math.min(1,e.functions.total/50);for(let t=8;t<s.VECTOR_DIMENSION;t++)u[t]=Math.sin(t*a)*.5+.5;return u}async findSimilarGapPatterns(e){try{let u=this.createCoverageEmbedding(e);return await this.memory.vectorSearch(u,5)}catch{return[]}}generateRecommendations(e,u,a){let t=[],r=this.calculateOverallCoverage(u);if(r<a){let o=a-r;t.push(`Coverage is ${o.toFixed(1)}% below threshold. Focus on high-risk files first.`)}u.branch<u.line-10&&t.push("Branch coverage is significantly lower than line coverage. Add tests for conditional logic."),u.function<70&&t.push("Function coverage is below 70%. Ensure all exported functions have tests.");let i=e.files.filter(o=>o.lines.covered===0&&o.lines.total>0);i.length>0&&t.push(`${i.length} file(s) have no test coverage. Prioritize adding tests for these files.`);let n=e.files.filter(o=>o.uncoveredLines.length>50);return n.length>0&&t.push(`${n.length} file(s) have more than 50 uncovered lines. Consider breaking them into smaller, testable modules.`),t}generateGapRecommendation(e,u){let a=e.uncoveredLines.length,t=this.getLineRanges(e.uncoveredLines),r=`Add tests for ${a} uncovered lines`;return t.length<=3&&(r+=` (lines: ${t.join(", ")})`),e.uncoveredBranches.length>0&&(r+=`. Focus on ${e.uncoveredBranches.length} uncovered branches.`),u.length>0&&u[0].score>.8&&(r+=" Similar pattern found in codebase - consider reusing test strategies."),r}getLineRanges(e){if(e.length===0)return[];let u=[...e].sort((i,n)=>i-n),a=[],t=u[0],r=u[0];for(let i=1;i<=u.length;i++)i<u.length&&u[i]===r+1?r=u[i]:(a.push(t===r?`${t}`:`${t}-${r}`),i<u.length&&(t=u[i],r=u[i]));return a}generateGapId(e){let u=e.split("").reduce((a,t)=>{let r=t.charCodeAt(0);return(a<<5)-a+r|0},0);return`gap-${Math.abs(u).toString(16)}`}estimateEffort(e){let u=e*12,a=1/20;return Math.ceil(u*a)}};N();S();J();var Xc={minCoverage:80,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},jhu=B.create("coverage-analysis/gap-detector"),f0=class s{static DEFAULT_MIN_COVERAGE=80;static VECTOR_DIMENSION=384;memory;config;llmRouter;constructor(e,u){"memory"in e?(this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...Xc,...u}):(this.memory=e,this.llmRouter=void 0,this.config={...Xc})}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async analyzeGapsWithLLM(e,u){if(!this.llmRouter)return m(new Error("LLM router not available"));if(e.length===0)return p({prioritizedGaps:[],suggestedTests:[],effortEstimate:{totalHours:0,confidence:1,breakdown:{}},summary:"No coverage gaps to analyze."});try{let a=this.buildGapAnalysisPrompt(e,u),t=this.getModelForTier(this.config.llmModelTier??2),r=await this.llmRouter.chat({messages:[{role:"system",content:`You are a senior QE engineer analyzing coverage gaps. Provide:
2465
+ `,a}parseInsightsResponse(e){try{let u=e,a=e.match(/```(?:json)?\n?([\s\S]*?)```/);a&&(u=a[1].trim());let t=T(u);return{uncoveredReasoning:Array.isArray(t.uncoveredReasoning)?t.uncoveredReasoning:[],suggestedTestCases:Array.isArray(t.suggestedTestCases)?t.suggestedTestCases.map(this.normalizeTestCase):[],riskAssessment:this.normalizeRiskAssessment(t.riskAssessment)}}catch{return Yc.warn("Failed to parse LLM response as JSON"),this.getDefaultInsights()}}normalizeTestCase(e){return{name:e.name||"Unnamed test",description:e.description||"No description provided",type:["unit","integration","edge-case"].includes(e.type)?e.type:"unit",targetLines:Array.isArray(e.targetLines)?e.targetLines:[],estimatedEffort:["low","medium","high"].includes(e.estimatedEffort)?e.estimatedEffort:"medium"}}normalizeRiskAssessment(e){return e?{overallRisk:["low","medium","high","critical"].includes(e.overallRisk)?e.overallRisk:"medium",riskFactors:Array.isArray(e.riskFactors)?e.riskFactors:[],businessImpact:e.businessImpact||"Unknown",recommendations:Array.isArray(e.recommendations)?e.recommendations:[]}:{overallRisk:"medium",riskFactors:["Unable to determine specific risk factors"],businessImpact:"Unknown - manual review recommended",recommendations:["Review uncovered code paths manually"]}}getDefaultInsights(){return{uncoveredReasoning:["LLM analysis not available - using rule-based analysis","Consider enabling LLM analysis for deeper insights"],suggestedTestCases:[],riskAssessment:{overallRisk:"medium",riskFactors:["Unable to perform automated risk analysis"],businessImpact:"Unknown - manual review recommended",recommendations:["Enable LLM analysis for intelligent gap detection","Review high-risk files manually","Prioritize branch coverage for conditional logic"]}}}calculateOverallCoverage(e){return(e.line+e.branch+e.function+e.statement)/4}calculateFileCoveragePercentage(e){let u=[e.lines.total>0?e.lines.covered/e.lines.total*100:100,e.branches.total>0?e.branches.covered/e.branches.total*100:100,e.functions.total>0?e.functions.covered/e.functions.total*100:100,e.statements.total>0?e.statements.covered/e.statements.total*100:100];return u.reduce((a,t)=>a+t,0)/u.length}calculateFileRiskScore(e){let u=e.lines.total>0?1-e.lines.covered/e.lines.total:0,a=e.branches.total>0?1-e.branches.covered/e.branches.total:0,t=e.functions.total>0?1-e.functions.covered/e.functions.total:0,r=u*.3+a*.4+t*.3;return Math.min(1,Math.max(0,r))}riskScoreToSeverity(e){return e>=.8?"critical":e>=.6?"high":e>=.3?"medium":"low"}async calculateDelta(e){try{let u=await this.memory.get("coverage:latest");if(!u)return;let a=e.line-u.line,t=e.branch-u.branch,r=e.function-u.function,i=e.statement-u.statement,n=(a+t+r+i)/4,o;return n>.5?o="improving":n<-.5?o="declining":o="stable",{line:a,branch:t,function:r,statement:i,trend:o}}catch{return}}async storeCoverageSnapshot(e){try{let u=await this.memory.get("coverage:latest");u&&await this.memory.set("coverage:previous",u,{persist:!0}),await this.memory.set("coverage:latest",e,{persist:!0});let a=Date.now();await this.memory.set(`coverage:history:${a}`,e,{persist:!0,namespace:"coverage-history"})}catch{}}async storeFileCoverageKV(e){for(let u of e)try{let a=u.lines.total>0?Math.round(u.lines.covered/u.lines.total*1e4)/100:0,t=u.branches.total>0?Math.round(u.branches.covered/u.branches.total*1e4)/100:0,r=u.functions.total>0?Math.round(u.functions.covered/u.functions.total*1e4)/100:0,i=u.statements.total>0?Math.round(u.statements.covered/u.statements.total*1e4)/100:0;await this.memory.set(`coverage:file:${u.path}`,{line:a,branch:t,function:r,statement:i},{persist:!0})}catch{}}async indexFileCoverageVectors(e){for(let u of e)try{let a=this.createCoverageEmbedding(u);await this.memory.storeVector(`coverage:file:${u.path}`,a,{path:u.path,lineCoverage:u.lines.covered/(u.lines.total||1),branchCoverage:u.branches.covered/(u.branches.total||1),uncoveredLineCount:u.uncoveredLines.length})}catch{}}createCoverageEmbedding(e){let u=new Array(s.VECTOR_DIMENSION).fill(0);u[0]=e.lines.covered/(e.lines.total||1),u[1]=e.branches.covered/(e.branches.total||1),u[2]=e.functions.covered/(e.functions.total||1),u[3]=e.statements.covered/(e.statements.total||1);let a=e.uncoveredLines.length/(e.lines.total||1);u[4]=a,u[5]=Math.min(1,e.lines.total/1e3),u[6]=Math.min(1,e.branches.total/100),u[7]=Math.min(1,e.functions.total/50);for(let t=8;t<s.VECTOR_DIMENSION;t++)u[t]=Math.sin(t*a)*.5+.5;return u}async findSimilarGapPatterns(e){try{let u=this.createCoverageEmbedding(e);return await this.memory.vectorSearch(u,5)}catch{return[]}}generateRecommendations(e,u,a){let t=[],r=this.calculateOverallCoverage(u);if(r<a){let o=a-r;t.push(`Coverage is ${o.toFixed(1)}% below threshold. Focus on high-risk files first.`)}u.branch<u.line-10&&t.push("Branch coverage is significantly lower than line coverage. Add tests for conditional logic."),u.function<70&&t.push("Function coverage is below 70%. Ensure all exported functions have tests.");let i=e.files.filter(o=>o.lines.covered===0&&o.lines.total>0);i.length>0&&t.push(`${i.length} file(s) have no test coverage. Prioritize adding tests for these files.`);let n=e.files.filter(o=>o.uncoveredLines.length>50);return n.length>0&&t.push(`${n.length} file(s) have more than 50 uncovered lines. Consider breaking them into smaller, testable modules.`),t}generateGapRecommendation(e,u){let a=e.uncoveredLines.length,t=this.getLineRanges(e.uncoveredLines),r=`Add tests for ${a} uncovered lines`;return t.length<=3&&(r+=` (lines: ${t.join(", ")})`),e.uncoveredBranches.length>0&&(r+=`. Focus on ${e.uncoveredBranches.length} uncovered branches.`),u.length>0&&u[0].score>.8&&(r+=" Similar pattern found in codebase - consider reusing test strategies."),r}getLineRanges(e){if(e.length===0)return[];let u=[...e].sort((i,n)=>i-n),a=[],t=u[0],r=u[0];for(let i=1;i<=u.length;i++)i<u.length&&u[i]===r+1?r=u[i]:(a.push(t===r?`${t}`:`${t}-${r}`),i<u.length&&(t=u[i],r=u[i]));return a}generateGapId(e){let u=e.split("").reduce((a,t)=>{let r=t.charCodeAt(0);return(a<<5)-a+r|0},0);return`gap-${Math.abs(u).toString(16)}`}estimateEffort(e){let u=e*12,a=1/20;return Math.ceil(u*a)}};N();S();J();var Xc={minCoverage:80,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},jhu=B.create("coverage-analysis/gap-detector"),f0=class s{static DEFAULT_MIN_COVERAGE=80;static VECTOR_DIMENSION=384;memory;config;llmRouter;constructor(e,u){"memory"in e?(this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...Xc,...u}):(this.memory=e,this.llmRouter=void 0,this.config={...Xc})}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){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 analyzeGapsWithLLM(e,u){if(!this.llmRouter)return m(new Error("LLM router not available"));if(e.length===0)return p({prioritizedGaps:[],suggestedTests:[],effortEstimate:{totalHours:0,confidence:1,breakdown:{}},summary:"No coverage gaps to analyze."});try{let a=this.buildGapAnalysisPrompt(e,u),t=this.getModelForTier(this.config.llmModelTier??2),r=await this.llmRouter.chat({messages:[{role:"system",content:`You are a senior QE engineer analyzing coverage gaps. Provide:
2466
2466
  1. Risk-weighted prioritization (which gaps are most dangerous)
2467
2467
  2. Business impact assessment for each gap
2468
2468
  3. Specific test cases to fill each gap
@@ -2621,7 +2621,7 @@ describe('${u} Integration', () => {
2621
2621
  `);if(d.length<20)continue;let D=this.hashString(d),h=i.get(D)||[];h.push({file:l,line:E+1}),i.set(D,h)}for(let[,l]of i.entries())l.length>1&&(r+=u*(l.length-1),n.push({lines:u,occurrences:l.length,locations:l.map(c=>({file:c.file,startLine:c.line,endLine:c.line+u-1}))}));let o=n.sort((l,c)=>c.occurrences-l.occurrences).slice(0,20);return{percentage:t>0?Math.round(r/t*100*10)/10:0,duplicates:o}}countLines(e){let u=0,a=0,t=0,r=!1;for(let i of e){let n=i.trim();if(n===""){t++;continue}if(r){a++,n.includes("*/")&&(r=!1);continue}n.startsWith("//")?a++:n.startsWith("/*")?(a++,n.includes("*/")||(r=!0)):(u++,(n.includes("//")||n.includes("/*"))&&a++)}return{codeLines:u,commentLines:a,blankLines:t}}calculateCyclomaticComplexity(e){let u=[/\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],a=1;for(let t of u){let r=e.match(t);r&&(a+=r.length)}return a}calculateCognitiveComplexity(e){let u=0,a=0,t=e.split(`
2622
2622
  `);for(let r of t){let i=r.trim();/\bif\s*\(/.test(i)&&(u+=1+a,a++),/\belse\s+if\s*\(/.test(i)&&(u+=1+a),/\belse\s*{/.test(i)&&(u+=1),/\bfor\s*\(/.test(i)&&(u+=1+a,a++),/\bwhile\s*\(/.test(i)&&(u+=1+a,a++),/\bswitch\s*\(/.test(i)&&(u+=1+a,a++),/\bcatch\s*\(/.test(i)&&(u+=1+a,a++),/\?\s*[^:]/.test(i)&&(u+=1+a),/&&|\|\|/.test(i)&&(u+=1);let n=(i.match(/{/g)||[]).length,o=(i.match(/}/g)||[]).length;a=Math.max(0,a+n-o)}return u}estimateCyclomaticComplexity(e){return this.calculateCyclomaticComplexity(e)}estimateCognitiveComplexity(e){return this.calculateCognitiveComplexity(e)}calculateNestingDepth(e,u){let t=e.split(`
2623
2623
  `).slice(u.startLine-1,u.endLine).join(`
2624
- `),r=0,i=0;for(let n of t)n==="{"?(i++,r=Math.max(r,i)):n==="}"&&(i=Math.max(0,i-1));return r}calculateHalsteadMetrics(e){let u=new Set,a=new Set,t=0,r=0,i=[/[+\-*/%]=?/g,/[<>]=?/g,/[!=]=?=?/g,/&&|\|\|/g,/\+\+|--/g,/\./g,/,/g,/:/g,/\?/g,/=>/g];for(let R of i){let w=e.match(R);if(w)for(let P of w)u.add(P),t++}let n=/\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"]),l=e.match(n);if(l)for(let R of l)o.has(R)||(a.add(R),r++);let c=u.size,E=a.size,d=t,D=r,h=c+E,C=d+D,y=C>0&&h>0?C*Math.log2(h):0,x=E>0?c/2*(D/E):0,b=y*x;return{vocabulary:h,length:C,volume:Math.round(y*100)/100,difficulty:Math.round(x*100)/100,effort:Math.round(b*100)/100}}calculateMaintainabilityIndex(e,u,a){if(a<=0||e<=0)return 100;let t=Math.log(e),r=Math.log(a),i=171-5.2*t-.23*u-16.2*r,n=Math.max(0,Math.min(100,i*100/171));return Math.round(n*100)/100}hashString(e){let u=0;for(let a=0;a<e.length;a++){let t=e.charCodeAt(a);u=(u<<5)-u+t,u=u&u}return u.toString(16)}},$s=null;function qs(){return $s||($s=new Lr),$s}import*as ne from"os";var Nr=class{lastCpuUsage=null;lastCpuTime=0;metricHistory=new Map;maxHistorySize;constructor(e=1e3){this.maxHistorySize=e}collectSystemMetrics(){let e=this.collectCpuMetrics(),u=this.collectMemoryMetrics(),a=this.collectProcessMetrics(),t={timestamp:new Date,cpu:e,memory:u,process:a};return this.recordMetric("cpu_usage",e.usage),this.recordMetric("memory_usage",u.usage),this.recordMetric("process_cpu_usage",a.cpuUsage),this.recordMetric("process_memory_usage",a.memoryUsage),t}collectCpuMetrics(){let e=ne.cpus(),u=ne.loadavg(),a=0,t=0;for(let i of e){for(let n of Object.keys(i.times))t+=i.times[n];a+=i.times.idle}let r=t>0?(t-a)/t*100:0;return{usage:Math.round(r*100)/100,loadAverage:u,cores:e.length}}collectMemoryMetrics(){let e=ne.totalmem(),u=ne.freemem(),a=e-u,t=a/e*100;return{usage:Math.round(t*100)/100,total:e,free:u,used:a}}collectProcessMetrics(){let e=process.memoryUsage(),u=process.cpuUsage(this.lastCpuUsage??void 0),a=Date.now(),r=(this.lastCpuTime>0?a-this.lastCpuTime:1e3)*1e3,n=(u.user+u.system)/r*100;this.lastCpuUsage=u,this.lastCpuTime=a;let o=ne.totalmem(),l=e.rss/o*100;return{cpuUsage:Math.min(100,Math.round(n*100)/100),memoryUsage:Math.round(l*100)/100,heapUsed:e.heapUsed,heapTotal:e.heapTotal,rss:e.rss,uptime:process.uptime()}}getMetricValue(e){let u=this.collectSystemMetrics();switch(e){case"cpu_usage":return u.cpu.usage;case"memory_usage":return u.memory.usage;case"process_cpu_usage":return u.process.cpuUsage;case"process_memory_usage":return u.process.memoryUsage;case"heap_used":return u.process.heapUsed;case"heap_total":return u.process.heapTotal;case"rss":return u.process.rss;case"load_average_1m":return u.cpu.loadAverage[0];case"load_average_5m":return u.cpu.loadAverage[1];case"load_average_15m":return u.cpu.loadAverage[2];default:let a=this.metricHistory.get(e);return a&&a.length>0?a[a.length-1].value:0}}getChaosMetricValue(e){let a={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)}[e];return a?a():this.getMetricValue(e)}recordMetric(e,u,a){let t={name:e,value:u,timestamp:new Date,labels:a},r=this.metricHistory.get(e)||[];r.push(t),r.length>this.maxHistorySize&&r.shift(),this.metricHistory.set(e,r)}recordHttpMetrics(e){this.recordMetric("response_time_ms",e.responseTimeMs),this.recordMetric("http_status",e.statusCode),this.recordMetric("http_success",e.success?1:0)}getMetricHistory(e,u){let a=this.metricHistory.get(e)||[];return u&&a.length>u?a.slice(-u):[...a]}getMetricAverage(e,u=10){let a=this.getMetricHistory(e,u);return a.length===0?0:a.reduce((r,i)=>r+i.value,0)/a.length}getResponseTimeEstimate(){let e=this.collectSystemMetrics().cpu,u=50,a=1+e.usage/100;return Math.round(u*a)}getErrorRateEstimate(){let e=this.getMetricHistory("http_success",100);return e.length===0?0:e.filter(a=>a.value===0).length/e.length}getThroughputEstimate(){let e=this.getMetricHistory("response_time_ms",100);if(e.length<2)return 1e3;let u=e[0].timestamp.getTime(),t=(e[e.length-1].timestamp.getTime()-u)/1e3;return t<=0?1e3:Math.round(e.length/t)}getLatencyPercentile(e){let u=this.getMetricHistory("response_time_ms",1e3);if(u.length===0)return 50;let a=u.map(r=>r.value).sort((r,i)=>r-i),t=Math.floor(e/100*a.length);return a[Math.min(t,a.length-1)]}clearHistory(){this.metricHistory.clear()}},Js=null;function Us(){return Js||(Js=new Nr),Js}S();J();var Qhu={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},Ir={A:90,B:80,C:70,D:50,E:0},u1=B.create("quality-assessment/quality-analyzer"),oe=class{config;metricsAnalyzer;memory;llmRouter;constructor(e,u={}){this.config={...Qhu,...u},this.metricsAnalyzer=qs(),"memory"in e?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0)}isLLMInsightsAvailable(){return this.config.enableLLMInsights===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async generateQualityInsightsWithLLM(e,u,a){if(!this.llmRouter)return null;try{let t=this.buildQualityInsightsPrompt(e,u,a),r=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software quality engineer. Analyze quality metrics and provide actionable insights.
2624
+ `),r=0,i=0;for(let n of t)n==="{"?(i++,r=Math.max(r,i)):n==="}"&&(i=Math.max(0,i-1));return r}calculateHalsteadMetrics(e){let u=new Set,a=new Set,t=0,r=0,i=[/[+\-*/%]=?/g,/[<>]=?/g,/[!=]=?=?/g,/&&|\|\|/g,/\+\+|--/g,/\./g,/,/g,/:/g,/\?/g,/=>/g];for(let R of i){let w=e.match(R);if(w)for(let P of w)u.add(P),t++}let n=/\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"]),l=e.match(n);if(l)for(let R of l)o.has(R)||(a.add(R),r++);let c=u.size,E=a.size,d=t,D=r,h=c+E,C=d+D,y=C>0&&h>0?C*Math.log2(h):0,x=E>0?c/2*(D/E):0,b=y*x;return{vocabulary:h,length:C,volume:Math.round(y*100)/100,difficulty:Math.round(x*100)/100,effort:Math.round(b*100)/100}}calculateMaintainabilityIndex(e,u,a){if(a<=0||e<=0)return 100;let t=Math.log(e),r=Math.log(a),i=171-5.2*t-.23*u-16.2*r,n=Math.max(0,Math.min(100,i*100/171));return Math.round(n*100)/100}hashString(e){let u=0;for(let a=0;a<e.length;a++){let t=e.charCodeAt(a);u=(u<<5)-u+t,u=u&u}return u.toString(16)}},$s=null;function qs(){return $s||($s=new Lr),$s}import*as ne from"os";var Nr=class{lastCpuUsage=null;lastCpuTime=0;metricHistory=new Map;maxHistorySize;constructor(e=1e3){this.maxHistorySize=e}collectSystemMetrics(){let e=this.collectCpuMetrics(),u=this.collectMemoryMetrics(),a=this.collectProcessMetrics(),t={timestamp:new Date,cpu:e,memory:u,process:a};return this.recordMetric("cpu_usage",e.usage),this.recordMetric("memory_usage",u.usage),this.recordMetric("process_cpu_usage",a.cpuUsage),this.recordMetric("process_memory_usage",a.memoryUsage),t}collectCpuMetrics(){let e=ne.cpus(),u=ne.loadavg(),a=0,t=0;for(let i of e){for(let n of Object.keys(i.times))t+=i.times[n];a+=i.times.idle}let r=t>0?(t-a)/t*100:0;return{usage:Math.round(r*100)/100,loadAverage:u,cores:e.length}}collectMemoryMetrics(){let e=ne.totalmem(),u=ne.freemem(),a=e-u,t=a/e*100;return{usage:Math.round(t*100)/100,total:e,free:u,used:a}}collectProcessMetrics(){let e=process.memoryUsage(),u=process.cpuUsage(this.lastCpuUsage??void 0),a=Date.now(),r=(this.lastCpuTime>0?a-this.lastCpuTime:1e3)*1e3,n=(u.user+u.system)/r*100;this.lastCpuUsage=u,this.lastCpuTime=a;let o=ne.totalmem(),l=e.rss/o*100;return{cpuUsage:Math.min(100,Math.round(n*100)/100),memoryUsage:Math.round(l*100)/100,heapUsed:e.heapUsed,heapTotal:e.heapTotal,rss:e.rss,uptime:process.uptime()}}getMetricValue(e){let u=this.collectSystemMetrics();switch(e){case"cpu_usage":return u.cpu.usage;case"memory_usage":return u.memory.usage;case"process_cpu_usage":return u.process.cpuUsage;case"process_memory_usage":return u.process.memoryUsage;case"heap_used":return u.process.heapUsed;case"heap_total":return u.process.heapTotal;case"rss":return u.process.rss;case"load_average_1m":return u.cpu.loadAverage[0];case"load_average_5m":return u.cpu.loadAverage[1];case"load_average_15m":return u.cpu.loadAverage[2];default:let a=this.metricHistory.get(e);return a&&a.length>0?a[a.length-1].value:0}}getChaosMetricValue(e){let a={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)}[e];return a?a():this.getMetricValue(e)}recordMetric(e,u,a){let t={name:e,value:u,timestamp:new Date,labels:a},r=this.metricHistory.get(e)||[];r.push(t),r.length>this.maxHistorySize&&r.shift(),this.metricHistory.set(e,r)}recordHttpMetrics(e){this.recordMetric("response_time_ms",e.responseTimeMs),this.recordMetric("http_status",e.statusCode),this.recordMetric("http_success",e.success?1:0)}getMetricHistory(e,u){let a=this.metricHistory.get(e)||[];return u&&a.length>u?a.slice(-u):[...a]}getMetricAverage(e,u=10){let a=this.getMetricHistory(e,u);return a.length===0?0:a.reduce((r,i)=>r+i.value,0)/a.length}getResponseTimeEstimate(){let e=this.collectSystemMetrics().cpu,u=50,a=1+e.usage/100;return Math.round(u*a)}getErrorRateEstimate(){let e=this.getMetricHistory("http_success",100);return e.length===0?0:e.filter(a=>a.value===0).length/e.length}getThroughputEstimate(){let e=this.getMetricHistory("response_time_ms",100);if(e.length<2)return 1e3;let u=e[0].timestamp.getTime(),t=(e[e.length-1].timestamp.getTime()-u)/1e3;return t<=0?1e3:Math.round(e.length/t)}getLatencyPercentile(e){let u=this.getMetricHistory("response_time_ms",1e3);if(u.length===0)return 50;let a=u.map(r=>r.value).sort((r,i)=>r-i),t=Math.floor(e/100*a.length);return a[Math.min(t,a.length-1)]}clearHistory(){this.metricHistory.clear()}},Js=null;function Us(){return Js||(Js=new Nr),Js}S();J();var Qhu={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},Ir={A:90,B:80,C:70,D:50,E:0},u1=B.create("quality-assessment/quality-analyzer"),oe=class{config;metricsAnalyzer;memory;llmRouter;constructor(e,u={}){this.config={...Qhu,...u},this.metricsAnalyzer=qs(),"memory"in e?(this.memory=e.memory,this.llmRouter=e.llmRouter):(this.memory=e,this.llmRouter=void 0)}isLLMInsightsAvailable(){return this.config.enableLLMInsights===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){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(e,u,a){if(!this.llmRouter)return null;try{let t=this.buildQualityInsightsPrompt(e,u,a),r=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software quality engineer. Analyze quality metrics and provide actionable insights.
2625
2625
 
2626
2626
  Your response MUST be valid JSON with this exact structure:
2627
2627
  {
@@ -2667,7 +2667,7 @@ ${a.slice(0,2e3)}
2667
2667
  `,t+=`2. Prioritized recommendations for improvement (most impactful first)
2668
2668
  `,t+=`3. Estimated impact on quality score if recommendations are followed
2669
2669
  `,t+=`4. A brief summary of key findings
2670
- `,t}parseQualityInsightsResponse(e){try{let u=e.match(/\{[\s\S]*\}/);if(u){let a=T(u[0]);if(typeof a.explanation=="string"&&Array.isArray(a.prioritizedRecommendations)&&typeof a.estimatedImpactOnScore=="number"&&typeof a.keySummary=="string")return{explanation:a.explanation,prioritizedRecommendations:a.prioritizedRecommendations.map((t,r)=>({priority:t.priority??r+1,title:t.title??"Recommendation",description:t.description??"",estimatedImpact:this.normalizeImpact(t.estimatedImpact),estimatedEffort:this.normalizeEffort(t.estimatedEffort)})),estimatedImpactOnScore:a.estimatedImpactOnScore,keySummary:a.keySummary}}return null}catch{return u1.warn("Failed to parse LLM insights response:"),null}}normalizeImpact(e){let u=e?.toLowerCase();return u==="high"||u==="medium"||u==="low"?u:"medium"}normalizeEffort(e){let u=e?.toLowerCase();return u==="high"||u==="medium"||u==="low"?u:"medium"}async analyzeQuality(e){try{let{sourceFiles:u,includeMetrics:a,compareBaseline:t}=e;if(u.length===0)return m(new Error("No source files provided for analysis"));let r=await this.collectFileMetrics(u,a),i=this.aggregateMetrics(r),n=this.calculateQualityScore(i),o=this.config.enableTrendAnalysis?await this.generateTrends(i,t):[],l=this.generateRecommendations(i,n),c;if(this.isLLMInsightsAvailable()){let d=await this.generateQualityInsightsWithLLM(i,n);d&&(c=d)}let E={score:n,metrics:i,trends:o,recommendations:l,llmInsights:c};return await this.storeReport(E,u),p(E)}catch(u){return m(g(u))}}async analyzeComplexity(e){try{let{sourceFiles:u,metrics:a}=e;if(u.length===0)return m(new Error("No source files provided for complexity analysis"));let t=[];for(let o of u){let l=await this.analyzeFileComplexity(o,a);t.push(l)}let r=this.calculateComplexitySummary(t),i=this.identifyHotspots(t),n={files:t,summary:r,hotspots:i};return await this.storeComplexityReport(n),p(n)}catch(u){return m(g(u))}}async getQualityTrend(e,u){try{let a=new Date;a.setDate(a.getDate()-u);let t=await this.memory.search("quality-analysis:report:*",u*10),r=[];for(let n of t){let o=await this.memory.get(n);if(o){let l=new Date(o.analyzedAt);if(l>=a){let c=o.metrics.find(E=>E.name===e);c&&r.push({date:l,value:c.value})}}}r.sort((n,o)=>n.date.getTime()-o.date.getTime());let i=this.calculateTrendDirection(r);return p({metric:e,dataPoints:r,direction:i})}catch(a){return m(g(a))}}async collectFileMetrics(e,u){let a=new Map,t=u.length===0,r=0;if(t||u.includes("duplication"))try{r=(await this.metricsAnalyzer.detectDuplication(e)).percentage}catch{r=0}for(let i of e){let n={},o=await this.metricsAnalyzer.analyzeFile(i);if(o){if((t||u.includes("complexity"))&&(n.complexity=o.cyclomaticComplexity),(t||u.includes("maintainability"))&&(n.maintainability=o.maintainabilityIndex),(t||u.includes("duplication"))&&(n.duplication=r),t||u.includes("testability")){let l=Math.max(0,100-o.cyclomaticComplexity*3),c=o.maintainabilityIndex;n.testability=Math.round((l*.4+c*.6)*100)/100}if(t||u.includes("coverage")){let l=await this.getStoredCoverage(i);l!==null&&(n.coverage=l)}}else{if(t||u.includes("coverage")){let l=await this.getStoredCoverage(i);l!==null&&(n.coverage=l)}(t||u.includes("complexity"))&&(n.complexity=10),(t||u.includes("maintainability"))&&(n.maintainability=70),(t||u.includes("duplication"))&&(n.duplication=r),(t||u.includes("testability"))&&(n.testability=70)}a.set(i,n)}return a}async getStoredCoverage(e){try{let u=await this.memory.get(`coverage:file:${e}`);if(u&&typeof u.line=="number")return u.line;let a=await this.memory.get("coverage:latest");return a&&typeof a.line=="number"?a.line:null}catch{return null}}aggregateMetrics(e){let u=new Map;for(let t of e.values())for(let[r,i]of Object.entries(t)){let n=u.get(r)||[];n.push(i),u.set(r,n)}let a=[];for(let[t,r]of u.entries()){let i=r.reduce((l,c)=>l+c,0)/r.length,n=this.getMetricRating(i,t),o=this.estimateTrend(r);a.push({name:t,value:Math.round(i*100)/100,rating:n,trend:o})}return a}calculateQualityScore(e){let u={coverage:.25,complexity:.2,maintainability:.25,duplication:.15,testability:.15},a=0,t=0;for(let n of e){let o=u[n.name]||.1,l=n.name==="complexity"||n.name==="duplication"?Math.max(0,100-n.value*2):n.value;a+=l*o,t+=o}let r=t>0?Math.round(a/t):0,i=e.find(n=>n.name==="coverage");return{overall:r,coverage:i?i.value:-1,complexity:e.find(n=>n.name==="complexity")?.value||0,maintainability:e.find(n=>n.name==="maintainability")?.value||0,security:85}}async generateTrends(e,u){let a=[];for(let t of e){let r=await this.getQualityTrend(t.name,30);r.success?a.push(r.value):a.push({metric:t.name,dataPoints:[{date:new Date,value:t.value}],direction:"stable"})}return a}generateRecommendations(e,u){let a=[],t=e.find(o=>o.name==="coverage");t&&t.value<80&&a.push({type:t.value<60?"critical":"improvement",title:"Increase Test Coverage",description:`Current coverage is ${t.value}%. Aim for at least 80% coverage to ensure code reliability.`,impact:"high",effort:t.value<60?"high":"medium"});let r=e.find(o=>o.name==="complexity");r&&r.value>this.config.complexityThresholds.cyclomatic.warning&&a.push({type:r.value>this.config.complexityThresholds.cyclomatic.critical?"critical":"warning",title:"Reduce Code Complexity",description:`Average cyclomatic complexity is ${r.value}. Consider refactoring complex functions.`,impact:"high",effort:"medium"});let i=e.find(o=>o.name==="maintainability");i&&i.value<this.config.complexityThresholds.maintainability.warning&&a.push({type:i.value<this.config.complexityThresholds.maintainability.critical?"critical":"warning",title:"Improve Maintainability",description:`Maintainability index is ${i.value}. Consider improving code structure and documentation.`,impact:"medium",effort:"medium"});let n=e.find(o=>o.name==="duplication");return n&&n.value>5&&a.push({type:n.value>10?"warning":"improvement",title:"Reduce Code Duplication",description:`${n.value}% of code is duplicated. Extract common patterns into reusable functions.`,impact:"medium",effort:"low"}),u.overall<70&&a.push({type:"critical",title:"Overall Quality Improvement Needed",description:`Overall quality score is ${u.overall}. Multiple areas need attention to bring code quality to acceptable levels.`,impact:"high",effort:"high"}),a.sort((o,l)=>{let c={critical:0,warning:1,improvement:2};return c[o.type]-c[l.type]})}async analyzeFileComplexity(e,u){let a=u.length===0,t=await this.metricsAnalyzer.analyzeFile(e);return t?{path:e,cyclomatic:a||u.includes("cyclomatic")?t.cyclomaticComplexity:0,cognitive:a||u.includes("cognitive")?t.cognitiveComplexity:0,maintainability:a||u.includes("maintainability")?t.maintainabilityIndex:0,linesOfCode:t.linesOfCode}:{path:e,cyclomatic:a||u.includes("cyclomatic")?5:0,cognitive:a||u.includes("cognitive")?8:0,maintainability:a||u.includes("maintainability")?70:0,linesOfCode:100}}calculateComplexitySummary(e){if(e.length===0)return{averageCyclomatic:0,averageCognitive:0,averageMaintainability:0,totalLinesOfCode:0};let u=e.reduce((i,n)=>i+n.cyclomatic,0),a=e.reduce((i,n)=>i+n.cognitive,0),t=e.reduce((i,n)=>i+n.maintainability,0),r=e.reduce((i,n)=>i+n.linesOfCode,0);return{averageCyclomatic:Math.round(u/e.length*100)/100,averageCognitive:Math.round(a/e.length*100)/100,averageMaintainability:Math.round(t/e.length*100)/100,totalLinesOfCode:r}}identifyHotspots(e){let u=[],a=this.config.complexityThresholds;for(let t of e)t.cyclomatic>=a.cyclomatic.warning&&u.push({file:t.path,function:"unknown",complexity:t.cyclomatic,recommendation:t.cyclomatic>=a.cyclomatic.critical?"Critical: Refactor this function immediately. Consider splitting into smaller functions.":"Consider refactoring to reduce complexity."}),t.cognitive>=a.cognitive.warning&&u.push({file:t.path,function:"unknown",complexity:t.cognitive,recommendation:t.cognitive>=a.cognitive.critical?"Critical: High cognitive complexity makes this code hard to understand and maintain.":"Simplify control flow and reduce nesting depth."}),t.maintainability<=a.maintainability.warning&&u.push({file:t.path,function:"unknown",complexity:100-t.maintainability,recommendation:t.maintainability<=a.maintainability.critical?"Critical: Very low maintainability. Consider a major refactoring effort.":"Improve code documentation and reduce complexity."});return u.sort((t,r)=>r.complexity-t.complexity).slice(0,10)}getMetricRating(e,u){let t=["complexity","duplication"].includes(u)?Math.max(0,100-e*2):e;return t>=Ir.A?"A":t>=Ir.B?"B":t>=Ir.C?"C":t>=Ir.D?"D":"E"}estimateTrend(e){if(e.length<2)return"stable";let u=e.slice(0,Math.floor(e.length/2)),a=e.slice(Math.floor(e.length/2)),t=u.reduce((o,l)=>o+l,0)/u.length,i=a.reduce((o,l)=>o+l,0)/a.length-t,n=t*.05;return i>n?"improving":i<-n?"declining":"stable"}calculateTrendDirection(e){if(e.length<this.config.trendDataPointsMin)return"stable";let u=e.map(t=>t.value);switch(this.estimateTrend(u)){case"improving":return"up";case"declining":return"down";default:return"stable"}}async storeReport(e,u){let a=A(),t=`quality-analysis:report:${a}`;await this.memory.set(t,{id:a,...e,sourceFiles:u,analyzedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400*90})}async storeComplexityReport(e){let u=A(),a=`quality-analysis:complexity:${u}`;await this.memory.set(a,{id:u,...e,analyzedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400*30})}};N();S();J();var Yhu={riskWeights:{coverage:.15,testsPassing:.2,criticalBugs:.25,codeSmells:.05,securityVulnerabilities:.25,technicalDebt:.05,duplications:.05},decisionThresholds:{approved:.3,warning:.6,blocked:.6},enableMLPrediction:!0,learningRate:.1,enableLLMAdvice:!0,llmModelTier:2},e1=B.create("quality-assessment/deployment-advisor"),$e=class{config;memory;llmRouter;constructor(e,u={}){this.config={...Yhu,...u},"memory"in e?(this.memory=e.memory,this.llmRouter=e.llmRouter):this.memory=e}isLLMAdviceAvailable(){return this.config.enableLLMAdvice&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async generateDeploymentAdviceWithLLM(e,u,a,t){if(!this.llmRouter)return{};try{let r=this.getModelForTier(this.config.llmModelTier),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are a senior DevOps/SRE engineer providing deployment advice.
2670
+ `,t}parseQualityInsightsResponse(e){try{let u=e.match(/\{[\s\S]*\}/);if(u){let a=T(u[0]);if(typeof a.explanation=="string"&&Array.isArray(a.prioritizedRecommendations)&&typeof a.estimatedImpactOnScore=="number"&&typeof a.keySummary=="string")return{explanation:a.explanation,prioritizedRecommendations:a.prioritizedRecommendations.map((t,r)=>({priority:t.priority??r+1,title:t.title??"Recommendation",description:t.description??"",estimatedImpact:this.normalizeImpact(t.estimatedImpact),estimatedEffort:this.normalizeEffort(t.estimatedEffort)})),estimatedImpactOnScore:a.estimatedImpactOnScore,keySummary:a.keySummary}}return null}catch{return u1.warn("Failed to parse LLM insights response:"),null}}normalizeImpact(e){let u=e?.toLowerCase();return u==="high"||u==="medium"||u==="low"?u:"medium"}normalizeEffort(e){let u=e?.toLowerCase();return u==="high"||u==="medium"||u==="low"?u:"medium"}async analyzeQuality(e){try{let{sourceFiles:u,includeMetrics:a,compareBaseline:t}=e;if(u.length===0)return m(new Error("No source files provided for analysis"));let r=await this.collectFileMetrics(u,a),i=this.aggregateMetrics(r),n=this.calculateQualityScore(i),o=this.config.enableTrendAnalysis?await this.generateTrends(i,t):[],l=this.generateRecommendations(i,n),c;if(this.isLLMInsightsAvailable()){let d=await this.generateQualityInsightsWithLLM(i,n);d&&(c=d)}let E={score:n,metrics:i,trends:o,recommendations:l,llmInsights:c};return await this.storeReport(E,u),p(E)}catch(u){return m(g(u))}}async analyzeComplexity(e){try{let{sourceFiles:u,metrics:a}=e;if(u.length===0)return m(new Error("No source files provided for complexity analysis"));let t=[];for(let o of u){let l=await this.analyzeFileComplexity(o,a);t.push(l)}let r=this.calculateComplexitySummary(t),i=this.identifyHotspots(t),n={files:t,summary:r,hotspots:i};return await this.storeComplexityReport(n),p(n)}catch(u){return m(g(u))}}async getQualityTrend(e,u){try{let a=new Date;a.setDate(a.getDate()-u);let t=await this.memory.search("quality-analysis:report:*",u*10),r=[];for(let n of t){let o=await this.memory.get(n);if(o){let l=new Date(o.analyzedAt);if(l>=a){let c=o.metrics.find(E=>E.name===e);c&&r.push({date:l,value:c.value})}}}r.sort((n,o)=>n.date.getTime()-o.date.getTime());let i=this.calculateTrendDirection(r);return p({metric:e,dataPoints:r,direction:i})}catch(a){return m(g(a))}}async collectFileMetrics(e,u){let a=new Map,t=u.length===0,r=0;if(t||u.includes("duplication"))try{r=(await this.metricsAnalyzer.detectDuplication(e)).percentage}catch{r=0}for(let i of e){let n={},o=await this.metricsAnalyzer.analyzeFile(i);if(o){if((t||u.includes("complexity"))&&(n.complexity=o.cyclomaticComplexity),(t||u.includes("maintainability"))&&(n.maintainability=o.maintainabilityIndex),(t||u.includes("duplication"))&&(n.duplication=r),t||u.includes("testability")){let l=Math.max(0,100-o.cyclomaticComplexity*3),c=o.maintainabilityIndex;n.testability=Math.round((l*.4+c*.6)*100)/100}if(t||u.includes("coverage")){let l=await this.getStoredCoverage(i);l!==null&&(n.coverage=l)}}else{if(t||u.includes("coverage")){let l=await this.getStoredCoverage(i);l!==null&&(n.coverage=l)}(t||u.includes("complexity"))&&(n.complexity=10),(t||u.includes("maintainability"))&&(n.maintainability=70),(t||u.includes("duplication"))&&(n.duplication=r),(t||u.includes("testability"))&&(n.testability=70)}a.set(i,n)}return a}async getStoredCoverage(e){try{let u=await this.memory.get(`coverage:file:${e}`);if(u&&typeof u.line=="number")return u.line;let a=await this.memory.get("coverage:latest");return a&&typeof a.line=="number"?a.line:null}catch{return null}}aggregateMetrics(e){let u=new Map;for(let t of e.values())for(let[r,i]of Object.entries(t)){let n=u.get(r)||[];n.push(i),u.set(r,n)}let a=[];for(let[t,r]of u.entries()){let i=r.reduce((l,c)=>l+c,0)/r.length,n=this.getMetricRating(i,t),o=this.estimateTrend(r);a.push({name:t,value:Math.round(i*100)/100,rating:n,trend:o})}return a}calculateQualityScore(e){let u={coverage:.25,complexity:.2,maintainability:.25,duplication:.15,testability:.15},a=0,t=0;for(let n of e){let o=u[n.name]||.1,l=n.name==="complexity"||n.name==="duplication"?Math.max(0,100-n.value*2):n.value;a+=l*o,t+=o}let r=t>0?Math.round(a/t):0,i=e.find(n=>n.name==="coverage");return{overall:r,coverage:i?i.value:-1,complexity:e.find(n=>n.name==="complexity")?.value||0,maintainability:e.find(n=>n.name==="maintainability")?.value||0,security:85}}async generateTrends(e,u){let a=[];for(let t of e){let r=await this.getQualityTrend(t.name,30);r.success?a.push(r.value):a.push({metric:t.name,dataPoints:[{date:new Date,value:t.value}],direction:"stable"})}return a}generateRecommendations(e,u){let a=[],t=e.find(o=>o.name==="coverage");t&&t.value<80&&a.push({type:t.value<60?"critical":"improvement",title:"Increase Test Coverage",description:`Current coverage is ${t.value}%. Aim for at least 80% coverage to ensure code reliability.`,impact:"high",effort:t.value<60?"high":"medium"});let r=e.find(o=>o.name==="complexity");r&&r.value>this.config.complexityThresholds.cyclomatic.warning&&a.push({type:r.value>this.config.complexityThresholds.cyclomatic.critical?"critical":"warning",title:"Reduce Code Complexity",description:`Average cyclomatic complexity is ${r.value}. Consider refactoring complex functions.`,impact:"high",effort:"medium"});let i=e.find(o=>o.name==="maintainability");i&&i.value<this.config.complexityThresholds.maintainability.warning&&a.push({type:i.value<this.config.complexityThresholds.maintainability.critical?"critical":"warning",title:"Improve Maintainability",description:`Maintainability index is ${i.value}. Consider improving code structure and documentation.`,impact:"medium",effort:"medium"});let n=e.find(o=>o.name==="duplication");return n&&n.value>5&&a.push({type:n.value>10?"warning":"improvement",title:"Reduce Code Duplication",description:`${n.value}% of code is duplicated. Extract common patterns into reusable functions.`,impact:"medium",effort:"low"}),u.overall<70&&a.push({type:"critical",title:"Overall Quality Improvement Needed",description:`Overall quality score is ${u.overall}. Multiple areas need attention to bring code quality to acceptable levels.`,impact:"high",effort:"high"}),a.sort((o,l)=>{let c={critical:0,warning:1,improvement:2};return c[o.type]-c[l.type]})}async analyzeFileComplexity(e,u){let a=u.length===0,t=await this.metricsAnalyzer.analyzeFile(e);return t?{path:e,cyclomatic:a||u.includes("cyclomatic")?t.cyclomaticComplexity:0,cognitive:a||u.includes("cognitive")?t.cognitiveComplexity:0,maintainability:a||u.includes("maintainability")?t.maintainabilityIndex:0,linesOfCode:t.linesOfCode}:{path:e,cyclomatic:a||u.includes("cyclomatic")?5:0,cognitive:a||u.includes("cognitive")?8:0,maintainability:a||u.includes("maintainability")?70:0,linesOfCode:100}}calculateComplexitySummary(e){if(e.length===0)return{averageCyclomatic:0,averageCognitive:0,averageMaintainability:0,totalLinesOfCode:0};let u=e.reduce((i,n)=>i+n.cyclomatic,0),a=e.reduce((i,n)=>i+n.cognitive,0),t=e.reduce((i,n)=>i+n.maintainability,0),r=e.reduce((i,n)=>i+n.linesOfCode,0);return{averageCyclomatic:Math.round(u/e.length*100)/100,averageCognitive:Math.round(a/e.length*100)/100,averageMaintainability:Math.round(t/e.length*100)/100,totalLinesOfCode:r}}identifyHotspots(e){let u=[],a=this.config.complexityThresholds;for(let t of e)t.cyclomatic>=a.cyclomatic.warning&&u.push({file:t.path,function:"unknown",complexity:t.cyclomatic,recommendation:t.cyclomatic>=a.cyclomatic.critical?"Critical: Refactor this function immediately. Consider splitting into smaller functions.":"Consider refactoring to reduce complexity."}),t.cognitive>=a.cognitive.warning&&u.push({file:t.path,function:"unknown",complexity:t.cognitive,recommendation:t.cognitive>=a.cognitive.critical?"Critical: High cognitive complexity makes this code hard to understand and maintain.":"Simplify control flow and reduce nesting depth."}),t.maintainability<=a.maintainability.warning&&u.push({file:t.path,function:"unknown",complexity:100-t.maintainability,recommendation:t.maintainability<=a.maintainability.critical?"Critical: Very low maintainability. Consider a major refactoring effort.":"Improve code documentation and reduce complexity."});return u.sort((t,r)=>r.complexity-t.complexity).slice(0,10)}getMetricRating(e,u){let t=["complexity","duplication"].includes(u)?Math.max(0,100-e*2):e;return t>=Ir.A?"A":t>=Ir.B?"B":t>=Ir.C?"C":t>=Ir.D?"D":"E"}estimateTrend(e){if(e.length<2)return"stable";let u=e.slice(0,Math.floor(e.length/2)),a=e.slice(Math.floor(e.length/2)),t=u.reduce((o,l)=>o+l,0)/u.length,i=a.reduce((o,l)=>o+l,0)/a.length-t,n=t*.05;return i>n?"improving":i<-n?"declining":"stable"}calculateTrendDirection(e){if(e.length<this.config.trendDataPointsMin)return"stable";let u=e.map(t=>t.value);switch(this.estimateTrend(u)){case"improving":return"up";case"declining":return"down";default:return"stable"}}async storeReport(e,u){let a=A(),t=`quality-analysis:report:${a}`;await this.memory.set(t,{id:a,...e,sourceFiles:u,analyzedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400*90})}async storeComplexityReport(e){let u=A(),a=`quality-analysis:complexity:${u}`;await this.memory.set(a,{id:u,...e,analyzedAt:new Date().toISOString()},{namespace:"quality-assessment",ttl:86400*30})}};N();S();J();var Yhu={riskWeights:{coverage:.15,testsPassing:.2,criticalBugs:.25,codeSmells:.05,securityVulnerabilities:.25,technicalDebt:.05,duplications:.05},decisionThresholds:{approved:.3,warning:.6,blocked:.6},enableMLPrediction:!0,learningRate:.1,enableLLMAdvice:!0,llmModelTier:2},e1=B.create("quality-assessment/deployment-advisor"),$e=class{config;memory;llmRouter;constructor(e,u={}){this.config={...Yhu,...u},"memory"in e?(this.memory=e.memory,this.llmRouter=e.llmRouter):this.memory=e}isLLMAdviceAvailable(){return this.config.enableLLMAdvice&&this.llmRouter!==void 0}getModelForTier(e){switch(e){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 generateDeploymentAdviceWithLLM(e,u,a,t){if(!this.llmRouter)return{};try{let r=this.getModelForTier(this.config.llmModelTier),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are a senior DevOps/SRE engineer providing deployment advice.
2671
2671
  Analyze the deployment metrics and provide comprehensive advice. Be specific and actionable.
2672
2672
  Return JSON with the following structure:
2673
2673
  {
@@ -2732,7 +2732,7 @@ ${JSON.stringify(s,null,2)}
2732
2732
  `).filter(Boolean);return Array.from(new Set(r))}catch{return[]}}async getCommitFiles(e="HEAD"){if(!await this.isGitRepository())return[];try{let u=Be(e),a=fu("git",["diff-tree","--no-commit-id","--name-only","-r",u],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();return a?a.split(`
2733
2733
  `).filter(Boolean):[]}catch{return[]}}async getUncommittedFiles(){if(!await this.isGitRepository())return[];try{let e=[];try{let u=fu("git",["diff","--name-only","HEAD"],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();u&&e.push(...u.split(`
2734
2734
  `).filter(Boolean))}catch{}try{let u=fu("git",["diff","--name-only","--cached"],{cwd:this.config.repoRoot,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();u&&e.push(...u.split(`
2735
- `).filter(Boolean))}catch{}return Array.from(new Set(e))}catch{return[]}}getRelativePath(e){return $r.isAbsolute(e)?$r.relative(this.config.repoRoot,e):e}getFromCache(e){if(!this.config.enableCache)return;let u=this.cache.get(e);if(u){if(Date.now()-u.timestamp>this.config.cacheTtl){this.cache.delete(e);return}return u.data}}setCache(e,u){this.config.enableCache&&this.cache.set(e,{data:u,timestamp:Date.now()})}getDefaultFileHistory(e){return{filePath:e,totalCommits:0,uniqueAuthors:0,firstCommit:null,lastCommit:null,changeFrequency:0,isRecentlyModified:!1,bugFixCommits:0}}clearCache(){this.cache.clear()}};S();J();var vpu={defaultThreshold:.5,maxPredictionsPerBatch:100,enableHistoricalAnalysis:!0,modelNamespace:"defect-intelligence:predictor",featureWeights:{codeComplexity:.25,changeFrequency:.2,developerExperience:.15,testCoverage:.2,codeAge:.1,bugHistory:.1},enableLLMPrediction:!0,llmModelTier:2,llmMaxTokens:2048},Fpu=[{name:"codeComplexity",weight:.25},{name:"changeFrequency",weight:.2},{name:"developerExperience",weight:.15},{name:"testCoverage",weight:.2},{name:"codeAge",weight:.1},{name:"bugHistory",weight:.1}],al=B.create("defect-intelligence/defect-predictor"),b0=class{config;memory;gitAnalyzer;fileReader;tsParser;llmRouter;modelMetrics={accuracy:.75,precision:.72,recall:.78,f1Score:.75,totalPredictions:0,lastUpdated:new Date};constructor(e,u={},a,t,r){this.config={...vpu,...u},this.isDependenciesObject(e)?(this.memory=e.memory,this.gitAnalyzer=e.gitAnalyzer??new F0({enableCache:!0}),this.fileReader=e.fileReader??new ju,this.tsParser=e.tsParser??new ua,this.llmRouter=e.llmRouter):(this.memory=e,this.gitAnalyzer=a??new F0({enableCache:!0}),this.fileReader=t??new ju,this.tsParser=r??new ua,this.llmRouter=void 0)}isDependenciesObject(e){return typeof e=="object"&&e!==null&&"memory"in e&&typeof e.memory=="object"}isLLMPredictionAvailable(){return this.config.enableLLMPrediction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async analyzeDefectRiskWithLLM(e,u,a=[]){if(!this.llmRouter)return null;try{let t=this.buildDefectAnalysisPrompt(e,u,a),r=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software quality engineer specializing in defect prediction and code analysis.
2735
+ `).filter(Boolean))}catch{}return Array.from(new Set(e))}catch{return[]}}getRelativePath(e){return $r.isAbsolute(e)?$r.relative(this.config.repoRoot,e):e}getFromCache(e){if(!this.config.enableCache)return;let u=this.cache.get(e);if(u){if(Date.now()-u.timestamp>this.config.cacheTtl){this.cache.delete(e);return}return u.data}}setCache(e,u){this.config.enableCache&&this.cache.set(e,{data:u,timestamp:Date.now()})}getDefaultFileHistory(e){return{filePath:e,totalCommits:0,uniqueAuthors:0,firstCommit:null,lastCommit:null,changeFrequency:0,isRecentlyModified:!1,bugFixCommits:0}}clearCache(){this.cache.clear()}};S();J();var vpu={defaultThreshold:.5,maxPredictionsPerBatch:100,enableHistoricalAnalysis:!0,modelNamespace:"defect-intelligence:predictor",featureWeights:{codeComplexity:.25,changeFrequency:.2,developerExperience:.15,testCoverage:.2,codeAge:.1,bugHistory:.1},enableLLMPrediction:!0,llmModelTier:2,llmMaxTokens:2048},Fpu=[{name:"codeComplexity",weight:.25},{name:"changeFrequency",weight:.2},{name:"developerExperience",weight:.15},{name:"testCoverage",weight:.2},{name:"codeAge",weight:.1},{name:"bugHistory",weight:.1}],al=B.create("defect-intelligence/defect-predictor"),b0=class{config;memory;gitAnalyzer;fileReader;tsParser;llmRouter;modelMetrics={accuracy:.75,precision:.72,recall:.78,f1Score:.75,totalPredictions:0,lastUpdated:new Date};constructor(e,u={},a,t,r){this.config={...vpu,...u},this.isDependenciesObject(e)?(this.memory=e.memory,this.gitAnalyzer=e.gitAnalyzer??new F0({enableCache:!0}),this.fileReader=e.fileReader??new ju,this.tsParser=e.tsParser??new ua,this.llmRouter=e.llmRouter):(this.memory=e,this.gitAnalyzer=a??new F0({enableCache:!0}),this.fileReader=t??new ju,this.tsParser=r??new ua,this.llmRouter=void 0)}isDependenciesObject(e){return typeof e=="object"&&e!==null&&"memory"in e&&typeof e.memory=="object"}isLLMPredictionAvailable(){return this.config.enableLLMPrediction===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){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 analyzeDefectRiskWithLLM(e,u,a=[]){if(!this.llmRouter)return null;try{let t=this.buildDefectAnalysisPrompt(e,u,a),r=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software quality engineer specializing in defect prediction and code analysis.
2736
2736
  Your task is to analyze code changes and provide actionable insights about potential defects.
2737
2737
 
2738
2738
  Respond in JSON format with the following structure:
@@ -2765,9 +2765,9 @@ ${e.slice(0,4e3)}
2765
2765
  // File: ${c}
2766
2766
  ${d.value.slice(0,2e3)}
2767
2767
  `)}}let o=this.calculateModelConfidence(r),l=null;if(this.isLLMPredictionAvailable()&&n.length>0){let c=await this.getHistoricalDefectPatterns(u);if(l=await this.analyzeDefectRiskWithLLM(n,r,c),l){for(let E of r)E.recommendations=this.mergeRecommendationsWithLLM(E.recommendations,l);l.confidenceLevel>.7&&(o=Math.min(1,o*1.1))}}return await this.storePrediction(r),this.modelMetrics.totalPredictions+=r.length,this.modelMetrics.lastUpdated=new Date,p({predictions:r,modelConfidence:o,factors:Array.from(i),llmAnalysis:l??void 0})}catch(u){return m(g(u))}}async getHistoricalDefectPatterns(e){let u=[];for(let t of e.slice(0,5)){let r=await this.memory.get(`${this.config.modelNamespace}:defect-patterns:${t}`);r?.patterns&&u.push(...r.patterns)}let a=await this.memory.get(`${this.config.modelNamespace}:common-defect-patterns`);return a&&u.push(...a),[...new Set(u)].slice(0,10)}async analyzeRegressionRisk(e){try{let{changeset:u,baseline:a,depth:t="shallow"}=e;if(u.length===0)return m(new Error("No files in changeset"));let r=[],i=0;for(let E of u){let d=await this.analyzeFileImpact(E,t);r.push(...d.areas),i+=d.risk}if(a&&this.config.enableHistoricalAnalysis){let E=await this.getBaselineRisk(a);i=(i+E)/2}let n=Math.min(1,i/u.length),o=this.riskToSeverity(n),l=this.generateTestRecommendations(r);return p({overallRisk:n,riskLevel:o,impactedAreas:r,recommendedTests:l,confidence:t==="deep"?.85:.7})}catch(u){return m(g(u))}}async updateModel(e){try{let u=`${this.config.modelNamespace}:feedback:${e.predictionId}`;return await this.memory.set(u,e,{namespace:"defect-intelligence",persist:!0}),await this.recalculateMetrics(e),p(void 0)}catch(u){return m(g(u))}}async getModelMetrics(){let e=await this.memory.get(`${this.config.modelNamespace}:metrics`);return e&&(this.modelMetrics={...e,lastUpdated:new Date(e.lastUpdated)}),{...this.modelMetrics}}async predictForFile(e,u,a){let t=await this.extractFileMetrics(e),r=[],i=0;for(let l of u){let E=(t[l.name]??0)*l.weight;i+=E,r.push({name:l.name,contribution:Math.round(E*100)/100})}i=Math.max(0,Math.min(1,i));let n=this.probabilityToRisk(i,a),o=this.generateRecommendations(r,i);return{file:e,probability:i,riskLevel:n,factors:r.filter(l=>l.contribution>.05),recommendations:o}}async extractFileMetrics(e){let u=await this.memory.get(`${this.config.modelNamespace}:file-metrics:${e}`);if(u)return u;let a={codeComplexity:await this.calculateComplexity(e),changeFrequency:await this.getChangeFrequency(e),developerExperience:await this.getDeveloperExperience(e),testCoverage:await this.getTestCoverage(e),codeAge:await this.getCodeAge(e),bugHistory:await this.getBugHistory(e)};return await this.memory.set(`${this.config.modelNamespace}:file-metrics:${e}`,a,{namespace:"defect-intelligence",ttl:3600}),a}async calculateComplexity(e){let u=e.split(".").pop()?.toLowerCase();if(u&&["ts","tsx","js","jsx"].includes(u)){let a=await this.fileReader.readFile(e);if(a.success)try{let t=e.split("/").pop()||e,r=this.tsParser.parseFile(t,a.value),i=this.tsParser.extractFunctions(r),n=this.tsParser.extractClasses(r),o=a.value.split(`
2768
- `).length,l=i.length,c=n.length,E=n.reduce((eu,q)=>eu+q.methods.length,0),d=i.filter(eu=>eu.isAsync).length,D=a.value,h=(D.match(/\bif\s*\(/g)||[]).length,C=(D.match(/\b(for|while|do)\s*[\(\{]/g)||[]).length,y=(D.match(/\bswitch\s*\(/g)||[]).length,x=(D.match(/\bcatch\s*\(/g)||[]).length,b=(D.match(/\?[^?:]+:/g)||[]).length,R=h+C*2+y*2+x+b,w=Math.min(1,o/500),P=Math.min(1,(l+E)/30),V=Math.min(1,R/50),X=d>0?.1:0,Bu=w*.2+P*.25+V*.4+X+(c>3?.05:0);return Math.max(0,Math.min(1,Bu))}catch(t){al.debug(`AST parse failed: ${t instanceof Error?t.message:t}`)}}return this.estimateComplexityFromPath(e)}estimateComplexityFromPath(e){let u=e.split("/"),a=u[u.length-1],t=.3;return(e.includes("controller")||e.includes("service"))&&(t+=.2),(e.includes("coordinator")||e.includes("orchestrator"))&&(t+=.15),(e.includes("utils")||e.includes("helper"))&&(t-=.1),(e.includes("types")||e.includes("interfaces"))&&(t-=.15),a.length>30&&(t+=.1),Math.max(0,Math.min(1,t))}async getChangeFrequency(e){let u=await this.gitAnalyzer.getChangeFrequency(e);if(u!==.4)return await this.memory.set(`${this.config.modelNamespace}:history:${e}`,{changes:Math.round(u*30)},{ttl:3600}),u;let a=`${this.config.modelNamespace}:history:${e}`,t=await this.memory.get(a);return t?Math.min(1,t.changes/50):.4}async getDeveloperExperience(e){let u=await this.gitAnalyzer.getDeveloperExperience(e);if(u!==.5)return await this.memory.set(`${this.config.modelNamespace}:developer-exp:${e}`,{score:u},{ttl:3600}),u;let a=`${this.config.modelNamespace}:developer-exp:${e}`,t=await this.memory.get(a);return t?t.score:.5}async getTestCoverage(e){try{let u=await this.memory.get(`coverage:file:${e}`);if(u&&typeof u.line=="number")return 1-u.line/100;let a=await this.memory.get("coverage:latest");if(a&&typeof a.line=="number")return 1-a.line/100}catch{}return .4}async getCodeAge(e){let u=await this.gitAnalyzer.getCodeAge(e);if(u!==.4)return u;let a=`${this.config.modelNamespace}:age:${e}`,t=await this.memory.get(a);return t?t.days<7?.7:t.days>365?.3:.4:.4}async getBugHistory(e){let u=await this.gitAnalyzer.getBugHistory(e);if(u!==.2)return await this.memory.set(`${this.config.modelNamespace}:bugs:${e}`,{count:Math.round(u*10)},{ttl:3600}),u;let a=`${this.config.modelNamespace}:bugs:${e}`,t=await this.memory.get(a);return t?Math.min(1,t.count/10):.2}probabilityToRisk(e,u){return e>=u+.3?"critical":e>=u+.15?"high":e>=u?"medium":e>=u-.2?"low":"info"}riskToSeverity(e){return e>=.8?"critical":e>=.6?"high":e>=.4?"medium":e>=.2?"low":"info"}generateRecommendations(e,u){let a=[],t=[...e].sort((r,i)=>i.contribution-r.contribution);for(let r of t.slice(0,3))switch(r.name){case"codeComplexity":r.contribution>.1&&(a.push("Consider refactoring to reduce cyclomatic complexity"),a.push("Break down large functions into smaller, testable units"));break;case"changeFrequency":r.contribution>.1&&(a.push("High churn area - add comprehensive regression tests"),a.push("Consider stabilizing the interface before further changes"));break;case"testCoverage":r.contribution>.1&&(a.push("Increase test coverage to reduce defect risk"),a.push("Add unit tests for critical paths"));break;case"bugHistory":r.contribution>.1&&(a.push("Review past bug fixes for patterns"),a.push("Add regression tests for previously fixed issues"));break;case"codeAge":r.contribution>.1&&a.push("New code requires thorough review and testing");break;case"developerExperience":r.contribution>.1&&a.push("Request code review from senior developer");break}return u>.7&&a.push("CRITICAL: Schedule immediate code review"),a}async analyzeFileImpact(e,u){let a=[],t=0,r=this.categorizeFile(e),i=(await this.extractFileMetrics(e)).codeComplexity;if(a.push({area:r,files:[e],risk:i,reason:`Modified file in ${r} area`}),t+=i,u==="deep"){let n=await this.analyzeDependencies(e);for(let o of n){let l=(await this.extractFileMetrics(o)).codeComplexity*.5;a.push({area:this.categorizeFile(o),files:[o],risk:l,reason:`Dependency of ${e}`}),t+=l}}return{areas:a,risk:t}}categorizeFile(e){return e.includes("controller")?"API Layer":e.includes("service")?"Business Logic":e.includes("repository")||e.includes("dao")?"Data Access":e.includes("model")||e.includes("entity")?"Domain Model":e.includes("util")||e.includes("helper")?"Utilities":e.includes("test")?"Tests":e.includes("config")?"Configuration":"General"}async analyzeDependencies(e){let u=`code-intelligence:dependencies:${e}`,a=await this.memory.get(u);if(a&&a.length>0)return a;let t=[];try{let r=await this.fileReader.readFile(e);if(!r.success)return[];let i=e.split("/").pop()||e,n=this.tsParser.parseFile(i,r.value),o=this.tsParser.extractImports(n);for(let l of o)if(l.module.startsWith(".")){let c=this.resolveRelativeImport(e,l.module);t.push(c)}else l.module.startsWith("node:")||t.push(l.module);t.length>0&&await this.memory.set(u,t,{namespace:"code-intelligence",ttl:3600})}catch(r){al.error(`Failed to analyze dependencies for ${e}`,r instanceof Error?r:void 0)}return t}resolveRelativeImport(e,u){let t=e.substring(0,e.lastIndexOf("/")).split("/"),r=u.split("/");for(let n of r)n!=="."&&(n===".."?t.pop():t.push(n));let i=t.join("/");return!i.endsWith(".ts")&&!i.endsWith(".tsx")&&!i.endsWith(".js")&&(i=i+".ts"),i}async getBaselineRisk(e){let u=`${this.config.modelNamespace}:baseline:${e}`;return(await this.memory.get(u))?.risk??.3}generateTestRecommendations(e){let u=[],a=new Set(e.map(r=>r.area));for(let r of a)switch(r){case"API Layer":u.push("Run API integration tests"),u.push("Verify endpoint response contracts");break;case"Business Logic":u.push("Run unit tests for business rules"),u.push("Execute scenario-based tests");break;case"Data Access":u.push("Run database integration tests"),u.push("Verify data integrity constraints");break;case"Domain Model":u.push("Run entity validation tests"),u.push("Check serialization/deserialization");break}return e.filter(r=>r.risk>.6).length>0&&(u.push("Run full regression test suite"),u.push("Consider exploratory testing for edge cases")),[...new Set(u)]}calculateModelConfidence(e){let u=this.modelMetrics.accuracy,a=e.map(r=>r.probability);return this.calculateVariance(a)>.2&&(u*=.9),e.length>10&&(u*=1.05),Math.min(1,Math.max(0,u))}calculateVariance(e){if(e.length===0)return 0;let u=e.reduce((t,r)=>t+r,0)/e.length;return e.map(t=>Math.pow(t-u,2)).reduce((t,r)=>t+r,0)/e.length}async storePrediction(e){let u=A();await this.memory.set(`${this.config.modelNamespace}:prediction:${u}`,{id:u,predictions:e,timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}async recalculateMetrics(e){let u=e.predictedProbability>=this.config.defaultThreshold,a=u===e.actualDefect,t=.01;this.modelMetrics.accuracy=this.modelMetrics.accuracy*(1-t)+(a?1:0)*t,u&&e.actualDefect?(this.modelMetrics.precision=this.modelMetrics.precision*(1-t)+1*t,this.modelMetrics.recall=this.modelMetrics.recall*(1-t)+1*t):u&&!e.actualDefect?this.modelMetrics.precision=this.modelMetrics.precision*(1-t)+0*t:!u&&e.actualDefect&&(this.modelMetrics.recall=this.modelMetrics.recall*(1-t)+0*t),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})}};N();S();var bpu={minPatternFrequency:2,maxPatterns:50,clusterThreshold:.7,embeddingDimension:Re.DIMENSIONS,patternNamespace:"defect-intelligence:patterns",enableSemanticClustering:!0,enableFlashAttention:!0},qr={"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"}},Bpu=B.create("defect-intelligence/pattern-learner"),B0=class{constructor(e,u={}){this.memory=e;this.config={...bpu,...u},this.embedder=u.embedder??new Pe({enableFallback:!0}),this.config.enableFlashAttention&&this.initializeFlashAttention()}config;patternCache=new Map;embedder;flashAttention=null;flashAttentionAvailable=!1;MAX_CACHED_PATTERNS=5e3;async initializeFlashAttention(){let{createQEFlashAttention:e}=await import("./wrappers-44R4HXVW.js");this.flashAttention=await e("defect-matching",this.config.flashAttentionConfig),this.flashAttentionAvailable=!0,Bpu.info("Flash Attention initialized for defect matching")}async ensureFlashAttentionInitialized(){this.config.enableFlashAttention&&!this.flashAttention&&await this.initializeFlashAttention()}async learnPatterns(e){try{let{defects:u,includeResolutions:a=!1}=e;if(u.length===0)return m(new Error("No defects provided for learning"));let t=[],r=!1,i=await this.extractPatterns(u),n=this.mergeWithKnownPatterns(i);for(let l of n)l.frequency>=this.config.minPatternFrequency&&(t.push(l),await this.storePattern(l),r=!0);let o=this.calculateImprovementEstimate(u.length,t);return a&&await this.learnResolutions(u,t),p({patterns:t.slice(0,this.config.maxPatterns),modelUpdated:r,improvementEstimate:o})}catch(u){return m(g(u))}}async clusterDefects(e){try{let{defects:u,method:a,minClusterSize:t=2}=e;if(u.length===0)return m(new Error("No defects provided for clustering"));let r;switch(a){case"semantic":r=await this.clusterBySemantic(u,t);break;case"behavioral":r=await this.clusterByBehavior(u,t);break;case"temporal":r=await this.clusterByTemporal(u,t);break;default:return m(new Error(`Unknown clustering method: ${a}`))}let i=new Set(r.flatMap(l=>l.defects)),n=u.filter(l=>!i.has(l.id)).map(l=>l.id),o=this.calculateClusteringMetrics(r,u.length);return p({clusters:r,outliers:n,clusteringMetrics:o})}catch(u){return m(g(u))}}async findSimilarDefects(e,u=5){try{let a=await this.generateDefectEmbedding(e),t=await this.memory.vectorSearch(a,u+1),r=[];for(let i of t)if(i.score>=this.config.clusterThreshold){let n=await this.memory.get(i.key);n&&n.id!==e.id&&r.push(n)}return p(r.slice(0,u))}catch(a){return m(g(a))}}async getPatternById(e){if(this.patternCache.has(e))return this.patternCache.get(e);let u=`${this.config.patternNamespace}:${e}`,a=await this.memory.get(u);if(a)return this.cachePattern(a),a}async listPatterns(e=this.config.maxPatterns){let u=[],a=await this.memory.search(`${this.config.patternNamespace}:*`,e*2);for(let t of a){let r=await this.memory.get(t);if(r&&(u.push(r),u.length>=e))break}return u.sort((t,r)=>r.frequency-t.frequency)}getFlashAttentionStatus(){let e=0,u=null,a=null;return this.flashAttention&&(e=this.flashAttention.getMetrics().length,u=this.flashAttention.getAverageSpeedup(),a=this.flashAttention.getWorkload()),{enabled:this.config.enableFlashAttention??!1,available:this.flashAttentionAvailable,workload:a,metricsCount:e,averageSpeedup:u}}async extractPatterns(e){let u=new Map;for(let t of e){let r=`${t.title} ${t.description}`.toLowerCase();for(let[i,n]of Object.entries(qr)){let o=n.indicators.filter(l=>r.includes(l.toLowerCase()));if(o.length>0){let l=u.get(i);l?(l.defects.push(t.id),l.indicators.push(...o.filter(c=>!l.indicators.includes(c)))):u.set(i,{indicators:o,defects:[t.id]})}}if(t.tags)for(let i of t.tags){let n=`tag-${i}`,o=u.get(n);o?o.defects.push(t.id):u.set(n,{indicators:[i],defects:[t.id]})}}let a=[];for(let[t,r]of u){let i=qr[t];a.push({id:A(),name:this.formatPatternName(t),indicators:[...new Set(r.indicators)],frequency:r.defects.length,prevention:i?.prevention||`Address ${t} issues proactively`})}return a}mergeWithKnownPatterns(e){let u=[...e];for(let[a,t]of Object.entries(qr))u.some(i=>i.name.toLowerCase().includes(a.replace("-"," ")))||u.push({id:A(),name:this.formatPatternName(a),indicators:t.indicators,frequency:0,prevention:t.prevention});return u}formatPatternName(e){return e.split("-").map(u=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}async storePattern(e){let u=`${this.config.patternNamespace}:${e.id}`;if(await this.memory.set(u,e,{namespace:"defect-intelligence",persist:!0}),this.config.enableSemanticClustering){let a=await this.generatePatternEmbedding(e);await this.memory.storeVector(u,a,{patternId:e.id,name:e.name})}this.cachePattern(e)}async learnResolutions(e,u){for(let a of u){let t=e.filter(r=>{let i=`${r.title} ${r.description}`.toLowerCase();return a.indicators.some(n=>i.includes(n.toLowerCase()))});t.length>0&&await this.memory.set(`${this.config.patternNamespace}:resolutions:${a.id}`,{patternId:a.id,defectIds:t.map(r=>r.id),learnedAt:new Date().toISOString()},{namespace:"defect-intelligence",persist:!0})}}calculateImprovementEstimate(e,u){if(e===0)return 0;let a=u.reduce((i,n)=>i+n.frequency,0),t=Math.min(1,a/e),r=u.length>0?u.reduce((i,n)=>i+(n.prevention?.1:0),0)/u.length:0;return t*.7+r*.3}async clusterBySemantic(e,u){let a=new Map;await this.ensureFlashAttentionInitialized();let t=[];for(let i of e){let n=await this.generateDefectEmbedding(i);t.push({defect:i,embedding:n}),await this.memory.storeVector(`${this.config.patternNamespace}:defect:${i.id}`,n,{defectId:i.id})}let r=new Set;for(let{defect:i,embedding:n}of t){if(r.has(i.id))continue;let o=[i.id];r.add(i.id);for(let l of t){if(l.defect.id===i.id||r.has(l.defect.id))continue;await this.computeSimilarity(n,l.embedding)>=this.config.clusterThreshold&&(o.push(l.defect.id),r.add(l.defect.id))}if(o.length>=u){let l=A(),c=this.findCommonFactors(e.filter(E=>o.includes(E.id)));a.set(l,{id:l,label:this.generateClusterLabel(e.filter(E=>o.includes(E.id))),defects:o,commonFactors:c,suggestedFix:this.suggestFix(c)})}}return Array.from(a.values())}async computeSimilarity(e,u){if(!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Call ensureFlashAttentionInitialized() first.");return this.computeFlashAttentionSimilarity(e,u)}async computeFlashAttentionSimilarity(e,u){let a=e.length,t=new Float32Array(a),r=new Float32Array(a),i=new Float32Array(a);for(let l=0;l<a;l++)t[l]=e[l],r[l]=u[l],i[l]=u[l];let n=await this.flashAttention.computeFlashAttention(t,r,i,1,a),o=0;for(let l=0;l<a;l++)o+=n[l]*e[l];return Math.max(0,Math.min(1,(o+1)/2))}async batchComputeSimilarities(e,u){if(await this.ensureFlashAttentionInitialized(),!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Ensure @ruvector/attention is installed as a dependency.");let a=new Float32Array(e),t=u.map(n=>new Float32Array(n)),r=await this.flashAttention.matchDefectPattern(a,t),i=new Array(u.length).fill(0);for(let n of r)n.pattern<i.length&&(i[n.pattern]=Math.max(0,Math.min(1,(n.score+1)/2)));return i}async clusterByBehavior(e,u){let a=new Map,t=new Map;for(let r of e){let i=r.tags?.sort().join("|")||r.file||"unknown",n=t.get(i)||[];n.push(r),t.set(i,n)}for(let[r,i]of t)if(i.length>=u){let n=A(),o=this.findCommonFactors(i);a.set(n,{id:n,label:`Behavioral: ${r.replace(/\|/g,", ")}`,defects:i.map(l=>l.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(a.values())}async clusterByTemporal(e,u){let a=new Map,t=new Map;for(let r of e){let i=r.title.toLowerCase().split(/\s+/).slice(0,2).join(" "),n=t.get(i)||[];n.push(r),t.set(i,n)}for(let[r,i]of t)if(i.length>=2){let n=A(),o=this.findCommonFactors(i);a.set(n,{id:n,label:`Temporal: ${r}`,defects:i.map(l=>l.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(a.values())}findCommonFactors(e){let u=[];if(e.every(r=>r.tags)){let r=e.map(n=>new Set(n.tags)),i=[...r[0]].filter(n=>r.every(o=>o.has(n)));u.push(...i)}if(e.every(r=>r.file)){let r=e.map(n=>n.file.split("/")),i=Math.min(...r.map(n=>n.length));for(let n=0;n<i;n++)r.every(o=>o[n]===r[0][n])&&u.push(`Path: ${r[0][n]}`)}let a=e.map(r=>new Set(r.title.toLowerCase().split(/\s+/))),t=[...a[0]].filter(r=>r.length>3&&a.every(i=>i.has(r)));return u.push(...t.map(r=>`Keyword: ${r}`)),[...new Set(u)]}generateClusterLabel(e){let a=e.map(i=>i.title.toLowerCase()).flatMap(i=>i.split(/\s+/)),t=new Map;for(let i of a)i.length>3&&t.set(i,(t.get(i)||0)+1);return[...t.entries()].sort((i,n)=>n[1]-i[1]).slice(0,2).map(([i])=>i).join(" ")||"Unnamed Cluster"}suggestFix(e){for(let u of e)for(let[a,t]of Object.entries(qr))if(u.toLowerCase().includes(a)||t.indicators.some(r=>u.toLowerCase().includes(r.toLowerCase())))return t.prevention;return"Review common factors and implement targeted fixes"}calculateClusteringMetrics(e,u){if(e.length===0||u===0)return{silhouette:0,cohesion:0};let a=e.reduce((l,c)=>l+c.defects.length,0),t=a/e.length,r=a/u,i=e.map(l=>l.defects.length),n=i.reduce((l,c)=>l+Math.pow(c-t,2),0)/i.length,o=Math.max(0,1-n/(t*t||1));return{silhouette:Math.round(o*100)/100,cohesion:Math.round(r*100)/100}}async generateDefectEmbedding(e){let u=this.formatDefectForEmbedding(e);return this.embedder.embed(u)}async generatePatternEmbedding(e){let u=this.formatPatternForEmbedding(e);return this.embedder.embed(u)}formatDefectForEmbedding(e){return[`Title: ${e.title}`,e.description?`Description: ${e.description}`:"",e.tags?.length?`Tags: ${e.tags.join(", ")}`:"",e.file?`File: ${e.file}`:""].filter(Boolean).join(`
2768
+ `).length,l=i.length,c=n.length,E=n.reduce((eu,q)=>eu+q.methods.length,0),d=i.filter(eu=>eu.isAsync).length,D=a.value,h=(D.match(/\bif\s*\(/g)||[]).length,C=(D.match(/\b(for|while|do)\s*[\(\{]/g)||[]).length,y=(D.match(/\bswitch\s*\(/g)||[]).length,x=(D.match(/\bcatch\s*\(/g)||[]).length,b=(D.match(/\?[^?:]+:/g)||[]).length,R=h+C*2+y*2+x+b,w=Math.min(1,o/500),P=Math.min(1,(l+E)/30),V=Math.min(1,R/50),X=d>0?.1:0,Bu=w*.2+P*.25+V*.4+X+(c>3?.05:0);return Math.max(0,Math.min(1,Bu))}catch(t){al.debug(`AST parse failed: ${t instanceof Error?t.message:t}`)}}return this.estimateComplexityFromPath(e)}estimateComplexityFromPath(e){let u=e.split("/"),a=u[u.length-1],t=.3;return(e.includes("controller")||e.includes("service"))&&(t+=.2),(e.includes("coordinator")||e.includes("orchestrator"))&&(t+=.15),(e.includes("utils")||e.includes("helper"))&&(t-=.1),(e.includes("types")||e.includes("interfaces"))&&(t-=.15),a.length>30&&(t+=.1),Math.max(0,Math.min(1,t))}async getChangeFrequency(e){let u=await this.gitAnalyzer.getChangeFrequency(e);if(u!==.4)return await this.memory.set(`${this.config.modelNamespace}:history:${e}`,{changes:Math.round(u*30)},{ttl:3600}),u;let a=`${this.config.modelNamespace}:history:${e}`,t=await this.memory.get(a);return t?Math.min(1,t.changes/50):.4}async getDeveloperExperience(e){let u=await this.gitAnalyzer.getDeveloperExperience(e);if(u!==.5)return await this.memory.set(`${this.config.modelNamespace}:developer-exp:${e}`,{score:u},{ttl:3600}),u;let a=`${this.config.modelNamespace}:developer-exp:${e}`,t=await this.memory.get(a);return t?t.score:.5}async getTestCoverage(e){try{let u=await this.memory.get(`coverage:file:${e}`);if(u&&typeof u.line=="number")return 1-u.line/100;let a=await this.memory.get("coverage:latest");if(a&&typeof a.line=="number")return 1-a.line/100}catch{}return .4}async getCodeAge(e){let u=await this.gitAnalyzer.getCodeAge(e);if(u!==.4)return u;let a=`${this.config.modelNamespace}:age:${e}`,t=await this.memory.get(a);return t?t.days<7?.7:t.days>365?.3:.4:.4}async getBugHistory(e){let u=await this.gitAnalyzer.getBugHistory(e);if(u!==.2)return await this.memory.set(`${this.config.modelNamespace}:bugs:${e}`,{count:Math.round(u*10)},{ttl:3600}),u;let a=`${this.config.modelNamespace}:bugs:${e}`,t=await this.memory.get(a);return t?Math.min(1,t.count/10):.2}probabilityToRisk(e,u){return e>=u+.3?"critical":e>=u+.15?"high":e>=u?"medium":e>=u-.2?"low":"info"}riskToSeverity(e){return e>=.8?"critical":e>=.6?"high":e>=.4?"medium":e>=.2?"low":"info"}generateRecommendations(e,u){let a=[],t=[...e].sort((r,i)=>i.contribution-r.contribution);for(let r of t.slice(0,3))switch(r.name){case"codeComplexity":r.contribution>.1&&(a.push("Consider refactoring to reduce cyclomatic complexity"),a.push("Break down large functions into smaller, testable units"));break;case"changeFrequency":r.contribution>.1&&(a.push("High churn area - add comprehensive regression tests"),a.push("Consider stabilizing the interface before further changes"));break;case"testCoverage":r.contribution>.1&&(a.push("Increase test coverage to reduce defect risk"),a.push("Add unit tests for critical paths"));break;case"bugHistory":r.contribution>.1&&(a.push("Review past bug fixes for patterns"),a.push("Add regression tests for previously fixed issues"));break;case"codeAge":r.contribution>.1&&a.push("New code requires thorough review and testing");break;case"developerExperience":r.contribution>.1&&a.push("Request code review from senior developer");break}return u>.7&&a.push("CRITICAL: Schedule immediate code review"),a}async analyzeFileImpact(e,u){let a=[],t=0,r=this.categorizeFile(e),i=(await this.extractFileMetrics(e)).codeComplexity;if(a.push({area:r,files:[e],risk:i,reason:`Modified file in ${r} area`}),t+=i,u==="deep"){let n=await this.analyzeDependencies(e);for(let o of n){let l=(await this.extractFileMetrics(o)).codeComplexity*.5;a.push({area:this.categorizeFile(o),files:[o],risk:l,reason:`Dependency of ${e}`}),t+=l}}return{areas:a,risk:t}}categorizeFile(e){return e.includes("controller")?"API Layer":e.includes("service")?"Business Logic":e.includes("repository")||e.includes("dao")?"Data Access":e.includes("model")||e.includes("entity")?"Domain Model":e.includes("util")||e.includes("helper")?"Utilities":e.includes("test")?"Tests":e.includes("config")?"Configuration":"General"}async analyzeDependencies(e){let u=`code-intelligence:dependencies:${e}`,a=await this.memory.get(u);if(a&&a.length>0)return a;let t=[];try{let r=await this.fileReader.readFile(e);if(!r.success)return[];let i=e.split("/").pop()||e,n=this.tsParser.parseFile(i,r.value),o=this.tsParser.extractImports(n);for(let l of o)if(l.module.startsWith(".")){let c=this.resolveRelativeImport(e,l.module);t.push(c)}else l.module.startsWith("node:")||t.push(l.module);t.length>0&&await this.memory.set(u,t,{namespace:"code-intelligence",ttl:3600})}catch(r){al.error(`Failed to analyze dependencies for ${e}`,r instanceof Error?r:void 0)}return t}resolveRelativeImport(e,u){let t=e.substring(0,e.lastIndexOf("/")).split("/"),r=u.split("/");for(let n of r)n!=="."&&(n===".."?t.pop():t.push(n));let i=t.join("/");return!i.endsWith(".ts")&&!i.endsWith(".tsx")&&!i.endsWith(".js")&&(i=i+".ts"),i}async getBaselineRisk(e){let u=`${this.config.modelNamespace}:baseline:${e}`;return(await this.memory.get(u))?.risk??.3}generateTestRecommendations(e){let u=[],a=new Set(e.map(r=>r.area));for(let r of a)switch(r){case"API Layer":u.push("Run API integration tests"),u.push("Verify endpoint response contracts");break;case"Business Logic":u.push("Run unit tests for business rules"),u.push("Execute scenario-based tests");break;case"Data Access":u.push("Run database integration tests"),u.push("Verify data integrity constraints");break;case"Domain Model":u.push("Run entity validation tests"),u.push("Check serialization/deserialization");break}return e.filter(r=>r.risk>.6).length>0&&(u.push("Run full regression test suite"),u.push("Consider exploratory testing for edge cases")),[...new Set(u)]}calculateModelConfidence(e){let u=this.modelMetrics.accuracy,a=e.map(r=>r.probability);return this.calculateVariance(a)>.2&&(u*=.9),e.length>10&&(u*=1.05),Math.min(1,Math.max(0,u))}calculateVariance(e){if(e.length===0)return 0;let u=e.reduce((t,r)=>t+r,0)/e.length;return e.map(t=>Math.pow(t-u,2)).reduce((t,r)=>t+r,0)/e.length}async storePrediction(e){let u=A();await this.memory.set(`${this.config.modelNamespace}:prediction:${u}`,{id:u,predictions:e,timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}async recalculateMetrics(e){let u=e.predictedProbability>=this.config.defaultThreshold,a=u===e.actualDefect,t=.01;this.modelMetrics.accuracy=this.modelMetrics.accuracy*(1-t)+(a?1:0)*t,u&&e.actualDefect?(this.modelMetrics.precision=this.modelMetrics.precision*(1-t)+1*t,this.modelMetrics.recall=this.modelMetrics.recall*(1-t)+1*t):u&&!e.actualDefect?this.modelMetrics.precision=this.modelMetrics.precision*(1-t)+0*t:!u&&e.actualDefect&&(this.modelMetrics.recall=this.modelMetrics.recall*(1-t)+0*t),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})}};N();S();var bpu={minPatternFrequency:2,maxPatterns:50,clusterThreshold:.7,embeddingDimension:Re.DIMENSIONS,patternNamespace:"defect-intelligence:patterns",enableSemanticClustering:!0,enableFlashAttention:!0},qr={"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"}},Bpu=B.create("defect-intelligence/pattern-learner"),B0=class{constructor(e,u={}){this.memory=e;this.config={...bpu,...u},this.embedder=u.embedder??new Pe({enableFallback:!0}),this.config.enableFlashAttention&&this.initializeFlashAttention()}config;patternCache=new Map;embedder;flashAttention=null;flashAttentionAvailable=!1;MAX_CACHED_PATTERNS=5e3;async initializeFlashAttention(){let{createQEFlashAttention:e}=await import("./wrappers-WSSLMFSE.js");this.flashAttention=await e("defect-matching",this.config.flashAttentionConfig),this.flashAttentionAvailable=!0,Bpu.info("Flash Attention initialized for defect matching")}async ensureFlashAttentionInitialized(){this.config.enableFlashAttention&&!this.flashAttention&&await this.initializeFlashAttention()}async learnPatterns(e){try{let{defects:u,includeResolutions:a=!1}=e;if(u.length===0)return m(new Error("No defects provided for learning"));let t=[],r=!1,i=await this.extractPatterns(u),n=this.mergeWithKnownPatterns(i);for(let l of n)l.frequency>=this.config.minPatternFrequency&&(t.push(l),await this.storePattern(l),r=!0);let o=this.calculateImprovementEstimate(u.length,t);return a&&await this.learnResolutions(u,t),p({patterns:t.slice(0,this.config.maxPatterns),modelUpdated:r,improvementEstimate:o})}catch(u){return m(g(u))}}async clusterDefects(e){try{let{defects:u,method:a,minClusterSize:t=2}=e;if(u.length===0)return m(new Error("No defects provided for clustering"));let r;switch(a){case"semantic":r=await this.clusterBySemantic(u,t);break;case"behavioral":r=await this.clusterByBehavior(u,t);break;case"temporal":r=await this.clusterByTemporal(u,t);break;default:return m(new Error(`Unknown clustering method: ${a}`))}let i=new Set(r.flatMap(l=>l.defects)),n=u.filter(l=>!i.has(l.id)).map(l=>l.id),o=this.calculateClusteringMetrics(r,u.length);return p({clusters:r,outliers:n,clusteringMetrics:o})}catch(u){return m(g(u))}}async findSimilarDefects(e,u=5){try{let a=await this.generateDefectEmbedding(e),t=await this.memory.vectorSearch(a,u+1),r=[];for(let i of t)if(i.score>=this.config.clusterThreshold){let n=await this.memory.get(i.key);n&&n.id!==e.id&&r.push(n)}return p(r.slice(0,u))}catch(a){return m(g(a))}}async getPatternById(e){if(this.patternCache.has(e))return this.patternCache.get(e);let u=`${this.config.patternNamespace}:${e}`,a=await this.memory.get(u);if(a)return this.cachePattern(a),a}async listPatterns(e=this.config.maxPatterns){let u=[],a=await this.memory.search(`${this.config.patternNamespace}:*`,e*2);for(let t of a){let r=await this.memory.get(t);if(r&&(u.push(r),u.length>=e))break}return u.sort((t,r)=>r.frequency-t.frequency)}getFlashAttentionStatus(){let e=0,u=null,a=null;return this.flashAttention&&(e=this.flashAttention.getMetrics().length,u=this.flashAttention.getAverageSpeedup(),a=this.flashAttention.getWorkload()),{enabled:this.config.enableFlashAttention??!1,available:this.flashAttentionAvailable,workload:a,metricsCount:e,averageSpeedup:u}}async extractPatterns(e){let u=new Map;for(let t of e){let r=`${t.title} ${t.description}`.toLowerCase();for(let[i,n]of Object.entries(qr)){let o=n.indicators.filter(l=>r.includes(l.toLowerCase()));if(o.length>0){let l=u.get(i);l?(l.defects.push(t.id),l.indicators.push(...o.filter(c=>!l.indicators.includes(c)))):u.set(i,{indicators:o,defects:[t.id]})}}if(t.tags)for(let i of t.tags){let n=`tag-${i}`,o=u.get(n);o?o.defects.push(t.id):u.set(n,{indicators:[i],defects:[t.id]})}}let a=[];for(let[t,r]of u){let i=qr[t];a.push({id:A(),name:this.formatPatternName(t),indicators:[...new Set(r.indicators)],frequency:r.defects.length,prevention:i?.prevention||`Address ${t} issues proactively`})}return a}mergeWithKnownPatterns(e){let u=[...e];for(let[a,t]of Object.entries(qr))u.some(i=>i.name.toLowerCase().includes(a.replace("-"," ")))||u.push({id:A(),name:this.formatPatternName(a),indicators:t.indicators,frequency:0,prevention:t.prevention});return u}formatPatternName(e){return e.split("-").map(u=>u.charAt(0).toUpperCase()+u.slice(1)).join(" ")}async storePattern(e){let u=`${this.config.patternNamespace}:${e.id}`;if(await this.memory.set(u,e,{namespace:"defect-intelligence",persist:!0}),this.config.enableSemanticClustering){let a=await this.generatePatternEmbedding(e);await this.memory.storeVector(u,a,{patternId:e.id,name:e.name})}this.cachePattern(e)}async learnResolutions(e,u){for(let a of u){let t=e.filter(r=>{let i=`${r.title} ${r.description}`.toLowerCase();return a.indicators.some(n=>i.includes(n.toLowerCase()))});t.length>0&&await this.memory.set(`${this.config.patternNamespace}:resolutions:${a.id}`,{patternId:a.id,defectIds:t.map(r=>r.id),learnedAt:new Date().toISOString()},{namespace:"defect-intelligence",persist:!0})}}calculateImprovementEstimate(e,u){if(e===0)return 0;let a=u.reduce((i,n)=>i+n.frequency,0),t=Math.min(1,a/e),r=u.length>0?u.reduce((i,n)=>i+(n.prevention?.1:0),0)/u.length:0;return t*.7+r*.3}async clusterBySemantic(e,u){let a=new Map;await this.ensureFlashAttentionInitialized();let t=[];for(let i of e){let n=await this.generateDefectEmbedding(i);t.push({defect:i,embedding:n}),await this.memory.storeVector(`${this.config.patternNamespace}:defect:${i.id}`,n,{defectId:i.id})}let r=new Set;for(let{defect:i,embedding:n}of t){if(r.has(i.id))continue;let o=[i.id];r.add(i.id);for(let l of t){if(l.defect.id===i.id||r.has(l.defect.id))continue;await this.computeSimilarity(n,l.embedding)>=this.config.clusterThreshold&&(o.push(l.defect.id),r.add(l.defect.id))}if(o.length>=u){let l=A(),c=this.findCommonFactors(e.filter(E=>o.includes(E.id)));a.set(l,{id:l,label:this.generateClusterLabel(e.filter(E=>o.includes(E.id))),defects:o,commonFactors:c,suggestedFix:this.suggestFix(c)})}}return Array.from(a.values())}async computeSimilarity(e,u){if(!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Call ensureFlashAttentionInitialized() first.");return this.computeFlashAttentionSimilarity(e,u)}async computeFlashAttentionSimilarity(e,u){let a=e.length,t=new Float32Array(a),r=new Float32Array(a),i=new Float32Array(a);for(let l=0;l<a;l++)t[l]=e[l],r[l]=u[l],i[l]=u[l];let n=await this.flashAttention.computeFlashAttention(t,r,i,1,a),o=0;for(let l=0;l<a;l++)o+=n[l]*e[l];return Math.max(0,Math.min(1,(o+1)/2))}async batchComputeSimilarities(e,u){if(await this.ensureFlashAttentionInitialized(),!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Ensure @ruvector/attention is installed as a dependency.");let a=new Float32Array(e),t=u.map(n=>new Float32Array(n)),r=await this.flashAttention.matchDefectPattern(a,t),i=new Array(u.length).fill(0);for(let n of r)n.pattern<i.length&&(i[n.pattern]=Math.max(0,Math.min(1,(n.score+1)/2)));return i}async clusterByBehavior(e,u){let a=new Map,t=new Map;for(let r of e){let i=r.tags?.sort().join("|")||r.file||"unknown",n=t.get(i)||[];n.push(r),t.set(i,n)}for(let[r,i]of t)if(i.length>=u){let n=A(),o=this.findCommonFactors(i);a.set(n,{id:n,label:`Behavioral: ${r.replace(/\|/g,", ")}`,defects:i.map(l=>l.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(a.values())}async clusterByTemporal(e,u){let a=new Map,t=new Map;for(let r of e){let i=r.title.toLowerCase().split(/\s+/).slice(0,2).join(" "),n=t.get(i)||[];n.push(r),t.set(i,n)}for(let[r,i]of t)if(i.length>=2){let n=A(),o=this.findCommonFactors(i);a.set(n,{id:n,label:`Temporal: ${r}`,defects:i.map(l=>l.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(a.values())}findCommonFactors(e){let u=[];if(e.every(r=>r.tags)){let r=e.map(n=>new Set(n.tags)),i=[...r[0]].filter(n=>r.every(o=>o.has(n)));u.push(...i)}if(e.every(r=>r.file)){let r=e.map(n=>n.file.split("/")),i=Math.min(...r.map(n=>n.length));for(let n=0;n<i;n++)r.every(o=>o[n]===r[0][n])&&u.push(`Path: ${r[0][n]}`)}let a=e.map(r=>new Set(r.title.toLowerCase().split(/\s+/))),t=[...a[0]].filter(r=>r.length>3&&a.every(i=>i.has(r)));return u.push(...t.map(r=>`Keyword: ${r}`)),[...new Set(u)]}generateClusterLabel(e){let a=e.map(i=>i.title.toLowerCase()).flatMap(i=>i.split(/\s+/)),t=new Map;for(let i of a)i.length>3&&t.set(i,(t.get(i)||0)+1);return[...t.entries()].sort((i,n)=>n[1]-i[1]).slice(0,2).map(([i])=>i).join(" ")||"Unnamed Cluster"}suggestFix(e){for(let u of e)for(let[a,t]of Object.entries(qr))if(u.toLowerCase().includes(a)||t.indicators.some(r=>u.toLowerCase().includes(r.toLowerCase())))return t.prevention;return"Review common factors and implement targeted fixes"}calculateClusteringMetrics(e,u){if(e.length===0||u===0)return{silhouette:0,cohesion:0};let a=e.reduce((l,c)=>l+c.defects.length,0),t=a/e.length,r=a/u,i=e.map(l=>l.defects.length),n=i.reduce((l,c)=>l+Math.pow(c-t,2),0)/i.length,o=Math.max(0,1-n/(t*t||1));return{silhouette:Math.round(o*100)/100,cohesion:Math.round(r*100)/100}}async generateDefectEmbedding(e){let u=this.formatDefectForEmbedding(e);return this.embedder.embed(u)}async generatePatternEmbedding(e){let u=this.formatPatternForEmbedding(e);return this.embedder.embed(u)}formatDefectForEmbedding(e){return[`Title: ${e.title}`,e.description?`Description: ${e.description}`:"",e.tags?.length?`Tags: ${e.tags.join(", ")}`:"",e.file?`File: ${e.file}`:""].filter(Boolean).join(`
2769
2769
  `)}formatPatternForEmbedding(e){return[`Pattern: ${e.name}`,`Indicators: ${e.indicators.join(", ")}`,`Prevention: ${e.prevention}`,`Frequency: ${e.frequency}`].filter(Boolean).join(`
2770
- `)}cachePattern(e){if(this.patternCache.size>=this.MAX_CACHED_PATTERNS){let u=this.patternCache.keys().next().value;u&&this.patternCache.delete(u)}this.patternCache.set(e.id,e)}destroy(){this.patternCache.clear(),this.flashAttention=null,this.flashAttentionAvailable=!1}};N();S();J();var kpu={maxTimelineEvents:20,maxRelatedFiles:10,minConfidenceThreshold:.3,analyzerNamespace:"defect-intelligence:root-cause",enableDeepAnalysis:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},Jr={"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"]}},Spu=B.create("defect-intelligence/root-cause-analyzer"),k0=class{config;memory;llmRouter;constructor(e,u={}){this.config={...kpu,...u},this.isMemoryBackend(e)?(this.memory=e,this.llmRouter=void 0):(this.memory=e.memory,this.llmRouter=e.llmRouter)}isMemoryBackend(e){return typeof e.get=="function"&&typeof e.set=="function"&&!("memory"in e)}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async analyzeRootCauseWithLLM(e,u,a){if(!this.llmRouter)return null;try{let t=this.buildLLMAnalysisPrompt(e,u,a),r=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software engineer specialized in debugging and root cause analysis.
2770
+ `)}cachePattern(e){if(this.patternCache.size>=this.MAX_CACHED_PATTERNS){let u=this.patternCache.keys().next().value;u&&this.patternCache.delete(u)}this.patternCache.set(e.id,e)}destroy(){this.patternCache.clear(),this.flashAttention=null,this.flashAttentionAvailable=!1}};N();S();J();var kpu={maxTimelineEvents:20,maxRelatedFiles:10,minConfidenceThreshold:.3,analyzerNamespace:"defect-intelligence:root-cause",enableDeepAnalysis:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},Jr={"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"]}},Spu=B.create("defect-intelligence/root-cause-analyzer"),k0=class{config;memory;llmRouter;constructor(e,u={}){this.config={...kpu,...u},this.isMemoryBackend(e)?(this.memory=e,this.llmRouter=void 0):(this.memory=e.memory,this.llmRouter=e.llmRouter)}isMemoryBackend(e){return typeof e.get=="function"&&typeof e.set=="function"&&!("memory"in e)}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){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(e,u,a){if(!this.llmRouter)return null;try{let t=this.buildLLMAnalysisPrompt(e,u,a),r=this.getModelForTier(this.config.llmModelTier??2),i=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software engineer specialized in debugging and root cause analysis.
2771
2771
  Analyze the provided defect information and provide:
2772
2772
  1. Root cause identification with clear explanation
2773
2773
  2. Contributing factors ranked by impact
@@ -2817,7 +2817,7 @@ ${a}
2817
2817
  `).filter(t=>t.trim())[0]?.replace(/^(root cause:|the root cause is|caused by)/i,"").trim()||"Unable to parse root cause",explanation:e,contributingFactors:[],recommendedFixes:[],preventionStrategies:[]}}async analyzeRootCause(e){try{let{defectId:u,symptoms:a,context:t={}}=e;if(a.length===0)return m(new Error("No symptoms provided for analysis"));if(this.isLLMAnalysisAvailable()){let E=await this.analyzeRootCauseWithLLM({defectId:u,symptoms:a,context:t},t.stackTrace,t.codeContext);if(E){let d=await this.findRelatedFiles(u,a),D=await this.generateTimeline(u),h=[...E.recommendedFixes.map(C=>C.codeExample?`${C.description}
2818
2818
  \`\`\`
2819
2819
  ${C.codeExample}
2820
- \`\`\``:C.description),...E.preventionStrategies];return await this.storeAnalysis({defectId:u,rootCause:E.rootCause,category:"llm-analyzed",confidence:.85,symptoms:a,timestamp:new Date}),p({defectId:u,rootCause:E.rootCause,confidence:.85,contributingFactors:E.contributingFactors,relatedFiles:d,recommendations:h,timeline:D.success?D.value:[]})}}let r=this.identifyRootCauseCategory(a),i=this.calculateConfidence(r,a);if(i<this.config.minConfidenceThreshold)return p({defectId:u,rootCause:"Unable to determine root cause with sufficient confidence",confidence:i,contributingFactors:[],relatedFiles:[],recommendations:["Provide more symptoms for better analysis"],timeline:[]});let n=await this.identifyContributingFactors(r.category,a,t),o=await this.findRelatedFiles(u,a),l=this.generateRecommendations(r,n),c=await this.generateTimeline(u);return await this.storeAnalysis({defectId:u,rootCause:r.rootCause,category:r.category,confidence:i,symptoms:a,timestamp:new Date}),p({defectId:u,rootCause:r.rootCause,confidence:i,contributingFactors:n,relatedFiles:o,recommendations:l,timeline:c.success?c.value:[]})}catch(u){return m(g(u))}}async findRelatedDefects(e){try{let u=await this.memory.get(`${this.config.analyzerNamespace}:analysis:${e}`);if(!u)return p([]);let a=await this.memory.search(`${this.config.analyzerNamespace}:analysis:*`,50),t=[];for(let r of a){let i=await this.memory.get(r);i&&i.defectId!==e&&i.category===u.category&&t.push(i.defectId)}return p(t)}catch(u){return m(g(u))}}async generateTimeline(e){try{let u=[],a=`${this.config.analyzerNamespace}:events:${e}`,t=await this.memory.get(a);t&&u.push(...t);let r=await this.memory.search("code-intelligence:change:*",this.config.maxTimelineEvents);for(let n of r){let o=await this.memory.get(n);o&&u.push({timestamp:new Date(o.timestamp),event:`Code change: ${o.description}`,relevance:.5})}let i=u.sort((n,o)=>o.timestamp.getTime()-n.timestamp.getTime()).slice(0,this.config.maxTimelineEvents);return p(i)}catch(u){return m(g(u))}}async suggestRemediation(e){let u=[];for(let[a,t]of Object.entries(Jr))(e.toLowerCase().includes(a)||t.causes.some(r=>e.toLowerCase().includes(r.toLowerCase())))&&u.push(...t.remediation);return u.length===0&&(u.push("Review the affected code thoroughly"),u.push("Add tests to prevent regression"),u.push("Document the fix for future reference")),[...new Set(u)]}identifyRootCauseCategory(e){let u={category:"unknown",rootCause:"Undetermined root cause",matchScore:0},a=e.join(" ").toLowerCase();for(let[t,r]of Object.entries(Jr)){let i=0;for(let n of r.symptoms)a.includes(n.toLowerCase())&&(i+=1);if(i=i/r.symptoms.length,i>u.matchScore){let n=this.selectLikelyCause(r.causes,a);u={category:t,rootCause:n,matchScore:i}}}return u}selectLikelyCause(e,u){let a=e[0],t=0;for(let r of e){let i=r.toLowerCase().split(/\s+/),n=0;for(let o of i)o.length>3&&u.includes(o)&&(n+=1);n>t&&(t=n,a=r)}return a}calculateConfidence(e,u){let a=e.matchScore;return u.length>=3?a*=1.1:u.length===1&&(a*=.8),Math.min(1,Math.max(0,a))}async identifyContributingFactors(e,u,a){let t=[],r=Jr[e];if(!r)return t;t.push({factor:`Category: ${e}`,impact:r.impact,evidence:u.slice(0,3)}),a.recentChanges&&t.push({factor:"Recent code changes",impact:"high",evidence:["Code was recently modified"]}),a.highTraffic&&t.push({factor:"High traffic conditions",impact:"medium",evidence:["Occurred during peak load"]}),a.environment&&t.push({factor:`Environment: ${a.environment}`,impact:"medium",evidence:[`Observed in ${a.environment} environment`]});let i=await this.getHistoricalFactors(e);return t.push(...i),t}async getHistoricalFactors(e){let u=[],a=`${this.config.analyzerNamespace}:history:${e}`,t=await this.memory.get(a);return t&&t.occurrences>1&&u.push({factor:"Recurring issue pattern",impact:"high",evidence:[`Similar issues occurred ${t.occurrences} times`,...t.commonFactors.slice(0,2)]}),u}async findRelatedFiles(e,u){let a=new Set;for(let r of u){let i=r.match(/[\w\-]+\.(ts|js|tsx|jsx|py|java|go)/g);i&&i.forEach(o=>a.add(o));let n=r.match(/(?:src|lib|app)\/[\w\/\-]+/g);n&&n.forEach(o=>a.add(o))}let t=await this.memory.search("code-intelligence:file:*",this.config.maxRelatedFiles);for(let r of t.slice(0,this.config.maxRelatedFiles-a.size)){let i=await this.memory.get(r);i&&a.add(i.path)}return Array.from(a).slice(0,this.config.maxRelatedFiles)}generateRecommendations(e,u){let a=[],t=Jr[e.category];t&&a.push(...t.remediation);for(let r of u)r.impact==="high"&&a.push(`Address: ${r.factor}`);return a.push("Add regression tests for this scenario"),a.push("Document the root cause and fix"),[...new Set(a)].slice(0,8)}async storeAnalysis(e){await this.memory.set(`${this.config.analyzerNamespace}:analysis:${e.defectId}`,e,{namespace:"defect-intelligence",persist:!0});let u=`${this.config.analyzerNamespace}:history:${e.category}`,a=await this.memory.get(u)||{occurrences:0,commonFactors:[]};a.occurrences+=1;for(let t of e.symptoms.slice(0,2))a.commonFactors.includes(t)||a.commonFactors.push(t);a.commonFactors=a.commonFactors.slice(0,10),await this.memory.set(u,a,{namespace:"defect-intelligence",persist:!0})}};Qu();var wpu={maxLag:5,alpha:.05,minSeriesLength:30},Tpu=200,Vu=1e-10,Oa=1e-12;function Ur(s){if(s<=0)return 1/0;let e=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,15056327351493116e-23];if(s<.5)return Math.log(Math.PI/Math.sin(Math.PI*s))-Ur(1-s);s-=1;let u=e[0];for(let t=1;t<9;t++)u+=e[t]/(s+t);let a=s+7.5;return .5*Math.log(2*Math.PI)+(s+.5)*Math.log(a)-a+Math.log(u)}function Mpu(s,e){return Ur(s)+Ur(e)-Ur(s+e)}function R1(s,e,u){if(s<=0)return 0;if(s>=1)return 1;if(e<=0||u<=0)return NaN;if(s>(e+1)/(e+u+2))return 1-R1(1-s,u,e);let a=Math.exp(e*Math.log(s)+u*Math.log(1-s)-Mpu(e,u)-Math.log(e)),t=1,r=1-(e+u)*s/(e+1);Math.abs(r)<Vu&&(r=Vu),r=1/r;let i=r;for(let n=1;n<=Tpu;n++){let o=n*(u-n)*s/((e+2*n-1)*(e+2*n));r=1+o*r,Math.abs(r)<Vu&&(r=Vu),t=1+o/t,Math.abs(t)<Vu&&(t=Vu),r=1/r,i*=t*r,o=-(e+n)*(e+u+n)*s/((e+2*n)*(e+2*n+1)),r=1+o*r,Math.abs(r)<Vu&&(r=Vu),t=1+o/t,Math.abs(t)<Vu&&(t=Vu),r=1/r;let l=t*r;if(i*=l,Math.abs(l-1)<Vu)break}return a*i}function Rpu(s,e,u){return s<=0?0:e<=0||u<=0?NaN:isFinite(s)?R1(e*s/(e*s+u),e/2,u/2):1}function Ppu(s,e){let u=e.length,a=s.map((r,i)=>[...r,e[i]]);for(let r=0;r<u;r++){let i=Math.abs(a[r][r]),n=r;for(let o=r+1;o<u;o++){let l=Math.abs(a[o][r]);l>i&&(i=l,n=o)}if(i<Oa)return null;n!==r&&([a[r],a[n]]=[a[n],a[r]]);for(let o=r+1;o<u;o++){let l=a[o][r]/a[r][r];for(let c=r;c<=u;c++)a[o][c]-=l*a[r][c]}}let t=new Array(u).fill(0);for(let r=u-1;r>=0;r--){if(Math.abs(a[r][r])<Oa)return null;let i=a[r][u];for(let n=r+1;n<u;n++)i-=a[r][n]*t[n];t[r]=i/a[r][r]}return t}function T1(s,e){let u=e.length,a=s[0].length,t=Array.from({length:a},()=>new Array(a).fill(0));for(let i=0;i<a;i++)for(let n=i;n<a;n++){let o=0;for(let l=0;l<u;l++)o+=s[l][i]*s[l][n];t[i][n]=o,t[n][i]=o}let r=new Array(a).fill(0);for(let i=0;i<a;i++){let n=0;for(let o=0;o<u;o++)n+=s[o][i]*e[o];r[i]=n}return Ppu(t,r)}function M1(s,e,u){let a=0;for(let t=0;t<e.length;t++){let r=0;for(let n=0;n<u.length;n++)r+=s[t][n]*u[n];let i=e[t]-r;a+=i*i}return a}function zpu(s,e){let u=Math.max(s.timestamps[0]??1/0,e.timestamps[0]??1/0),a=Math.min(s.timestamps[s.timestamps.length-1]??-1/0,e.timestamps[e.timestamps.length-1]??-1/0);if(u>=a)return null;let t=[];for(let l of[s,e])for(let c=1;c<l.timestamps.length;c++){let E=l.timestamps[c]-l.timestamps[c-1];E>0&&t.push(E)}if(t.length===0)return null;t.sort((l,c)=>l-c);let r=t[Math.floor(t.length/2)];if(r<=0)return null;let i=Math.floor((a-u)/r)+1;if(i<2)return null;let n=new Array(i).fill(0),o=new Array(i).fill(0);for(let[l,c]of[[s,n],[e,o]])for(let E=0;E<l.timestamps.length;E++){let d=Math.round((l.timestamps[E]-u)/r);d>=0&&d<i&&(c[d]=l.outcomes[E])}return{sourceOutcomes:n,targetOutcomes:o}}var _a=class{config;constructor(e){this.config={...wpu,...e}}analyzeCausality(e){if(e.length<2)return[];let u=[];for(let a=0;a<e.length;a++)for(let t=0;t<e.length;t++){if(a===t)continue;let r=e[a],i=e[t];if(r.outcomes.length<this.config.minSeriesLength||i.outcomes.length<this.config.minSeriesLength)continue;let n=null;for(let o=1;o<=this.config.maxLag;o++){let l=this.testPairwise(r,i,o);this.significanceTest(l)&&(n===null||l.pValue<n.pValue)&&(n=l)}n&&u.push(n)}return u.sort((a,t)=>a.pValue-t.pValue),u}testPairwise(e,u,a){let t={sourceTestId:e.testId,targetTestId:u.testId,lag:a,fStatistic:0,pValue:1,strength:0,direction:"positive"},r,i;if(this.arraysEqual(e.timestamps,u.timestamps))r=e.outcomes,i=u.outcomes;else{let q=zpu(e,u);if(!q)return t;r=q.sourceOutcomes,i=q.targetOutcomes}let n=i.length,o=n-a,l=o-2*a-1;if(l<=0||o<this.config.minSeriesLength)return t;let c=new Array(o);for(let q=0;q<o;q++)c[q]=i[q+a];let E=c.reduce((q,lu)=>q+lu,0)/c.length;if(c.reduce((q,lu)=>q+(lu-E)**2,0)<Oa)return t;let d=new Array(o);for(let q=0;q<o;q++){let lu=new Array(a+1);lu[0]=1;for(let au=1;au<=a;au++)lu[au]=i[q+a-au];d[q]=lu}let D=new Array(o);for(let q=0;q<o;q++){let lu=new Array(2*a+1);lu[0]=1;for(let au=1;au<=a;au++)lu[au]=i[q+a-au];for(let au=1;au<=a;au++)lu[a+au]=r[q+a-au];D[q]=lu}let h=T1(d,c);if(!h)return t;let C=M1(d,c,h),y=T1(D,c);if(!y)return t;let x=M1(D,c,y);if(x>C)return t;let b=(C-x)/a,R=x/l,w=y.slice(a+1,2*a+1),P=w.reduce((q,lu)=>q+Math.abs(lu),0)/a,X=w.reduce((q,lu)=>q+lu,0)/a>=0?"positive":"negative";if(R<Oa){let q=b>Oa?1e6:0;return{...t,fStatistic:q,pValue:q>0?0:1,strength:P,direction:X}}let Bu=b/R,eu=1-Rpu(Bu,a,l);return{sourceTestId:e.testId,targetTestId:u.testId,lag:a,fStatistic:Math.max(0,Bu),pValue:Math.max(0,Math.min(1,eu)),strength:P,direction:X}}significanceTest(e){return e.pValue<this.config.alpha&&e.fStatistic>0}arraysEqual(e,u){if(e.length!==u.length)return!1;for(let a=0;a<e.length;a++)if(e[a]!==u[a])return!1;return!0}};var Lpu={maxConcurrentWorkflows:5,defaultTimeout:6e4,enablePatternLearning:!0,publishEvents:!0,autoAnalyzeThreshold:.7,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Wa=B.create("defect-intelligence"),Zr=class extends Y{constructor(u,a,t,r={}){let i={...Lpu,...r};super(u,"defect-intelligence",i,{verifyFindingTypes:["defect-prediction","root-cause","regression-risk","pattern-classification"],...i.consensusConfig});this.memory=a;this.agentCoordinator=t;this.predictor=new b0(a),this.patternLearner=new B0(a),this.rootCauseAnalyzer=new k0(a)}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(u){return this.minCutMixin.onTopologyHealthChange(u)}requiresConsensus(u){return this.consensusMixin.requiresConsensus(u)}async verifyFinding(u){return this.consensusMixin.verifyFinding(u)}async predictDefects(u){let a=A();try{if(this.startWorkflow(a,"predict"),this.config.enableMinCutAwareness&&this.minCutMixin.shouldPauseOperations()&&Wa.warn("Topology is critical, proceeding with caution"),!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn prediction agents"));let t=await this.spawnPredictionAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=await this.predictor.predictDefects(u);if(r.success){let i=await this.verifyHighConfidencePredictions(r.value.predictions),n={...r.value,predictions:i};if(this.completeWorkflow(a),this.config.publishEvents&&await this.publishPredictionEvent(n),this.config.enablePatternLearning&&await this.autoAnalyzeHighRisk(n),Te().useGrangerCausality)try{let o=Date.now();for(let c of n.predictions){let E=this.testExecutionHistory.get(c.file)??{timestamps:[],outcomes:[]};E.timestamps.push(o),E.outcomes.push(c.probability>.5?0:1),E.timestamps.length>500&&(E.timestamps.splice(0,E.timestamps.length-500),E.outcomes.splice(0,E.outcomes.length-500)),this.testExecutionHistory.set(c.file,E)}let l=Array.from(this.testExecutionHistory.entries()).filter(([,c])=>c.timestamps.length>=30).map(([c,E])=>({testId:c,timestamps:E.timestamps,outcomes:E.outcomes}));if(l.length>=3){let E=new _a({maxLag:5,alpha:.05}).analyzeCausality(l);E.length>0&&Wa.info("Granger causality found causal links in defect predictions",{linkCount:E.length,historyDepth:l[0].timestamps.length,topLink:`${E[0].sourceTestId} \u2192 ${E[0].targetTestId} (lag=${E[0].lag}, p=${E[0].pValue.toFixed(4)})`})}}catch(o){Wa.warn("Granger causality analysis failed (non-fatal)",{error:o instanceof Error?o.message:"unknown"})}return await this.agentCoordinator.stop(t.value),p(n)}else this.failWorkflow(a,r.error.message);return await this.agentCoordinator.stop(t.value),r}catch(t){let r=g(t);return this.failWorkflow(a,r.message),{success:!1,error:r}}}async verifyHighConfidencePredictions(u){if(!this.config.enableConsensus)return u;let a=[];for(let t of u)if(t.probability>=this.config.consensusThreshold){let r={id:A(),type:"defect-prediction",confidence:t.probability,severity:t.riskLevel==="critical"||t.riskLevel==="high"?t.riskLevel:"medium",description:`Defect prediction for ${t.file}: ${t.probability*100}% probability`,payload:t,detectedAt:new Date,detectedBy:"defect-intelligence-coordinator"};if(this.consensusMixin.requiresConsensus(r))try{let i=await this.consensusMixin.verifyFinding(r);i.success?i.value.verdict==="verified"?a.push({...t,recommendations:[...t.recommendations,"[Consensus Verified] This prediction has been confirmed by multiple AI models."]}):i.value.verdict==="disputed"&&a.push({...t,probability:t.probability*.6,recommendations:[...t.recommendations,"[Consensus Disputed] This prediction requires human review."]}):a.push(t)}catch{Wa.warn(`Consensus verification failed for ${t.file}`),a.push(t)}else a.push(t)}else a.push(t);return a}async analyzeRootCause(u){let a=A();try{this.startWorkflow(a,"analyze");let t=await this.spawnAnalysisAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=await this.rootCauseAnalyzer.analyzeRootCause(u);if(r.success){let i=await this.verifyRootCauseAnalysis(r.value);return this.completeWorkflow(a),this.config.publishEvents&&await this.publishRootCauseEvent(i),await this.agentCoordinator.stop(t.value),p(i)}else this.failWorkflow(a,r.error.message);return await this.agentCoordinator.stop(t.value),r}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async verifyRootCauseAnalysis(u){if(!this.config.enableConsensus||u.confidence<this.config.consensusThreshold)return u;let a={id:A(),type:"root-cause",confidence:u.confidence,severity:"high",description:`Root cause identified for ${u.defectId}: ${u.rootCause}`,payload:u,detectedAt:new Date,detectedBy:"defect-intelligence-coordinator"};if(this.consensusMixin.requiresConsensus(a))try{let t=await this.consensusMixin.verifyFinding(a);if(t.success)return{...u,recommendations:[...u.recommendations,t.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:t.value.verdict==="verified"?Math.min(1,u.confidence*1.1):u.confidence*.7}}catch{Wa.warn("Consensus verification failed for root cause")}return u}async analyzeRegressionRisk(u){let a=A();try{this.startWorkflow(a,"regression");let t=await this.spawnRegressionAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=await this.predictor.analyzeRegressionRisk(u);return r.success?(this.completeWorkflow(a),this.config.publishEvents&&await this.publishRegressionEvent(r.value)):this.failWorkflow(a,r.error.message),await this.agentCoordinator.stop(t.value),r}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async clusterDefects(u){let a=A();try{this.startWorkflow(a,"cluster");let t=await this.patternLearner.clusterDefects(u);return t.success?this.completeWorkflow(a):this.failWorkflow(a,t.error.message),t}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async learnPatterns(u){let a=A();try{this.startWorkflow(a,"learn");let t=await this.patternLearner.learnPatterns(u);return t.success?(this.completeWorkflow(a),this.config.publishEvents&&t.value.modelUpdated&&await this.publishPatternLearnedEvent(t.value)):this.failWorkflow(a,t.error.message),t}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async spawnPredictionAgent(u,a){let t={name:`defect-predictor-${u.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["defect-prediction","ml-analysis"],config:{workflowId:u,files:a.files,threshold:a.threshold}};return this.agentCoordinator.spawn(t)}async spawnAnalysisAgent(u,a){let t={name:`root-cause-analyzer-${u.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["root-cause-analysis","symptom-analysis"],config:{workflowId:u,defectId:a.defectId,symptoms:a.symptoms}};return this.agentCoordinator.spawn(t)}async spawnRegressionAgent(u,a){let t={name:`regression-analyzer-${u.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["regression-analysis","impact-analysis"],config:{workflowId:u,changeset:a.changeset,depth:a.depth}};return this.agentCoordinator.spawn(t)}async publishPredictionEvent(u){for(let a of u.predictions)if(a.probability>=this.config.autoAnalyzeThreshold){let t=L(Dt.DefectPredicted,"defect-intelligence",{predictionId:A(),file:a.file,probability:a.probability,factors:a.factors.map(r=>r.name),recommendations:a.recommendations});await this.eventBus.publish(t)}}async publishRootCauseEvent(u){let a=L(Dt.RootCauseIdentified,"defect-intelligence",{analysisId:A(),defectId:u.defectId,rootCause:u.rootCause,confidence:u.confidence,relatedFiles:u.relatedFiles});await this.eventBus.publish(a)}async publishRegressionEvent(u){let a=L(Dt.RegressionRiskAnalyzed,"defect-intelligence",{riskLevel:u.riskLevel,overallRisk:u.overallRisk,impactedAreas:u.impactedAreas.length,recommendedTests:u.recommendedTests.length});await this.eventBus.publish(a)}async publishPatternLearnedEvent(u){let a=L("defect-intelligence.PatternLearned","defect-intelligence",{patternCount:u.patterns.length,modelUpdated:u.modelUpdated,improvementEstimate:u.improvementEstimate});await this.eventBus.publish(a)}async handleTestRunCompleted(u){let a=u.payload;a.failed>0&&this.config.enablePatternLearning&&await this.memory.set(`defect-intelligence:failed-tests:${Date.now()}`,{timestamp:new Date().toISOString(),failedCount:a.failed,testIds:a.testIds},{namespace:"defect-intelligence",ttl:86400*7})}async handleImpactAnalysis(u){let a=u.payload;a.changedFiles.length>3&&await this.analyzeRegressionRisk({changeset:a.changedFiles,depth:"shallow"})}async autoAnalyzeHighRisk(u){let a=u.predictions.filter(t=>t.probability>=this.config.autoAnalyzeThreshold);for(let t of a.slice(0,3))await this.memory.set(`defect-intelligence:high-risk:${t.file}`,{file:t.file,probability:t.probability,factors:t.factors,detectedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400})}async loadWorkflowState(){let u=await this.memory.get("defect-intelligence:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("defect-intelligence:coordinator:workflows",u,{namespace:"defect-intelligence",persist:!0})}};S();var tl=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.files,t=u.threshold;return!a||a.length===0?m(new Error("Invalid predict-defects payload: missing files")):this.coordinator.predictDefects({files:a,threshold:t??.7})}],["analyze-root-cause",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.defectId;if(!a)return m(new Error("Invalid analyze-root-cause payload: missing defectId"));let t=u.stackTrace?[u.stackTrace]:u.symptoms??[];return this.coordinator.analyzeRootCause({defectId:a,symptoms:t,context:u.context})}],["analyze-regression-risk",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.changedFiles;return!a||a.length===0?m(new Error("Invalid analyze-regression-risk payload: missing changedFiles")):this.coordinator.analyzeRegressionRisk({changeset:a,baseline:u.commitHash})}],["cluster-defects",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.defects;return!a||a.length===0?m(new Error("Invalid cluster-defects payload: missing defects")):this.coordinator.clusterDefects({defects:a.map(t=>({id:t.id,title:t.title??`Defect ${t.id}`,description:t.description??""})),method:u.method??"semantic"})}],["learn-patterns",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.defectHistory,t=u.defects,r=a??t;return!r||r.length===0?m(new Error("Invalid learn-patterns payload: missing defectHistory")):this.coordinator.learnPatterns({defects:r.map(i=>({id:i.id,title:i.title??`Defect ${i.id}`,description:i.description??""})),includeResolutions:u.includeResolutions})}]])}async onInitialize(){this.predictor=new b0(this.memory,this.pluginConfig.predictor),this.patternLearner=new B0(this.memory,this.pluginConfig.patternLearner),this.rootCauseAnalyzer=new k0(this.memory,this.pluginConfig.rootCauseAnalyzer),this.coordinator=new Zr(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"test-execution.FlakyTestDetected":await this.handleFlakyTest(u);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(u);break;case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(u);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(u);break;default:break}}async predictDefects(u){this.ensureInitialized();try{let a=await this.coordinator.predictDefects(u);return a.success?this.trackSuccessfulOperation("predict"):this.trackFailedOperation(a.error),a}catch(a){return this.handleError(a)}}async analyzeRootCause(u){this.ensureInitialized();try{let a=await this.coordinator.analyzeRootCause(u);return a.success?this.trackSuccessfulOperation("analyze"):this.trackFailedOperation(a.error),a}catch(a){return this.handleError(a)}}async analyzeRegressionRisk(u){this.ensureInitialized();try{return await this.coordinator.analyzeRegressionRisk(u)}catch(a){return this.handleError(a)}}async clusterDefects(u){this.ensureInitialized();try{return await this.coordinator.clusterDefects(u)}catch(a){return this.handleError(a)}}async learnPatterns(u){this.ensureInitialized();try{let a=await this.coordinator.learnPatterns(u);return a.success&&this.trackSuccessfulOperation("learn"),a}catch(a){return this.handleError(a)}}async handleFlakyTest(u){let a=u.payload;await this.memory.set(`defect-intelligence:flaky-test:${a.testId}`,{...a,detectedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*30}),a.failureRate>.3&&a.testFile&&await this.coordinator?.predictDefects({files:[a.testFile],threshold:.5})}async handleCoverageGap(u){let a=u.payload;a.riskScore>=.7&&await this.memory.set(`defect-intelligence:coverage-gap:${a.gapId}`,{...a,analyzedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}async handleImpactAnalysis(u){let a=u.payload;await this.memory.set(`defect-intelligence:impact:${a.analysisId}`,{...a,recordedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400})}async handleQualityGate(u){let a=u.payload;if(!a.passed){let t=a.checks.filter(r=>!r.passed);await this.memory.set(`defect-intelligence:quality-failure:${a.gateId}`,{failedChecks:t.map(r=>r.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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}};function P1(s,e,u,a){return new tl(s,e,u,a)}N();S();N();S();J();var Npu={enableAmbiguityDetection:!0,minAcceptanceCriteria:1,strictMode:!1,forbiddenTermsDefault:[],enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},rl={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"]},z1=B.create("requirements-validation/requirements-validator"),S0=class{config;memory;llmRouter;constructor(e,u={}){this.config={...Npu,...u},"memory"in e&&typeof e.memory=="object"?(this.memory=e.memory,this.llmRouter=e.llmRouter):this.memory=e}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-sonnet-4-20250514"}}async analyzeRequirementsWithLLM(e,u){if(!this.isLLMAnalysisAvailable())return p(this.getBasicAnalysis(e));try{let a=this.getModelForTier(this.config.llmModelTier??2),t=this.buildRequirementsAnalysisPrompt(e,u),r=await this.llmRouter.chat({messages:[{role:"system",content:`You are a senior requirements engineer and QA specialist. Analyze requirements for:
2820
+ \`\`\``:C.description),...E.preventionStrategies];return await this.storeAnalysis({defectId:u,rootCause:E.rootCause,category:"llm-analyzed",confidence:.85,symptoms:a,timestamp:new Date}),p({defectId:u,rootCause:E.rootCause,confidence:.85,contributingFactors:E.contributingFactors,relatedFiles:d,recommendations:h,timeline:D.success?D.value:[]})}}let r=this.identifyRootCauseCategory(a),i=this.calculateConfidence(r,a);if(i<this.config.minConfidenceThreshold)return p({defectId:u,rootCause:"Unable to determine root cause with sufficient confidence",confidence:i,contributingFactors:[],relatedFiles:[],recommendations:["Provide more symptoms for better analysis"],timeline:[]});let n=await this.identifyContributingFactors(r.category,a,t),o=await this.findRelatedFiles(u,a),l=this.generateRecommendations(r,n),c=await this.generateTimeline(u);return await this.storeAnalysis({defectId:u,rootCause:r.rootCause,category:r.category,confidence:i,symptoms:a,timestamp:new Date}),p({defectId:u,rootCause:r.rootCause,confidence:i,contributingFactors:n,relatedFiles:o,recommendations:l,timeline:c.success?c.value:[]})}catch(u){return m(g(u))}}async findRelatedDefects(e){try{let u=await this.memory.get(`${this.config.analyzerNamespace}:analysis:${e}`);if(!u)return p([]);let a=await this.memory.search(`${this.config.analyzerNamespace}:analysis:*`,50),t=[];for(let r of a){let i=await this.memory.get(r);i&&i.defectId!==e&&i.category===u.category&&t.push(i.defectId)}return p(t)}catch(u){return m(g(u))}}async generateTimeline(e){try{let u=[],a=`${this.config.analyzerNamespace}:events:${e}`,t=await this.memory.get(a);t&&u.push(...t);let r=await this.memory.search("code-intelligence:change:*",this.config.maxTimelineEvents);for(let n of r){let o=await this.memory.get(n);o&&u.push({timestamp:new Date(o.timestamp),event:`Code change: ${o.description}`,relevance:.5})}let i=u.sort((n,o)=>o.timestamp.getTime()-n.timestamp.getTime()).slice(0,this.config.maxTimelineEvents);return p(i)}catch(u){return m(g(u))}}async suggestRemediation(e){let u=[];for(let[a,t]of Object.entries(Jr))(e.toLowerCase().includes(a)||t.causes.some(r=>e.toLowerCase().includes(r.toLowerCase())))&&u.push(...t.remediation);return u.length===0&&(u.push("Review the affected code thoroughly"),u.push("Add tests to prevent regression"),u.push("Document the fix for future reference")),[...new Set(u)]}identifyRootCauseCategory(e){let u={category:"unknown",rootCause:"Undetermined root cause",matchScore:0},a=e.join(" ").toLowerCase();for(let[t,r]of Object.entries(Jr)){let i=0;for(let n of r.symptoms)a.includes(n.toLowerCase())&&(i+=1);if(i=i/r.symptoms.length,i>u.matchScore){let n=this.selectLikelyCause(r.causes,a);u={category:t,rootCause:n,matchScore:i}}}return u}selectLikelyCause(e,u){let a=e[0],t=0;for(let r of e){let i=r.toLowerCase().split(/\s+/),n=0;for(let o of i)o.length>3&&u.includes(o)&&(n+=1);n>t&&(t=n,a=r)}return a}calculateConfidence(e,u){let a=e.matchScore;return u.length>=3?a*=1.1:u.length===1&&(a*=.8),Math.min(1,Math.max(0,a))}async identifyContributingFactors(e,u,a){let t=[],r=Jr[e];if(!r)return t;t.push({factor:`Category: ${e}`,impact:r.impact,evidence:u.slice(0,3)}),a.recentChanges&&t.push({factor:"Recent code changes",impact:"high",evidence:["Code was recently modified"]}),a.highTraffic&&t.push({factor:"High traffic conditions",impact:"medium",evidence:["Occurred during peak load"]}),a.environment&&t.push({factor:`Environment: ${a.environment}`,impact:"medium",evidence:[`Observed in ${a.environment} environment`]});let i=await this.getHistoricalFactors(e);return t.push(...i),t}async getHistoricalFactors(e){let u=[],a=`${this.config.analyzerNamespace}:history:${e}`,t=await this.memory.get(a);return t&&t.occurrences>1&&u.push({factor:"Recurring issue pattern",impact:"high",evidence:[`Similar issues occurred ${t.occurrences} times`,...t.commonFactors.slice(0,2)]}),u}async findRelatedFiles(e,u){let a=new Set;for(let r of u){let i=r.match(/[\w\-]+\.(ts|js|tsx|jsx|py|java|go)/g);i&&i.forEach(o=>a.add(o));let n=r.match(/(?:src|lib|app)\/[\w\/\-]+/g);n&&n.forEach(o=>a.add(o))}let t=await this.memory.search("code-intelligence:file:*",this.config.maxRelatedFiles);for(let r of t.slice(0,this.config.maxRelatedFiles-a.size)){let i=await this.memory.get(r);i&&a.add(i.path)}return Array.from(a).slice(0,this.config.maxRelatedFiles)}generateRecommendations(e,u){let a=[],t=Jr[e.category];t&&a.push(...t.remediation);for(let r of u)r.impact==="high"&&a.push(`Address: ${r.factor}`);return a.push("Add regression tests for this scenario"),a.push("Document the root cause and fix"),[...new Set(a)].slice(0,8)}async storeAnalysis(e){await this.memory.set(`${this.config.analyzerNamespace}:analysis:${e.defectId}`,e,{namespace:"defect-intelligence",persist:!0});let u=`${this.config.analyzerNamespace}:history:${e.category}`,a=await this.memory.get(u)||{occurrences:0,commonFactors:[]};a.occurrences+=1;for(let t of e.symptoms.slice(0,2))a.commonFactors.includes(t)||a.commonFactors.push(t);a.commonFactors=a.commonFactors.slice(0,10),await this.memory.set(u,a,{namespace:"defect-intelligence",persist:!0})}};Qu();var wpu={maxLag:5,alpha:.05,minSeriesLength:30},Tpu=200,Vu=1e-10,Oa=1e-12;function Ur(s){if(s<=0)return 1/0;let e=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,15056327351493116e-23];if(s<.5)return Math.log(Math.PI/Math.sin(Math.PI*s))-Ur(1-s);s-=1;let u=e[0];for(let t=1;t<9;t++)u+=e[t]/(s+t);let a=s+7.5;return .5*Math.log(2*Math.PI)+(s+.5)*Math.log(a)-a+Math.log(u)}function Mpu(s,e){return Ur(s)+Ur(e)-Ur(s+e)}function R1(s,e,u){if(s<=0)return 0;if(s>=1)return 1;if(e<=0||u<=0)return NaN;if(s>(e+1)/(e+u+2))return 1-R1(1-s,u,e);let a=Math.exp(e*Math.log(s)+u*Math.log(1-s)-Mpu(e,u)-Math.log(e)),t=1,r=1-(e+u)*s/(e+1);Math.abs(r)<Vu&&(r=Vu),r=1/r;let i=r;for(let n=1;n<=Tpu;n++){let o=n*(u-n)*s/((e+2*n-1)*(e+2*n));r=1+o*r,Math.abs(r)<Vu&&(r=Vu),t=1+o/t,Math.abs(t)<Vu&&(t=Vu),r=1/r,i*=t*r,o=-(e+n)*(e+u+n)*s/((e+2*n)*(e+2*n+1)),r=1+o*r,Math.abs(r)<Vu&&(r=Vu),t=1+o/t,Math.abs(t)<Vu&&(t=Vu),r=1/r;let l=t*r;if(i*=l,Math.abs(l-1)<Vu)break}return a*i}function Rpu(s,e,u){return s<=0?0:e<=0||u<=0?NaN:isFinite(s)?R1(e*s/(e*s+u),e/2,u/2):1}function Ppu(s,e){let u=e.length,a=s.map((r,i)=>[...r,e[i]]);for(let r=0;r<u;r++){let i=Math.abs(a[r][r]),n=r;for(let o=r+1;o<u;o++){let l=Math.abs(a[o][r]);l>i&&(i=l,n=o)}if(i<Oa)return null;n!==r&&([a[r],a[n]]=[a[n],a[r]]);for(let o=r+1;o<u;o++){let l=a[o][r]/a[r][r];for(let c=r;c<=u;c++)a[o][c]-=l*a[r][c]}}let t=new Array(u).fill(0);for(let r=u-1;r>=0;r--){if(Math.abs(a[r][r])<Oa)return null;let i=a[r][u];for(let n=r+1;n<u;n++)i-=a[r][n]*t[n];t[r]=i/a[r][r]}return t}function T1(s,e){let u=e.length,a=s[0].length,t=Array.from({length:a},()=>new Array(a).fill(0));for(let i=0;i<a;i++)for(let n=i;n<a;n++){let o=0;for(let l=0;l<u;l++)o+=s[l][i]*s[l][n];t[i][n]=o,t[n][i]=o}let r=new Array(a).fill(0);for(let i=0;i<a;i++){let n=0;for(let o=0;o<u;o++)n+=s[o][i]*e[o];r[i]=n}return Ppu(t,r)}function M1(s,e,u){let a=0;for(let t=0;t<e.length;t++){let r=0;for(let n=0;n<u.length;n++)r+=s[t][n]*u[n];let i=e[t]-r;a+=i*i}return a}function zpu(s,e){let u=Math.max(s.timestamps[0]??1/0,e.timestamps[0]??1/0),a=Math.min(s.timestamps[s.timestamps.length-1]??-1/0,e.timestamps[e.timestamps.length-1]??-1/0);if(u>=a)return null;let t=[];for(let l of[s,e])for(let c=1;c<l.timestamps.length;c++){let E=l.timestamps[c]-l.timestamps[c-1];E>0&&t.push(E)}if(t.length===0)return null;t.sort((l,c)=>l-c);let r=t[Math.floor(t.length/2)];if(r<=0)return null;let i=Math.floor((a-u)/r)+1;if(i<2)return null;let n=new Array(i).fill(0),o=new Array(i).fill(0);for(let[l,c]of[[s,n],[e,o]])for(let E=0;E<l.timestamps.length;E++){let d=Math.round((l.timestamps[E]-u)/r);d>=0&&d<i&&(c[d]=l.outcomes[E])}return{sourceOutcomes:n,targetOutcomes:o}}var _a=class{config;constructor(e){this.config={...wpu,...e}}analyzeCausality(e){if(e.length<2)return[];let u=[];for(let a=0;a<e.length;a++)for(let t=0;t<e.length;t++){if(a===t)continue;let r=e[a],i=e[t];if(r.outcomes.length<this.config.minSeriesLength||i.outcomes.length<this.config.minSeriesLength)continue;let n=null;for(let o=1;o<=this.config.maxLag;o++){let l=this.testPairwise(r,i,o);this.significanceTest(l)&&(n===null||l.pValue<n.pValue)&&(n=l)}n&&u.push(n)}return u.sort((a,t)=>a.pValue-t.pValue),u}testPairwise(e,u,a){let t={sourceTestId:e.testId,targetTestId:u.testId,lag:a,fStatistic:0,pValue:1,strength:0,direction:"positive"},r,i;if(this.arraysEqual(e.timestamps,u.timestamps))r=e.outcomes,i=u.outcomes;else{let q=zpu(e,u);if(!q)return t;r=q.sourceOutcomes,i=q.targetOutcomes}let n=i.length,o=n-a,l=o-2*a-1;if(l<=0||o<this.config.minSeriesLength)return t;let c=new Array(o);for(let q=0;q<o;q++)c[q]=i[q+a];let E=c.reduce((q,lu)=>q+lu,0)/c.length;if(c.reduce((q,lu)=>q+(lu-E)**2,0)<Oa)return t;let d=new Array(o);for(let q=0;q<o;q++){let lu=new Array(a+1);lu[0]=1;for(let au=1;au<=a;au++)lu[au]=i[q+a-au];d[q]=lu}let D=new Array(o);for(let q=0;q<o;q++){let lu=new Array(2*a+1);lu[0]=1;for(let au=1;au<=a;au++)lu[au]=i[q+a-au];for(let au=1;au<=a;au++)lu[a+au]=r[q+a-au];D[q]=lu}let h=T1(d,c);if(!h)return t;let C=M1(d,c,h),y=T1(D,c);if(!y)return t;let x=M1(D,c,y);if(x>C)return t;let b=(C-x)/a,R=x/l,w=y.slice(a+1,2*a+1),P=w.reduce((q,lu)=>q+Math.abs(lu),0)/a,X=w.reduce((q,lu)=>q+lu,0)/a>=0?"positive":"negative";if(R<Oa){let q=b>Oa?1e6:0;return{...t,fStatistic:q,pValue:q>0?0:1,strength:P,direction:X}}let Bu=b/R,eu=1-Rpu(Bu,a,l);return{sourceTestId:e.testId,targetTestId:u.testId,lag:a,fStatistic:Math.max(0,Bu),pValue:Math.max(0,Math.min(1,eu)),strength:P,direction:X}}significanceTest(e){return e.pValue<this.config.alpha&&e.fStatistic>0}arraysEqual(e,u){if(e.length!==u.length)return!1;for(let a=0;a<e.length;a++)if(e[a]!==u[a])return!1;return!0}};var Lpu={maxConcurrentWorkflows:5,defaultTimeout:6e4,enablePatternLearning:!0,publishEvents:!0,autoAnalyzeThreshold:.7,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Wa=B.create("defect-intelligence"),Zr=class extends Y{constructor(u,a,t,r={}){let i={...Lpu,...r};super(u,"defect-intelligence",i,{verifyFindingTypes:["defect-prediction","root-cause","regression-risk","pattern-classification"],...i.consensusConfig});this.memory=a;this.agentCoordinator=t;this.predictor=new b0(a),this.patternLearner=new B0(a),this.rootCauseAnalyzer=new k0(a)}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(u){return this.minCutMixin.onTopologyHealthChange(u)}requiresConsensus(u){return this.consensusMixin.requiresConsensus(u)}async verifyFinding(u){return this.consensusMixin.verifyFinding(u)}async predictDefects(u){let a=A();try{if(this.startWorkflow(a,"predict"),this.config.enableMinCutAwareness&&this.minCutMixin.shouldPauseOperations()&&Wa.warn("Topology is critical, proceeding with caution"),!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn prediction agents"));let t=await this.spawnPredictionAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=await this.predictor.predictDefects(u);if(r.success){let i=await this.verifyHighConfidencePredictions(r.value.predictions),n={...r.value,predictions:i};if(this.completeWorkflow(a),this.config.publishEvents&&await this.publishPredictionEvent(n),this.config.enablePatternLearning&&await this.autoAnalyzeHighRisk(n),Te().useGrangerCausality)try{let o=Date.now();for(let c of n.predictions){let E=this.testExecutionHistory.get(c.file)??{timestamps:[],outcomes:[]};E.timestamps.push(o),E.outcomes.push(c.probability>.5?0:1),E.timestamps.length>500&&(E.timestamps.splice(0,E.timestamps.length-500),E.outcomes.splice(0,E.outcomes.length-500)),this.testExecutionHistory.set(c.file,E)}let l=Array.from(this.testExecutionHistory.entries()).filter(([,c])=>c.timestamps.length>=30).map(([c,E])=>({testId:c,timestamps:E.timestamps,outcomes:E.outcomes}));if(l.length>=3){let E=new _a({maxLag:5,alpha:.05}).analyzeCausality(l);E.length>0&&Wa.info("Granger causality found causal links in defect predictions",{linkCount:E.length,historyDepth:l[0].timestamps.length,topLink:`${E[0].sourceTestId} \u2192 ${E[0].targetTestId} (lag=${E[0].lag}, p=${E[0].pValue.toFixed(4)})`})}}catch(o){Wa.warn("Granger causality analysis failed (non-fatal)",{error:o instanceof Error?o.message:"unknown"})}return await this.agentCoordinator.stop(t.value),p(n)}else this.failWorkflow(a,r.error.message);return await this.agentCoordinator.stop(t.value),r}catch(t){let r=g(t);return this.failWorkflow(a,r.message),{success:!1,error:r}}}async verifyHighConfidencePredictions(u){if(!this.config.enableConsensus)return u;let a=[];for(let t of u)if(t.probability>=this.config.consensusThreshold){let r={id:A(),type:"defect-prediction",confidence:t.probability,severity:t.riskLevel==="critical"||t.riskLevel==="high"?t.riskLevel:"medium",description:`Defect prediction for ${t.file}: ${t.probability*100}% probability`,payload:t,detectedAt:new Date,detectedBy:"defect-intelligence-coordinator"};if(this.consensusMixin.requiresConsensus(r))try{let i=await this.consensusMixin.verifyFinding(r);i.success?i.value.verdict==="verified"?a.push({...t,recommendations:[...t.recommendations,"[Consensus Verified] This prediction has been confirmed by multiple AI models."]}):i.value.verdict==="disputed"&&a.push({...t,probability:t.probability*.6,recommendations:[...t.recommendations,"[Consensus Disputed] This prediction requires human review."]}):a.push(t)}catch{Wa.warn(`Consensus verification failed for ${t.file}`),a.push(t)}else a.push(t)}else a.push(t);return a}async analyzeRootCause(u){let a=A();try{this.startWorkflow(a,"analyze");let t=await this.spawnAnalysisAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=await this.rootCauseAnalyzer.analyzeRootCause(u);if(r.success){let i=await this.verifyRootCauseAnalysis(r.value);return this.completeWorkflow(a),this.config.publishEvents&&await this.publishRootCauseEvent(i),await this.agentCoordinator.stop(t.value),p(i)}else this.failWorkflow(a,r.error.message);return await this.agentCoordinator.stop(t.value),r}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async verifyRootCauseAnalysis(u){if(!this.config.enableConsensus||u.confidence<this.config.consensusThreshold)return u;let a={id:A(),type:"root-cause",confidence:u.confidence,severity:"high",description:`Root cause identified for ${u.defectId}: ${u.rootCause}`,payload:u,detectedAt:new Date,detectedBy:"defect-intelligence-coordinator"};if(this.consensusMixin.requiresConsensus(a))try{let t=await this.consensusMixin.verifyFinding(a);if(t.success)return{...u,recommendations:[...u.recommendations,t.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:t.value.verdict==="verified"?Math.min(1,u.confidence*1.1):u.confidence*.7}}catch{Wa.warn("Consensus verification failed for root cause")}return u}async analyzeRegressionRisk(u){let a=A();try{this.startWorkflow(a,"regression");let t=await this.spawnRegressionAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=await this.predictor.analyzeRegressionRisk(u);return r.success?(this.completeWorkflow(a),this.config.publishEvents&&await this.publishRegressionEvent(r.value)):this.failWorkflow(a,r.error.message),await this.agentCoordinator.stop(t.value),r}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async clusterDefects(u){let a=A();try{this.startWorkflow(a,"cluster");let t=await this.patternLearner.clusterDefects(u);return t.success?this.completeWorkflow(a):this.failWorkflow(a,t.error.message),t}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async learnPatterns(u){let a=A();try{this.startWorkflow(a,"learn");let t=await this.patternLearner.learnPatterns(u);return t.success?(this.completeWorkflow(a),this.config.publishEvents&&t.value.modelUpdated&&await this.publishPatternLearnedEvent(t.value)):this.failWorkflow(a,t.error.message),t}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async spawnPredictionAgent(u,a){let t={name:`defect-predictor-${u.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["defect-prediction","ml-analysis"],config:{workflowId:u,files:a.files,threshold:a.threshold}};return this.agentCoordinator.spawn(t)}async spawnAnalysisAgent(u,a){let t={name:`root-cause-analyzer-${u.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["root-cause-analysis","symptom-analysis"],config:{workflowId:u,defectId:a.defectId,symptoms:a.symptoms}};return this.agentCoordinator.spawn(t)}async spawnRegressionAgent(u,a){let t={name:`regression-analyzer-${u.slice(0,8)}`,domain:"defect-intelligence",type:"analyzer",capabilities:["regression-analysis","impact-analysis"],config:{workflowId:u,changeset:a.changeset,depth:a.depth}};return this.agentCoordinator.spawn(t)}async publishPredictionEvent(u){for(let a of u.predictions)if(a.probability>=this.config.autoAnalyzeThreshold){let t=L(Dt.DefectPredicted,"defect-intelligence",{predictionId:A(),file:a.file,probability:a.probability,factors:a.factors.map(r=>r.name),recommendations:a.recommendations});await this.eventBus.publish(t)}}async publishRootCauseEvent(u){let a=L(Dt.RootCauseIdentified,"defect-intelligence",{analysisId:A(),defectId:u.defectId,rootCause:u.rootCause,confidence:u.confidence,relatedFiles:u.relatedFiles});await this.eventBus.publish(a)}async publishRegressionEvent(u){let a=L(Dt.RegressionRiskAnalyzed,"defect-intelligence",{riskLevel:u.riskLevel,overallRisk:u.overallRisk,impactedAreas:u.impactedAreas.length,recommendedTests:u.recommendedTests.length});await this.eventBus.publish(a)}async publishPatternLearnedEvent(u){let a=L("defect-intelligence.PatternLearned","defect-intelligence",{patternCount:u.patterns.length,modelUpdated:u.modelUpdated,improvementEstimate:u.improvementEstimate});await this.eventBus.publish(a)}async handleTestRunCompleted(u){let a=u.payload;a.failed>0&&this.config.enablePatternLearning&&await this.memory.set(`defect-intelligence:failed-tests:${Date.now()}`,{timestamp:new Date().toISOString(),failedCount:a.failed,testIds:a.testIds},{namespace:"defect-intelligence",ttl:86400*7})}async handleImpactAnalysis(u){let a=u.payload;a.changedFiles.length>3&&await this.analyzeRegressionRisk({changeset:a.changedFiles,depth:"shallow"})}async autoAnalyzeHighRisk(u){let a=u.predictions.filter(t=>t.probability>=this.config.autoAnalyzeThreshold);for(let t of a.slice(0,3))await this.memory.set(`defect-intelligence:high-risk:${t.file}`,{file:t.file,probability:t.probability,factors:t.factors,detectedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400})}async loadWorkflowState(){let u=await this.memory.get("defect-intelligence:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("defect-intelligence:coordinator:workflows",u,{namespace:"defect-intelligence",persist:!0})}};S();var tl=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.files,t=u.threshold;return!a||a.length===0?m(new Error("Invalid predict-defects payload: missing files")):this.coordinator.predictDefects({files:a,threshold:t??.7})}],["analyze-root-cause",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.defectId;if(!a)return m(new Error("Invalid analyze-root-cause payload: missing defectId"));let t=u.stackTrace?[u.stackTrace]:u.symptoms??[];return this.coordinator.analyzeRootCause({defectId:a,symptoms:t,context:u.context})}],["analyze-regression-risk",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.changedFiles;return!a||a.length===0?m(new Error("Invalid analyze-regression-risk payload: missing changedFiles")):this.coordinator.analyzeRegressionRisk({changeset:a,baseline:u.commitHash})}],["cluster-defects",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.defects;return!a||a.length===0?m(new Error("Invalid cluster-defects payload: missing defects")):this.coordinator.clusterDefects({defects:a.map(t=>({id:t.id,title:t.title??`Defect ${t.id}`,description:t.description??""})),method:u.method??"semantic"})}],["learn-patterns",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.defectHistory,t=u.defects,r=a??t;return!r||r.length===0?m(new Error("Invalid learn-patterns payload: missing defectHistory")):this.coordinator.learnPatterns({defects:r.map(i=>({id:i.id,title:i.title??`Defect ${i.id}`,description:i.description??""})),includeResolutions:u.includeResolutions})}]])}async onInitialize(){this.predictor=new b0(this.memory,this.pluginConfig.predictor),this.patternLearner=new B0(this.memory,this.pluginConfig.patternLearner),this.rootCauseAnalyzer=new k0(this.memory,this.pluginConfig.rootCauseAnalyzer),this.coordinator=new Zr(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"test-execution.FlakyTestDetected":await this.handleFlakyTest(u);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(u);break;case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(u);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(u);break;default:break}}async predictDefects(u){this.ensureInitialized();try{let a=await this.coordinator.predictDefects(u);return a.success?this.trackSuccessfulOperation("predict"):this.trackFailedOperation(a.error),a}catch(a){return this.handleError(a)}}async analyzeRootCause(u){this.ensureInitialized();try{let a=await this.coordinator.analyzeRootCause(u);return a.success?this.trackSuccessfulOperation("analyze"):this.trackFailedOperation(a.error),a}catch(a){return this.handleError(a)}}async analyzeRegressionRisk(u){this.ensureInitialized();try{return await this.coordinator.analyzeRegressionRisk(u)}catch(a){return this.handleError(a)}}async clusterDefects(u){this.ensureInitialized();try{return await this.coordinator.clusterDefects(u)}catch(a){return this.handleError(a)}}async learnPatterns(u){this.ensureInitialized();try{let a=await this.coordinator.learnPatterns(u);return a.success&&this.trackSuccessfulOperation("learn"),a}catch(a){return this.handleError(a)}}async handleFlakyTest(u){let a=u.payload;await this.memory.set(`defect-intelligence:flaky-test:${a.testId}`,{...a,detectedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*30}),a.failureRate>.3&&a.testFile&&await this.coordinator?.predictDefects({files:[a.testFile],threshold:.5})}async handleCoverageGap(u){let a=u.payload;a.riskScore>=.7&&await this.memory.set(`defect-intelligence:coverage-gap:${a.gapId}`,{...a,analyzedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}async handleImpactAnalysis(u){let a=u.payload;await this.memory.set(`defect-intelligence:impact:${a.analysisId}`,{...a,recordedAt:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400})}async handleQualityGate(u){let a=u.payload;if(!a.passed){let t=a.checks.filter(r=>!r.passed);await this.memory.set(`defect-intelligence:quality-failure:${a.gateId}`,{failedChecks:t.map(r=>r.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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}};function P1(s,e,u,a){return new tl(s,e,u,a)}N();S();N();S();J();var Npu={enableAmbiguityDetection:!0,minAcceptanceCriteria:1,strictMode:!1,forbiddenTermsDefault:[],enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},rl={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"]},z1=B.create("requirements-validation/requirements-validator"),S0=class{config;memory;llmRouter;constructor(e,u={}){this.config={...Npu,...u},"memory"in e&&typeof e.memory=="object"?(this.memory=e.memory,this.llmRouter=e.llmRouter):this.memory=e}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(e){switch(e){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(e,u){if(!this.isLLMAnalysisAvailable())return p(this.getBasicAnalysis(e));try{let a=this.getModelForTier(this.config.llmModelTier??2),t=this.buildRequirementsAnalysisPrompt(e,u),r=await this.llmRouter.chat({messages:[{role:"system",content:`You are a senior requirements engineer and QA specialist. Analyze requirements for:
2821
2821
  1. Completeness - Are all necessary details present?
2822
2822
  2. Testability - Can acceptance criteria be converted to test cases?
2823
2823
  3. Ambiguity - Are there vague terms that need clarification?
@@ -2896,11 +2896,11 @@ Please analyze these requirements for:
2896
2896
  `).map(t=>t.trim()).filter(t=>t.length>0&&Au(t));if(a.length>0){let t=0;for(let r of a)t+=V1(r);return ti(t,"jest",s)}return qa(s,e)}catch{return qa(s,e)}}function cgu(s,e){try{let a=Ja("cargo test --list",{cwd:s,encoding:"utf-8",timeout:e.timeout}).split(`
2897
2897
  `).filter(o=>o.endsWith(": test")),t=a.length,r=a.filter(o=>!o.includes("integration")&&!o.includes("e2e")).length,i=a.filter(o=>o.includes("integration")).length,n=a.filter(o=>o.includes("e2e")).length;return{total:t,unit:r,integration:i,e2e:n,source:"cargo"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"cargo"}}}function Egu(s,e){try{let a=Ja("pytest --collect-only -q",{cwd:s,encoding:"utf-8",timeout:e.timeout}).split(`
2898
2898
  `).filter(o=>o.includes("::test_")||o.includes("::Test")),t=a.length,r=a.filter(o=>o.includes("unit")||!o.includes("integration")&&!o.includes("e2e")).length,i=a.filter(o=>o.includes("integration")||o.includes("_integration")).length,n=a.filter(o=>o.includes("e2e")||o.includes("end_to_end")).length;return{total:t,unit:r-i-n,integration:i,e2e:n,source:"pytest"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"pytest"}}}function dgu(s,e){try{let a=Ja('go test -list ".*" ./...',{cwd:s,encoding:"utf-8",timeout:e.timeout}).split(`
2899
- `).filter(o=>o.startsWith("Test")||o.startsWith("Example")||o.startsWith("Benchmark")),t=a.filter(o=>o.startsWith("Test")).length,r=a.filter(o=>o.startsWith("Test")&&!o.includes("Integration")&&!o.includes("E2E")).length,i=a.filter(o=>o.includes("Integration")).length,n=a.filter(o=>o.includes("E2E")).length;return{total:t,unit:r,integration:i,e2e:n,source:"go"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"go"}}}function qa(s,e){let u=0,a=0,t=0,r=0;function i(n){if(!Au(n))return;let o=ngu(n,{withFileTypes:!0});for(let l of o){let c=vu(n,l.name);if(l.isDirectory()){if(e.excludeDirs.includes(l.name))continue;i(c)}else if(l.isFile()&&mgu(l.name)){let E=ogu(l.name).toLowerCase(),d=0;[".ts",".tsx",".js",".jsx",".mjs"].includes(E)?d=V1(c):E===".py"?d=Dgu(c):E===".rs"?d=hgu(c):E===".go"&&(d=pgu(c)),u+=d;let D=c.toLowerCase();D.includes("e2e")||D.includes("end-to-end")?r+=d:D.includes("integration")?t+=d:a+=d}}}return i(s),{total:u,unit:a,integration:t,e2e:r,source:"fallback"}}function mgu(s){let e=s.toLowerCase();return e.includes(".test.")||e.includes(".spec.")||e.includes("_test.")||e.startsWith("test_")||e.endsWith("_test.ts")||e.endsWith("_test.js")||e.endsWith("_test.py")||e.endsWith("_test.go")||e.endsWith("_test.rs")}function V1(s){try{let e=Ua(s,"utf-8"),u=e.match(/\bit\s*\(/g)||[],a=e.match(/\btest\s*\(/g)||[];return u.length+a.length}catch{return 0}}function Dgu(s){try{let e=Ua(s,"utf-8"),u=e.match(/\bdef\s+test_\w+\s*\(/g)||[],a=e.match(/\basync\s+def\s+test_\w+\s*\(/g)||[];return u.length+a.length}catch{return 0}}function hgu(s){try{let e=Ua(s,"utf-8"),u=e.match(/#\[test\]/g)||[],a=e.match(/#\[tokio::test\]/g)||[],t=e.match(/#\[async_std::test\]/g)||[];return u.length+a.length+t.length}catch{return 0}}function pgu(s){try{return(Ua(s,"utf-8").match(/\bfunc\s+Test\w+\s*\(/g)||[]).length}catch{return 0}}function ti(s,e,u){let a=s,t=0,r=0;return(Au(vu(u,"tests","integration"))||Au(vu(u,"test","integration"))||Au(vu(u,"__tests__","integration")))&&(t=Math.floor(s*.2),a-=t),(Au(vu(u,"tests","e2e"))||Au(vu(u,"test","e2e"))||Au(vu(u,"e2e"))||Au(vu(u,"cypress")))&&(r=Math.floor(s*.1),a-=r),{total:s,unit:Math.max(0,a),integration:t,e2e:r,source:e}}var ml=class{config;cache=new Map;cacheHits=0;cacheMisses=0;constructor(e={}){this.config={...Ze,...e}}async collectAll(e){let u=`all:${e}`;if(this.config.enableCache){let c=this.getFromCache(u);if(c)return c}let[a,t,r]=await Promise.all([this.countLOC(e),this.countTests(e),this.countPatterns(e,this.detectLanguage(e))]),i=[];a.source!=="fallback"&&i.push(a.source),t.source!=="fallback"&&i.push(t.source);let n=a.source==="fallback"?"approximate":"accurate",o=t.source==="fallback"?"approximate":"accurate",l={loc:a,tests:t,patterns:r,collectedAt:new Date,toolsUsed:i,accuracy:{loc:n,tests:o,overall:n==="accurate"&&o==="accurate"?"accurate":"approximate"}};return this.config.enableCache&&this.setInCache(u,l),l}async countLOC(e){let u=`loc:${e}`;if(this.config.enableCache){let t=this.getFromCache(u);if(t)return t}let a=await sl(e,this.config);return this.config.enableCache&&this.setInCache(u,a),a}async countTests(e){let u=`tests:${e}`;if(this.config.enableCache){let t=this.getFromCache(u);if(t)return t}let a=await El(e,this.config);return this.config.enableCache&&this.setInCache(u,a),a}async countPatterns(e,u){let a=`patterns:${e}:${u}`;if(this.config.enableCache){let r=this.getFromCache(a);if(r)return r}let t=this.countPatternsInternal(e,u);return this.config.enableCache&&this.setInCache(a,t),t}checkTools(){let e=ll(),u=dl(process.cwd());return[...e,...u]}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0}getCacheStats(){return{hits:this.cacheHits,misses:this.cacheMisses,size:this.cache.size}}getFromCache(e){let u=this.cache.get(e);return u&&Date.now()-u.timestamp<this.config.cacheTTL?(this.cacheHits++,u.data):(this.cacheMisses++,null)}setInCache(e,u){this.cache.set(e,{data:u,timestamp:Date.now()})}detectLanguage(e){return Qe(Ye(e,"Cargo.toml"))?"rust":Qe(Ye(e,"go.mod"))?"go":Qe(Ye(e,"pyproject.toml"))||Qe(Ye(e,"requirements.txt"))?"python":Qe(Ye(e,"package.json"))?Qe(Ye(e,"tsconfig.json"))?"typescript":"javascript":"unknown"}countPatternsInternal(e,u){let a={},t=0,r=0,i=0,n=0,o=this.getPatternsForLanguage(u);function l(c){if(!Qe(c))return;let E=Cgu(c,{withFileTypes:!0});for(let d of E){let D=Ye(c,d.name);if(d.isDirectory()){if(["node_modules","dist","coverage","build",".git","vendor","target"].includes(d.name))continue;l(D)}else if(d.isFile()){let h=Agu(d.name).toLowerCase();if(ygu(h,u)){let C=xgu(D,o);(C.unwraps>0||C.unsafeBlocks>0||C.todoComments>0||C.consoleStatements>0)&&(a[D]=C,t+=C.unwraps,r+=C.unsafeBlocks,i+=C.todoComments,n+=C.consoleStatements)}}}}return l(e),{unwraps:t,unsafeBlocks:r,todoComments:i,consoleStatements:n,byFile:a}}getPatternsForLanguage(e){switch(e){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 ygu(s,e){switch(e){case"rust":return s===".rs";case"python":return[".py",".pyw"].includes(s);case"go":return s===".go";case"typescript":return[".ts",".tsx"].includes(s);case"javascript":return[".js",".jsx",".mjs",".cjs"].includes(s);default:return[".ts",".tsx",".js",".jsx",".py",".rs",".go"].includes(s)}}function xgu(s,e){try{let u=ggu(s,"utf-8");return{unwraps:e.unwrap?(u.match(e.unwrap)||[]).length:0,unsafeBlocks:e.unsafe?(u.match(e.unsafe)||[]).length:0,todoComments:(u.match(e.todo)||[]).length,consoleStatements:(u.match(e.console)||[]).length}}catch{return{unwraps:0,unsafeBlocks:0,todoComments:0,consoleStatements:0}}}function O1(s={}){return new ml(s)}N();S();cu();c0();S();c0();S();c0();S();c0();S();cu();c0();S();var $Hu=300*1e3;Qu();Qu();N();Qu();var nGu=B.create("temporal-compression");S();N();var cGu=B.create("ruvector-server-client");n3();import{Buffer as zgu}from"buffer";var gGu=zgu.from("COGCNTNR","ascii");Qu();Qu();var Ngu={capacity:1e4,minCoherenceThreshold:.3,highTierThreshold:.8,mediumTierThreshold:.5,highTierWeight:3,mediumTierWeight:1.5,lowTierWeight:1},Dl=class{config;cusumDetector;buffer;totalSeen=0;totalAdmitted=0;totalRejected=0;totalEvicted=0;totalSampled=0;constructor(e){this.config={...Ngu,...e},this.cusumDetector=new nn({threshold:this.config.cusumConfig?.threshold??5,slack:this.config.cusumConfig?.slack??.5,resetOnAlarm:!1,warmupSamples:20}),this.buffer=[]}admit(e,u,a){this.totalSeen++;let t=this.getEffectiveThreshold();if(a<t)return this.totalRejected++,!1;let r=this.classifyTier(a),i={id:e,data:u,coherenceScore:a,tier:r,admittedAt:Date.now(),replayCount:0};if(this.buffer.length<this.config.capacity)return this.buffer.push(i),this.totalAdmitted++,!0;let n=Math.floor(Math.random()*this.totalAdmitted),o=this.getTierWeight(r),l=Math.floor(n/o);if(l<this.config.capacity){let c=this.selectEvictionTarget(l);return this.buffer[c]=i,this.totalEvicted++,this.totalAdmitted++,!0}return this.totalRejected++,!1}sample(e,u){if(this.buffer.length===0)return[];let a=u!==void 0?this.buffer.filter(n=>n.coherenceScore>=u):this.buffer;if(a.length===0)return[];if(e>=a.length){let n=[...a];for(let o of n)o.replayCount++;return this.totalSampled+=n.length,n}let t=a.map(n=>this.getTierWeight(n.tier)),r=[],i=new Set;for(;r.length<e&&i.size<a.length;){let n=0;for(let c=0;c<a.length;c++)i.has(c)||(n+=t[c]);if(n<=0)break;let o=Math.random()*n,l=-1;for(let c=0;c<a.length;c++)if(!i.has(c)&&(o-=t[c],o<=0)){l=c;break}if(l===-1){for(let c=0;c<a.length;c++)if(!i.has(c)){l=c;break}}l>=0&&(i.add(l),a[l].replayCount++,r.push(a[l]))}return this.totalSampled+=r.length,r}size(){return this.buffer.length}getStats(){let e={high:0,medium:0,low:0};for(let u of this.buffer)e[u.tier]++;return{size:this.buffer.length,capacity:this.config.capacity,totalAdmitted:this.totalAdmitted,totalRejected:this.totalRejected,totalEvicted:this.totalEvicted,tierCounts:e,totalSampled:this.totalSampled}}getByTier(e){return this.buffer.filter(u=>u.tier===e)}clear(){this.buffer.length=0,this.totalSeen=0,this.totalAdmitted=0,this.totalRejected=0,this.totalEvicted=0,this.totalSampled=0,this.cusumDetector.reset()}getCusumState(e){return this.cusumDetector.getState(e)}observeCoherence(e,u){return this.cusumDetector.update(e,u)}classifyTier(e){return e>=this.config.highTierThreshold?"high":e>=this.config.mediumTierThreshold?"medium":"low"}getTierWeight(e){switch(e){case"high":return this.config.highTierWeight;case"medium":return this.config.mediumTierWeight;case"low":return this.config.lowTierWeight}}getEffectiveThreshold(){let e=["retrieve","write","learn","act"],u=!1;for(let a of e)if(this.cusumDetector.getState(a).driftDetected){u=!0;break}return u?Math.min(this.config.minCoherenceThreshold*1.5,.9):this.config.minCoherenceThreshold}selectEvictionTarget(e){let u=Math.min(10,this.buffer.length),a=Math.max(0,e-Math.floor(u/2)),t=Math.min(this.buffer.length,a+u),r=e,i=this.buffer[e].coherenceScore;for(let n=a;n<t;n++)this.buffer[n].coherenceScore<i&&(i=this.buffer[n].coherenceScore,r=n);return r}};cu();var M0=B.create("code-intelligence/gnn");async function _1(s,e,u){try{for(let a of u)try{let t=await e.readFile(a);if(t.success&&t.value){let i={vector:await hl(a,t.value),dimension:384,namespace:"code",text:t.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:a}};s.addEmbedding(i)}}catch(t){M0.error(`Failed to index ${a}:`,t instanceof Error?t:void 0)}M0.info(`Indexed ${u.length} code embeddings`)}catch(a){M0.error("Failed to index code embeddings:",a instanceof Error?a:void 0)}}async function hl(s,e){let u=[],a=s.split(".").pop(),t=ii(a||"");u.push(t%1e3/1e3),u.push(Math.min(1,e.length/1e4));let r=e.match(/function\s+\w+/g)||[],i=e.match(/class\s+\w+/g)||[];u.push(Math.min(1,(r.length+i.length)/50));let n=e.match(/import\s+.*from|require\s*\(/g)||[];u.push(Math.min(1,n.length/20));let o=e.match(/for\s*\(|while\s*\(/g)||[],l=e.match(/if\s*\(/g)||[];u.push(Math.min(1,(o.length+l.length)/30));let c=e.match(/\/\/.*|\/\*[\s\S]*?\*\//g)||[];u.push(Math.min(1,c.length/50));let E=ii(e.slice(0,500));for(let d=u.length;d<384;d++)u.push(E*(d+1)%1e4/1e4);return u.slice(0,384)}async function W1(s,e){try{let a={vector:await hl("query",e),dimension:384,namespace:"code",text:e,timestamp:Date.now(),quantization:"none"};return s.search(a,{limit:10,namespace:"code"}).map(r=>({file:r.metadata?.path??`file-${r.id}`,similarity:1-r.distance}))}catch(u){return M0.error("Failed to search with GNN:",u instanceof Error?u:void 0),[]}}async function $1(s,e,u){try{for(let a of u.changedFiles){let t=await e.readFile(a);if(t.success&&t.value){let i={vector:await hl(a,t.value),dimension:384,namespace:"code",text:t.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:a}},n=s.search(i,{limit:5,namespace:"code"});M0.info(`Found ${n.length} semantically similar files to ${a}`)}}}catch(a){M0.error("Failed to enhance impact analysis:",a instanceof Error?a:void 0)}}function q1(s,e){let u=new Map,a=new Map;for(let t of s)u.set(t.file,t.score),a.set(t.file,t);for(let t of e){let r=u.get(t.file);r!==void 0?u.set(t.file,(r+t.similarity)/2):(u.set(t.file,t.similarity*.8),a.set(t.file,{file:t.file,snippet:"",score:t.similarity*.8,highlights:[]}))}return Array.from(a.values()).map(t=>({...t,score:u.get(t.file)??t.score})).sort((t,r)=>r.score-t.score).slice(0,20)}function ii(s){let e=0;for(let u=0;u<s.length;u++)e=(e<<5)-e+s.charCodeAt(u),e=e|0;return Math.abs(e)}N();S();var qu=B.create("code-intelligence/hypergraph");async function J1(s,e,u){try{let a=await s.findUntestedFunctions();if(qu.info(`[CodeIntelligence] Found ${a.length} untested functions via hypergraph`),u){let t=L("code-intelligence.UntestedFunctionsFound","code-intelligence",{count:a.length,functions:a.slice(0,10).map(r=>({name:r.name,file:r.filePath,complexity:r.complexity}))});await e.publish(t)}return{success:!0,value:a}}catch(a){let t=g(a);return qu.error("Failed to find untested functions:"),m(t)}}async function U1(s,e,u,a){if(e.length===0)return{success:!0,value:[]};try{let t=await s.findImpactedTests(e);if(qu.info(`[CodeIntelligence] Found ${t.length} impacted tests for ${e.length} changed files via hypergraph`),a){let r=L("code-intelligence.ImpactedTestsFound","code-intelligence",{changedFiles:e,testCount:t.length,tests:t.slice(0,10).map(i=>({name:i.name,file:i.filePath}))});await u.publish(r)}return{success:!0,value:t}}catch(t){let r=g(t);return qu.error("Failed to find impacted tests:"),m(r)}}async function Z1(s,e,u,a){try{let t=await s.findCoverageGaps(e);if(qu.info(`[CodeIntelligence] Found ${t.length} coverage gaps (functions with <=${e}% coverage) via hypergraph`),a){let r=L("code-intelligence.CoverageGapsFound","code-intelligence",{maxCoverage:e,gapCount:t.length,gaps:t.slice(0,10).map(i=>({name:i.name,file:i.filePath,coverage:i.coverage,complexity:i.complexity}))});await u.publish(r)}return{success:!0,value:t}}catch(t){let r=g(t);return qu.error("Failed to find coverage gaps:"),m(r)}}async function Q1(s,e,u,a,t){try{qu.info(`[CodeIntelligence] Building hypergraph from ${e.files.length} indexed files`);let r=await s.buildFromIndexResult(e);if(qu.info(`[CodeIntelligence] Hypergraph built: ${r.nodesCreated} nodes created, ${r.nodesUpdated} nodes updated, ${r.edgesCreated} edges created (${r.durationMs}ms)`),await u.set("hypergraph:build:latest",{timestamp:new Date().toISOString(),...r},{namespace:"code-intelligence",persist:!0}),t){let i=L("code-intelligence.HypergraphBuilt","code-intelligence",{nodesCreated:r.nodesCreated,nodesUpdated:r.nodesUpdated,edgesCreated:r.edgesCreated,durationMs:r.durationMs,errorCount:r.errors.length});await a.publish(i)}return{success:!0,value:r}}catch(r){let i=g(r);return qu.error("Failed to build hypergraph:"),m(i)}}async function Y1(s,e,u){try{let a=await s.findImpactedTests(e.changedFiles),t=new Set([...u.impactedTests,...a.map(n=>n.filePath||n.name)]),r=u.riskLevel;if(a.length>u.impactedTests.length){let n=u.directImpact.length+u.transitiveImpact.length;n>10&&t.size>20?r="critical":n>5&&t.size>10&&(r="high")}let i=[...u.recommendations];return a.length>0&&i.push(`Hypergraph analysis found ${a.length} additional test(s) to run`),{...u,impactedTests:Array.from(t),riskLevel:r,recommendations:i}}catch(a){return qu.error("Failed to enhance impact with hypergraph:",a instanceof Error?a:void 0),u}}N();var R0=B.create("code-intelligence/consensus");async function X1(s,e,u,a){let t=O({id:A(),type:"code-pattern-detection",confidence:e,description:`Verify code pattern: ${s.name} (${s.type}) at ${s.location}`,payload:s,detectedBy:"code-intelligence-coordinator",severity:e>.9?"high":"medium"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(R0.info(`Code pattern '${s.name}' verified by consensus`),!0):(R0.warn(`Code pattern '${s.name}' NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async function uE(s,e,u,a){let t=O({id:A(),type:"impact-analysis",confidence:e,description:`Verify impact analysis: ${s.changedFiles.length} files, risk=${s.riskLevel}, ${s.impactedTests.length} tests`,payload:s,detectedBy:"code-intelligence-coordinator",severity:s.riskLevel==="critical"||s.riskLevel==="high"?"high":"medium"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(R0.info(`Impact analysis verified by consensus (risk=${s.riskLevel})`),!0):(R0.warn(`Impact analysis NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async function eE(s,e,u,a){let t=O({id:A(),type:"dependency-mapping",confidence:e,description:`Verify dependency: ${s.source} -> ${s.targets.length} targets (${s.type})`,payload:s,detectedBy:"code-intelligence-coordinator",severity:e>.85?"high":"medium"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(R0.info("Dependency mapping verified by consensus"),!0):(R0.warn(`Dependency mapping NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}var Xgu={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},su=B.create("code-intelligence"),Qa=class extends Y{constructor(u,a,t,r={}){let i={...Xgu,...r};super(u,"code-intelligence",i,{verifyFindingTypes:["code-pattern-detection","impact-analysis","dependency-mapping"]});this.memory=a;this.agentCoordinator=t;this.knowledgeGraph=new ze(a),this.semanticAnalyzer=new Ue(a),this.impactAnalyzer=new ea(a,this.knowledgeGraph),this.fileReader=new ju,this.productFactorsBridge=new ei(u,a,{publishEvents:this.config.publishEvents})}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=O1({enableCache:!0,cacheTTL:3e5}),su.info("MetricCollector initialized for real code metrics")),this.config.enableHypergraph&&await this.initializeHypergraph(),await this.productFactorsBridge.initialize()}async initializeHypergraph(){try{let{openDatabase:u}=await import("./safe-db-D2JVWU7V.js"),a=await import("fs"),t=await import("path"),{findProjectRoot:r}=await import("./unified-memory-H55OLMCH.js"),i=r(),n=this.config.hypergraphDbPath||t.join(i,".agentic-qe","memory.db"),o=t.dirname(n);a.existsSync(o)||a.mkdirSync(o,{recursive:!0}),this.hypergraphDb=u(n),this.hypergraph=await Ct({db:this.hypergraphDb,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:this.config.enableGNN}),su.info(`Hypergraph Engine initialized at ${n}`)}catch(u){let a=u instanceof Error?u.message:String(u);if(su.warn(`Hypergraph Engine initialization failed (feature degraded): ${a}`),this.hypergraph=void 0,this.hypergraphDb=void 0,this.config.publishEvents){let t=L("code-intelligence.HypergraphDegraded","code-intelligence",{reason:a});this.eventBus.publish(t).catch(()=>{})}}}async initializeRLIntegrations(){try{if(this.config.enableGNN&&(rn(),this.gnnIndex=gt.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 gu({domain:"code-intelligence",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.6}),su.info("PersistentSONAEngine initialized for code pattern learning")}catch(u){su.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(u){throw su.error("Failed to initialize RL integrations:",u instanceof Error?u:void 0),u}}async onDispose(){if(await this.saveWorkflowState(),this.gnnIndex&&gt.closeInstance("code-intelligence"),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(u){su.error("Error closing SONA engine:",u instanceof Error?u:void 0)}if(this.hypergraphDb){try{this.hypergraphDb.close()}catch(u){su.error("Error closing hypergraph database:",u instanceof Error?u:void 0)}this.hypergraphDb=void 0}this.hypergraph=void 0,await this.productFactorsBridge.dispose()}getActiveWorkflows(){return super.getActiveWorkflows()}async index(u){let a=A();try{if(this.startWorkflow(a,"index"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&su.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Indexing paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn indexing agents"));let t=await this.spawnIndexerAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value),this.updateWorkflowProgress(a,10);let r=await this.knowledgeGraph.index(u);if(r.success){if(this.updateWorkflowProgress(a,40),this.config.enableGNN&&this.gnnIndex&&u.paths.length>0&&await this.indexCodeEmbeddings(u.paths),this.updateWorkflowProgress(a,60),this.config.enableMetricCollector&&this.metricCollector&&u.paths.length>0){let i=this.getProjectRootFromPaths(u.paths);i&&await this.collectProjectMetrics(i)}if(this.updateWorkflowProgress(a,70),u.paths.length>0&&await this.indexForSemanticSearch(u.paths),this.updateWorkflowProgress(a,85),this.config.enableHypergraph&&this.hypergraph&&u.paths.length>0)try{let i=await this.buildCodeIndexResultFromPaths(u.paths);i.files.length>0&&(await this.hypergraph.buildFromIndexResult(i),su.info(`Hypergraph rebuilt from ${i.files.length} indexed files`))}catch(i){su.warn(`Hypergraph rebuild skipped: ${i instanceof Error?i.message:i}`)}this.updateWorkflowProgress(a,100),this.completeWorkflow(a),this.config.publishEvents&&await this.publishKnowledgeGraphUpdated(r.value)}else this.failWorkflow(a,r.error.message);return await this.agentCoordinator.stop(t.value),r}catch(t){let r=g(t);return this.failWorkflow(a,r.message),m(r)}}async search(u){let a=A();try{this.startWorkflow(a,"search");let t=await this.spawnSearchAgent(a,u);if(t.success&&this.addAgentToWorkflow(a,t.value),this.config.enableSONA&&this.sonaEngine){let n=await this.adaptSearchPattern(u);n.success&&n.pattern&&su.info(`Adapted search pattern with ${n.similarity.toFixed(3)} similarity`)}let r=[];this.config.enableGNN&&this.gnnIndex&&(r=await this.searchCodeWithGNN(u));let i=await this.semanticAnalyzer.search(u);return i.success?(r.length>0&&(i.value.results=this.mergeSearchResults(i.value.results,r)),this.completeWorkflow(a),this.config.publishEvents&&await this.publishSemanticSearchCompleted(u,i.value)):this.failWorkflow(a,i.error.message),t.success&&await this.agentCoordinator.stop(t.value),i}catch(t){let r=g(t);return this.failWorkflow(a,r.message),m(r)}}async analyzeImpact(u){let a=A();try{if(this.startWorkflow(a,"impact"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&su.warn("Topology degraded, using conservative impact analysis"),this.minCutMixin.shouldPauseOperations())return m(new Error("Impact analysis paused: topology is in critical state"));let t=await this.spawnImpactAnalyzerAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value),this.updateWorkflowProgress(a,20),this.config.enableGNN&&this.gnnIndex&&await this.enhanceImpactAnalysisWithGNN(u);let r=await this.impactAnalyzer.analyzeImpact(u);if(r.success){this.updateWorkflowProgress(a,80);let i=r.value;return this.config.enableHypergraph&&this.hypergraph&&(i=await this.enhanceImpactWithHypergraph(u,r.value)),this.updateWorkflowProgress(a,100),this.completeWorkflow(a),this.config.enableSONA&&this.sonaEngine&&await this.storeImpactPattern(u,i),this.config.publishEvents&&await this.publishImpactAnalysisCompleted(u,i),{success:!0,value:i}}else this.failWorkflow(a,r.error.message);return await this.agentCoordinator.stop(t.value),r}catch(t){let r=g(t);return this.failWorkflow(a,r.message),m(r)}}async mapDependencies(u){let a=A();try{this.startWorkflow(a,"dependency");let t=await this.knowledgeGraph.mapDependencies(u);return t.success?this.completeWorkflow(a):this.failWorkflow(a,t.error.message),t}catch(t){let r=g(t);return this.failWorkflow(a,r.message),m(r)}}async queryKG(u){let a=A();try{this.startWorkflow(a,"query");let t=await this.knowledgeGraph.query(u);return t.success?this.completeWorkflow(a):this.failWorkflow(a,t.error.message),t}catch(t){let r=g(t);return this.failWorkflow(a,r.message),m(r)}}async indexCodeEmbeddings(u){!this.gnnIndex||!this.rlInitialized||await _1(this.gnnIndex,this.fileReader,u)}async searchCodeWithGNN(u){return!this.gnnIndex||!this.rlInitialized?[]:W1(this.gnnIndex,u.query)}async enhanceImpactAnalysisWithGNN(u){!this.gnnIndex||!this.rlInitialized||await $1(this.gnnIndex,this.fileReader,u)}async adaptSearchPattern(u){if(!this.sonaEngine||!this.rlInitialized)return{success:!1,pattern:null,similarity:0};try{let a=Array.isArray(u.filters)?u.filters.find(i=>i.field==="language")?.value:void 0,t={id:`search-${u.type}`,features:[u.query.length,u.type==="semantic"?1:0,u.type==="exact"?1:0,a==="typescript"?1:0,a==="javascript"?1:0]},r=await this.sonaEngine.adaptPattern(t,"coverage-optimization","code-intelligence");return{success:r.success,pattern:r.pattern,similarity:r.similarity}}catch(a){return su.error("Failed to adapt search pattern:",a instanceof Error?a:void 0),{success:!1,pattern:null,similarity:0}}}async storeImpactPattern(u,a){if(!(!this.sonaEngine||!this.rlInitialized))try{let t={id:`impact-${u.changedFiles.join(",")}`,features:[u.changedFiles.length,u.depth||1,a.directImpact.length,a.transitiveImpact.length,a.impactedTests.length,a.riskLevel==="high"?1:a.riskLevel==="medium"?.5:0]},r={type:"analyze-impact",value:a.riskLevel},i={reward:a.riskLevel==="high"?.8:a.riskLevel==="medium"?.5:.3,success:a.impactedTests.length>0,quality:(a.directImpact.length+a.transitiveImpact.length)/100},n=this.sonaEngine.createPattern(t,r,i,"coverage-optimization","code-intelligence",{changedFiles:u.changedFiles,impactCount:a.directImpact.length+a.transitiveImpact.length,testImpactCount:a.impactedTests.length});su.info(`Stored impact pattern ${n.id}`)}catch(t){su.error("Failed to store impact pattern:",t instanceof Error?t:void 0)}}mergeSearchResults(u,a){return q1(u,a)}hashCode(u){return ii(u)}async spawnIndexerAgent(u,a){let t={name:`kg-indexer-${u.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["indexing","ast-parsing","graph-building"],config:{workflowId:u,paths:a.paths,incremental:a.incremental}};return this.agentCoordinator.spawn(t)}async spawnSearchAgent(u,a){let t={name:`semantic-search-${u.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["semantic-search","vector-similarity",a.type],config:{workflowId:u,query:a.query,type:a.type}};return this.agentCoordinator.spawn(t)}async spawnImpactAnalyzerAgent(u,a){let t={name:`impact-analyzer-${u.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["impact-analysis","dependency-traversal","risk-assessment"],config:{workflowId:u,changedFiles:a.changedFiles,depth:a.depth}};return this.agentCoordinator.spawn(t)}async publishKnowledgeGraphUpdated(u){let a={nodes:u.nodesCreated,edges:u.edgesCreated,filesIndexed:u.filesIndexed,duration:u.duration},t=L(Ee.KnowledgeGraphUpdated,"code-intelligence",a);await this.eventBus.publish(t)}async publishImpactAnalysisCompleted(u,a){let t={analysisId:A(),changedFiles:u.changedFiles,impactedFiles:[...a.directImpact.map(i=>i.file),...a.transitiveImpact.map(i=>i.file)],impactedTests:a.impactedTests,riskLevel:a.riskLevel},r=L(Ee.ImpactAnalysisCompleted,"code-intelligence",t);await this.eventBus.publish(r)}async publishSemanticSearchCompleted(u,a){let t=L(Ee.SemanticSearchCompleted,"code-intelligence",{query:u.query,type:u.type,resultCount:a.total,searchTime:a.searchTime});await this.eventBus.publish(t)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("source-control.FilesChanged",this.handleFilesChanged.bind(this))}async handleTestRunCompleted(u){let a=u.payload;await this.memory.set(`code-intelligence:test-correlation:${a.runId}`,a,{namespace:"code-intelligence",ttl:86400})}async handleFilesChanged(u){if(!this.config.enableIncrementalIndex)return;let a=u.payload;a.files&&a.files.length>0&&await this.memory.set(`code-intelligence:pending-index:${Date.now()}`,{files:a.files,timestamp:new Date().toISOString()},{namespace:"code-intelligence",ttl:3600})}async indexForSemanticSearch(u){let a=u.slice(0,100);for(let t of a)try{let r=await this.fileReader.readFile(t);r.success&&r.value&&await this.semanticAnalyzer.indexCode(t,r.value)}catch{}}async loadWorkflowState(){let u=await this.memory.get("code-intelligence:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("code-intelligence:coordinator:workflows",u,{namespace:"code-intelligence",persist:!0})}async generateC4Diagrams(u,a){let t=A();try{this.startWorkflow(t,"query");let r={projectPath:u,detectExternalSystems:a?.detectExternalSystems??!0,analyzeComponents:a?.analyzeComponents??!0,analyzeCoupling:a?.analyzeCoupling??!0,includeContext:a?.includeContext??!0,includeContainer:a?.includeContainer??!0,includeComponent:a?.includeComponent??!0,includeDependency:a?.includeDependency??!1,excludePatterns:a?.excludePatterns};this.updateWorkflowProgress(t,20);let i=await this.productFactorsBridge.requestC4Diagrams(r);return i.success?(this.updateWorkflowProgress(t,80),await this.storeC4DiagramsInMemory(u,i.value),this.updateWorkflowProgress(t,100),this.completeWorkflow(t),su.info(`[CodeIntelligenceCoordinator] C4 diagrams generated for ${u}: ${i.value.components.length} components, ${i.value.externalSystems.length} external systems`)):this.failWorkflow(t,i.error.message),i}catch(r){let i=g(r);return this.failWorkflow(t,i.message),m(i)}}getProductFactorsBridge(){return this.productFactorsBridge}async storeC4DiagramsInMemory(u,a){let t=`c4-diagrams:latest:${this.hashCode(u)}`;await this.memory.set(t,a,{namespace:"code-intelligence",persist:!0,ttl:36e5}),await this.memory.set(`c4-components:${this.hashCode(u)}`,a.components,{namespace:"code-intelligence",ttl:36e5}),await this.memory.set(`c4-external-systems:${this.hashCode(u)}`,a.externalSystems,{namespace:"code-intelligence",ttl:36e5})}async collectProjectMetrics(u){if(!this.config.enableMetricCollector||!this.metricCollector)return m(new Error("MetricCollector is not enabled"));try{su.info(`Collecting real metrics for ${u}`);let a=await this.metricCollector.collectAll(u),t=a.toolsUsed.length>0?a.toolsUsed.join(", "):a.loc.source==="node-native"?"node-native":"fallback";if(su.info(`[CodeIntelligence] Real metrics collected: ${a.loc.total} LOC, ${a.tests.total} tests, tools: ${t}`),a.loc.source==="node-native"&&su.info("[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)"),await this.storeProjectMetricsInMemory(u,a),this.config.publishEvents){let r=L("code-intelligence.MetricsCollected","code-intelligence",{projectPath:u,loc:a.loc.total,tests:a.tests.total,toolsUsed:a.toolsUsed});await this.eventBus.publish(r)}return{success:!0,value:a}}catch(a){let t=g(a);return su.error("Failed to collect metrics:"),m(t)}}async storeProjectMetricsInMemory(u,a){let t=`project-metrics:latest:${this.hashCode(u)}`;await this.memory.set(t,a,{namespace:"code-intelligence",persist:!0,ttl:3e5}),await this.memory.set(`loc-metrics:${this.hashCode(u)}`,a.loc,{namespace:"code-intelligence",ttl:3e5}),await this.memory.set(`test-metrics:${this.hashCode(u)}`,a.tests,{namespace:"code-intelligence",ttl:3e5})}getMetricCollector(){return this.metricCollector}getProjectRootFromPaths(u){if(u.length===0)return null;let a=u[0],t=a.split("/"),r="";for(let n of t){r=r?`${r}/${n}`:n;let o=["package.json","Cargo.toml","go.mod","pyproject.toml",".git"];for(let l of o)try{let c=`${r}/${l}`;if(Ji("fs").existsSync(c))return r}catch{}}let i=a.lastIndexOf("/");return i>0?a.substring(0,i):a}isHypergraphEnabled(){return this.config.enableHypergraph&&this.hypergraph!==void 0}async findUntestedFunctions(){return this.hypergraph?J1(this.hypergraph,this.eventBus,this.config.publishEvents):m(new Error("Hypergraph is not enabled or not initialized"))}async findImpactedTestsFromHypergraph(u){return this.hypergraph?U1(this.hypergraph,u,this.eventBus,this.config.publishEvents):m(new Error("Hypergraph is not enabled or not initialized"))}async findCoverageGapsFromHypergraph(u=50){return this.hypergraph?Z1(this.hypergraph,u,this.eventBus,this.config.publishEvents):m(new Error("Hypergraph is not enabled or not initialized"))}async buildHypergraphFromIndex(u){return this.hypergraph?Q1(this.hypergraph,u,this.memory,this.eventBus,this.config.publishEvents):m(new Error("Hypergraph is not enabled or not initialized"))}getHypergraph(){return this.hypergraph}async enhanceImpactWithHypergraph(u,a){return this.hypergraph?Y1(this.hypergraph,u,a):a}async buildCodeIndexResultFromPaths(u){let{extractCodeIndex:a}=await import("./code-index-extractor-YKAU2SIV.js");return a(u)}async verifyCodePatternDetection(u,a){return X1(u,a,this.consensusMixin,this.domainName)}async verifyImpactAnalysis(u,a){return uE(u,a,this.consensusMixin,this.domainName)}async verifyDependencyMapping(u,a){return eE(u,a,this.consensusMixin,this.domainName)}};S();var ni=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.paths;if(!a||a.length===0)return m(new Error("Invalid index payload: missing paths"));let t=u.language?[u.language]:u.languages;return this.coordinator.index({paths:a,languages:t})}],["search",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.query;return a?this.coordinator.search({query:a,type:u.type??"semantic",limit:u.limit}):m(new Error("Invalid search payload: missing query"))}],["analyze-impact",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.changedFiles;return!a||a.length===0?m(new Error("Invalid analyze-impact payload: missing changedFiles")):this.coordinator.analyzeImpact({changedFiles:a})}],["query-dependencies",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.file,r=u.files??(a?[a]:void 0);return!r||r.length===0?m(new Error("Invalid query-dependencies payload: missing file or files")):this.coordinator.mapDependencies({files:r,direction:u.direction??"both",depth:u.depth})}]])}async onInitialize(){this.knowledgeGraph=new ze(this.memory,this.pluginConfig.knowledgeGraph),this.semanticAnalyzer=new Ue(this.memory,this.pluginConfig.semanticAnalyzer),this.impactAnalyzer=new ea(this.memory,this.knowledgeGraph,this.pluginConfig.impactAnalyzer),this.coordinator=new Qa(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"test-generation.TestGenerated":await this.handleTestGenerated(u);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(u);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPredicted(u);break;default:break}}async index(u){this.ensureInitialized();try{let a=await this.coordinator.index(u);return a.success?this.trackSuccessfulOperation("index",a.value):this.trackFailedOperation("index",a.error),a}catch(a){return this.handleError(a)}}async search(u){this.ensureInitialized();try{let a=await this.coordinator.search(u);return a.success?this.trackSuccessfulOperation("search",a.value):this.trackFailedOperation("search",a.error),a}catch(a){return this.handleError(a)}}async analyzeImpact(u){this.ensureInitialized();try{let a=await this.coordinator.analyzeImpact(u);return a.success?this.trackSuccessfulOperation("impact",a.value):this.trackFailedOperation("impact",a.error),a}catch(a){return this.handleError(a)}}async mapDependencies(u){this.ensureInitialized();try{let a=await this.coordinator.mapDependencies(u);return a.success?this.trackSuccessfulOperation("dependency",a.value):this.trackFailedOperation("dependency",a.error),a}catch(a){return this.handleError(a)}}async queryKG(u){this.ensureInitialized();try{let a=await this.coordinator.queryKG(u);return a.success?this.trackSuccessfulOperation("query",a.value):this.trackFailedOperation("query",a.error),a}catch(a){return this.handleError(a)}}async getMetrics(){this.ensureInitialized();try{let u=this.getHealth();return{success:!0,value:{indexed:u.agents.total,queries:u.agents.idle,impacts:u.agents.active}}}catch(u){return this.handleError(u)}}async handleTestGenerated(u){let a=u.payload;await this.memory.set(`code-intelligence:test-mapping:${a.testId}`,{testFile:a.testFile,sourceFile:a.sourceFile,generatedAt:new Date().toISOString()},{namespace:"code-intelligence",ttl:86400*30})}async handleCoverageGap(u){let a=u.payload;await this.memory.set(`code-intelligence:coverage-gap:${a.gapId}`,a,{namespace:"code-intelligence",ttl:86400*7})}async handleDefectPredicted(u){let a=u.payload;await this.memory.set(`code-intelligence:defect-prediction:${a.predictionId}`,a,{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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u,a){let t=this.getHealth();this.updateHealth({agents:{...t.agents,total:t.agents.total+1,idle:t.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u,a){let t=this.getHealth();this.updateHealth({agents:{...t.agents,failed:t.agents.failed+1},errors:[...t.errors.slice(-9),a.message]})}};function pl(s,e,u,a){return new ni(s,e,u,a)}N();S();var yu=class s{constructor(e){this._value=e;if(!e||e.trim()==="")throw new Error("FilePath cannot be empty")}get value(){return this._value}get extension(){let e=this._value.split(".");return e.length>1?e[e.length-1]:""}get directory(){let e=this._value.lastIndexOf("/");return e>0?this._value.substring(0,e):""}get filename(){let e=this._value.lastIndexOf("/");return e>=0?this._value.substring(e+1):this._value}equals(e){return this._value===e._value}static create(e){return new s(e)}};var P0=class s{constructor(e){this._value=e;if(e<0||e>1)throw new Error("RiskScore must be between 0 and 1")}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(e){return this._value>e._value}equals(e){return this._value===e._value}static create(e){return new s(e)}static fromPercentage(e){return new s(e/100)}},Ju=class s{constructor(e,u){this._start=e;this._end=u;if(e>u)throw new Error("Start date cannot be after end date")}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(e){return e>=this._start&&e<=this._end}overlaps(e){return this._start<=e._end&&e._start<=this._end}equals(e){return this._start.getTime()===e._start.getTime()&&this._end.getTime()===e._end.getTime()}static create(e,u){return new s(e,u)}static lastNDays(e){let u=new Date,a=new Date(u.getTime()-e*24*60*60*1e3);return new s(a,u)}},Xe=class s{constructor(e,u,a,t){this._major=e;this._minor=u;this._patch=a;this._prerelease=t}get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let e=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${e}-${this._prerelease}`:e}isNewerThan(e){return this._major!==e._major?this._major>e._major:this._minor!==e._minor?this._minor>e._minor:this._patch>e._patch}equals(e){return this._major===e._major&&this._minor===e._minor&&this._patch===e._patch&&this._prerelease===e._prerelease}static create(e,u,a,t){return new s(e,u,a,t)}static parse(e){let u=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!u)throw new Error(`Invalid version format: ${e}`);return new s(parseInt(u[1]),parseInt(u[2]),parseInt(u[3]),u[4])}};var oi={defaultRuleSets:["owasp-top-10","cwe-sans-25"],maxConcurrentScans:4,timeout:3e5,enableFalsePositiveDetection:!0,dastMaxDepth:5,dastActiveScanning:!1,enableLLMAnalysis:!0,llmModelTier:4,enableSemgrep:!0};N();var gl=[{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"}],Cl=[{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"}],Al=[{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"}],yl=[{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"}],xl=[{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"}],fl=[{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())"}],vl=[{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"}],Fl=[{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"] })'}],si=[...gl,...Cl,...Al,...yl,...xl,...fl,...vl,...Fl],Ya=[{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"]}];S();J();S();J();import{execFile as uCu}from"child_process";import{promisify as eCu}from"util";import*as rE from"path";var bl=eCu(uCu);async function Xa(){try{return await bl("semgrep",["--version"],{timeout:5e3}),!0}catch{return!1}}async function aE(){try{let{stdout:s}=await bl("semgrep",["--version"],{timeout:5e3});return s.trim()}catch{return null}}async function aCu(s){let e={target:s.target||".",config:s.config||"auto",exclude:s.exclude||["node_modules",".git","dist","build","coverage"],maxFileSize:s.maxFileSize||5e6,timeout:s.timeout||300,verbose:s.verbose||!1};if(!await Xa())return{success:!1,findings:[],errors:["Semgrep is not installed. Install with: pip install semgrep"]};try{let a=["scan",`--config=${e.config}`,"--json",e.verbose?"--verbose":"--quiet",`--max-target-bytes=${e.maxFileSize}`];for(let o of e.exclude)a.push(`--exclude=${o}`);a.push(e.target);let t=(e.timeout??300)*1e3,{stdout:r,stderr:i}=await bl("semgrep",a,{timeout:t,maxBuffer:50*1024*1024,cwd:rE.isAbsolute(e.target)?void 0:process.cwd()}),n=tE(r);return i&&e.verbose&&n.errors.push(i),n.version=await aE()||void 0,n}catch(a){let t=a;if(t.stdout)try{let r=tE(t.stdout);return r.version=await aE()||void 0,r}catch{}return{success:!1,findings:[],errors:[t.message??String(a)]}}}function tE(s){try{let e=T(s),u=e.results||e.findings||[],a=e.errors?.map(t=>t.message||String(t))||[];return{success:!0,findings:u.map(t=>({check_id:t.check_id||t.rule_id||"unknown",path:t.path,start:{line:t.start?.line||1,col:t.start?.col||1},end:{line:t.end?.line||t.start?.line||1,col:t.end?.col||1},extra:{message:t.extra?.message||t.message||"Security issue detected",severity:t.extra?.severity||t.severity||"WARNING",lines:t.extra?.lines||"",metadata:{cwe:t.extra?.metadata?.cwe||t.metadata?.cwe,owasp:t.extra?.metadata?.owasp||t.metadata?.owasp,category:t.extra?.metadata?.category||t.metadata?.category,description:t.extra?.metadata?.description||t.metadata?.description,fix:t.extra?.metadata?.fix||t.extra?.fix,references:t.extra?.metadata?.references||t.metadata?.references,confidence:t.extra?.metadata?.confidence||t.metadata?.confidence}}})),errors:a}}catch(e){return{success:!1,findings:[],errors:[`Failed to parse semgrep output: ${k(e)}`]}}}async function li(s,e,u){let a={"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"},t=e.map(r=>a[r]||`p/${r}`).join(",");return aCu({...u,target:s,config:t||"auto"})}function tCu(s){return{ERROR:"high",WARNING:"medium",INFO:"low"}[s]||"medium"}function ci(s){return s.map(e=>({id:e.check_id,title:e.check_id.split(".").pop()||e.check_id,description:e.extra.message,severity:tCu(e.extra.severity),file:e.path,line:e.start.line,column:e.start.col,snippet:e.extra.lines,cweId:e.extra.metadata?.cwe?.[0],owaspCategory:e.extra.metadata?.owasp?.[0],remediation:e.extra.metadata?.fix||"Review and fix the identified security issue",references:e.extra.metadata?.references||[]}))}var rCu=B.create("security-compliance/sast-scanner"),z0=class{config;memory;llmRouter;activeScans;constructor(e,u,a,t){this.config=e,this.memory=u,this.llmRouter=a,this.activeScans=t||new Map}async scanFiles(e){return this.scanWithRules(e,this.config.defaultRuleSets)}async scanWithRules(e,u){let a=A();try{if(e.length===0)return m(new Error("No files provided for scanning"));this.activeScans.set(a,"running");let t=Date.now(),r=Ya.filter(h=>u.includes(h.id));if(r.length===0)return m(new Error(`No valid rule sets found: ${u.join(", ")}`));let[i,n]=await Promise.all([this.runPatternScanning(e,r),this.runSemgrepScanning(e,u)]),o=this.mergeVulnerabilities(i.vulnerabilities,n),l=i.linesScanned,c=Date.now()-t,E=this.calculateSummary(o,e.length,c),d=r.reduce((h,C)=>h+C.ruleCount,0),D={filesScanned:e.length,linesScanned:l,rulesApplied:d+(n.length>0?n.length:0)};return await this.storeScanResults(a,"sast",o,E),this.activeScans.set(a,"completed"),p({scanId:a,vulnerabilities:o,summary:E,coverage:D})}catch(t){return this.activeScans.set(a,"failed"),m(g(t))}}async runPatternScanning(e,u){let a=[],t=0;for(let r of e){let i=await this.analyzeFile(r,u);a.push(...i.vulnerabilities),t+=i.linesScanned}return{vulnerabilities:a,linesScanned:t}}async runSemgrepScanning(e,u){if(!this.config.enableSemgrep)return[];try{if(!await Xa())return[];let t=this.resolveTargetDirectory(e),r=await li(t,u);return!r.success||r.findings.length===0?[]:ci(r.findings).map(n=>({id:A(),cveId:void 0,title:n.title,description:`[semgrep] ${n.description}`,severity:n.severity,category:this.mapSemgrepCategory(n.owaspCategory),location:{file:n.file,line:n.line,column:n.column,snippet:n.snippet},remediation:{description:n.remediation,estimatedEffort:"moderate",automatable:!1},references:n.references}))}catch{return[]}}resolveTargetDirectory(e){if(e.length===0)return".";if(e.length===1)return e[0].directory||".";let u=e.map(n=>n.directory||"."),a=u[0],t=a.length;for(let n=1;n<u.length;n++){let o=u[n],l=Math.min(t,o.length),c=0;for(;c<l&&a[c]===o[c];)c++;t=c}let r=a.substring(0,t),i=r.lastIndexOf("/");return i>0?r.substring(0,i):r||"."}mapSemgrepCategory(e){if(!e)return"injection";let u={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[a,t]of Object.entries(u))if(e.startsWith(a))return t;return"injection"}mergeVulnerabilities(e,u){if(u.length===0)return e;if(e.length===0)return u;let a=new Set(e.map(r=>`${r.location.file}:${r.location.line??0}:${r.category}`)),t=u.filter(r=>!a.has(`${r.location.file}:${r.location.line??0}:${r.category}`));return[...e,...t]}async getAvailableRuleSets(){let e=await this.memory.get("security:custom-rule-sets");return[...Ya,...e||[]]}async checkFalsePositive(e){try{if(!this.config.enableFalsePositiveDetection)return p({isFalsePositive:!1,confidence:0,reason:"False positive detection is disabled"});let u=await this.analyzeFalsePositive(e);return await this.memory.set(`security:fp-check:${e.id}`,{vulnerability:e,analysis:u},{namespace:"security-compliance",ttl:86400*30}),p(u)}catch(u){return m(g(u))}}async analyzeFile(e,u){let a=[],t=e.value,r=e.extension,i,n;try{i=await(await import("fs/promises")).readFile(t,"utf-8"),n=i.split(`
2899
+ `).filter(o=>o.startsWith("Test")||o.startsWith("Example")||o.startsWith("Benchmark")),t=a.filter(o=>o.startsWith("Test")).length,r=a.filter(o=>o.startsWith("Test")&&!o.includes("Integration")&&!o.includes("E2E")).length,i=a.filter(o=>o.includes("Integration")).length,n=a.filter(o=>o.includes("E2E")).length;return{total:t,unit:r,integration:i,e2e:n,source:"go"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"go"}}}function qa(s,e){let u=0,a=0,t=0,r=0;function i(n){if(!Au(n))return;let o=ngu(n,{withFileTypes:!0});for(let l of o){let c=vu(n,l.name);if(l.isDirectory()){if(e.excludeDirs.includes(l.name))continue;i(c)}else if(l.isFile()&&mgu(l.name)){let E=ogu(l.name).toLowerCase(),d=0;[".ts",".tsx",".js",".jsx",".mjs"].includes(E)?d=V1(c):E===".py"?d=Dgu(c):E===".rs"?d=hgu(c):E===".go"&&(d=pgu(c)),u+=d;let D=c.toLowerCase();D.includes("e2e")||D.includes("end-to-end")?r+=d:D.includes("integration")?t+=d:a+=d}}}return i(s),{total:u,unit:a,integration:t,e2e:r,source:"fallback"}}function mgu(s){let e=s.toLowerCase();return e.includes(".test.")||e.includes(".spec.")||e.includes("_test.")||e.startsWith("test_")||e.endsWith("_test.ts")||e.endsWith("_test.js")||e.endsWith("_test.py")||e.endsWith("_test.go")||e.endsWith("_test.rs")}function V1(s){try{let e=Ua(s,"utf-8"),u=e.match(/\bit\s*\(/g)||[],a=e.match(/\btest\s*\(/g)||[];return u.length+a.length}catch{return 0}}function Dgu(s){try{let e=Ua(s,"utf-8"),u=e.match(/\bdef\s+test_\w+\s*\(/g)||[],a=e.match(/\basync\s+def\s+test_\w+\s*\(/g)||[];return u.length+a.length}catch{return 0}}function hgu(s){try{let e=Ua(s,"utf-8"),u=e.match(/#\[test\]/g)||[],a=e.match(/#\[tokio::test\]/g)||[],t=e.match(/#\[async_std::test\]/g)||[];return u.length+a.length+t.length}catch{return 0}}function pgu(s){try{return(Ua(s,"utf-8").match(/\bfunc\s+Test\w+\s*\(/g)||[]).length}catch{return 0}}function ti(s,e,u){let a=s,t=0,r=0;return(Au(vu(u,"tests","integration"))||Au(vu(u,"test","integration"))||Au(vu(u,"__tests__","integration")))&&(t=Math.floor(s*.2),a-=t),(Au(vu(u,"tests","e2e"))||Au(vu(u,"test","e2e"))||Au(vu(u,"e2e"))||Au(vu(u,"cypress")))&&(r=Math.floor(s*.1),a-=r),{total:s,unit:Math.max(0,a),integration:t,e2e:r,source:e}}var ml=class{config;cache=new Map;cacheHits=0;cacheMisses=0;constructor(e={}){this.config={...Ze,...e}}async collectAll(e){let u=`all:${e}`;if(this.config.enableCache){let c=this.getFromCache(u);if(c)return c}let[a,t,r]=await Promise.all([this.countLOC(e),this.countTests(e),this.countPatterns(e,this.detectLanguage(e))]),i=[];a.source!=="fallback"&&i.push(a.source),t.source!=="fallback"&&i.push(t.source);let n=a.source==="fallback"?"approximate":"accurate",o=t.source==="fallback"?"approximate":"accurate",l={loc:a,tests:t,patterns:r,collectedAt:new Date,toolsUsed:i,accuracy:{loc:n,tests:o,overall:n==="accurate"&&o==="accurate"?"accurate":"approximate"}};return this.config.enableCache&&this.setInCache(u,l),l}async countLOC(e){let u=`loc:${e}`;if(this.config.enableCache){let t=this.getFromCache(u);if(t)return t}let a=await sl(e,this.config);return this.config.enableCache&&this.setInCache(u,a),a}async countTests(e){let u=`tests:${e}`;if(this.config.enableCache){let t=this.getFromCache(u);if(t)return t}let a=await El(e,this.config);return this.config.enableCache&&this.setInCache(u,a),a}async countPatterns(e,u){let a=`patterns:${e}:${u}`;if(this.config.enableCache){let r=this.getFromCache(a);if(r)return r}let t=this.countPatternsInternal(e,u);return this.config.enableCache&&this.setInCache(a,t),t}checkTools(){let e=ll(),u=dl(process.cwd());return[...e,...u]}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0}getCacheStats(){return{hits:this.cacheHits,misses:this.cacheMisses,size:this.cache.size}}getFromCache(e){let u=this.cache.get(e);return u&&Date.now()-u.timestamp<this.config.cacheTTL?(this.cacheHits++,u.data):(this.cacheMisses++,null)}setInCache(e,u){this.cache.set(e,{data:u,timestamp:Date.now()})}detectLanguage(e){return Qe(Ye(e,"Cargo.toml"))?"rust":Qe(Ye(e,"go.mod"))?"go":Qe(Ye(e,"pyproject.toml"))||Qe(Ye(e,"requirements.txt"))?"python":Qe(Ye(e,"package.json"))?Qe(Ye(e,"tsconfig.json"))?"typescript":"javascript":"unknown"}countPatternsInternal(e,u){let a={},t=0,r=0,i=0,n=0,o=this.getPatternsForLanguage(u);function l(c){if(!Qe(c))return;let E=Cgu(c,{withFileTypes:!0});for(let d of E){let D=Ye(c,d.name);if(d.isDirectory()){if(["node_modules","dist","coverage","build",".git","vendor","target"].includes(d.name))continue;l(D)}else if(d.isFile()){let h=Agu(d.name).toLowerCase();if(ygu(h,u)){let C=xgu(D,o);(C.unwraps>0||C.unsafeBlocks>0||C.todoComments>0||C.consoleStatements>0)&&(a[D]=C,t+=C.unwraps,r+=C.unsafeBlocks,i+=C.todoComments,n+=C.consoleStatements)}}}}return l(e),{unwraps:t,unsafeBlocks:r,todoComments:i,consoleStatements:n,byFile:a}}getPatternsForLanguage(e){switch(e){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 ygu(s,e){switch(e){case"rust":return s===".rs";case"python":return[".py",".pyw"].includes(s);case"go":return s===".go";case"typescript":return[".ts",".tsx"].includes(s);case"javascript":return[".js",".jsx",".mjs",".cjs"].includes(s);default:return[".ts",".tsx",".js",".jsx",".py",".rs",".go"].includes(s)}}function xgu(s,e){try{let u=ggu(s,"utf-8");return{unwraps:e.unwrap?(u.match(e.unwrap)||[]).length:0,unsafeBlocks:e.unsafe?(u.match(e.unsafe)||[]).length:0,todoComments:(u.match(e.todo)||[]).length,consoleStatements:(u.match(e.console)||[]).length}}catch{return{unwraps:0,unsafeBlocks:0,todoComments:0,consoleStatements:0}}}function O1(s={}){return new ml(s)}N();S();cu();c0();S();c0();S();c0();S();c0();S();cu();c0();S();var $Hu=300*1e3;Qu();Qu();N();Qu();var nGu=B.create("temporal-compression");S();N();var cGu=B.create("ruvector-server-client");n3();import{Buffer as zgu}from"buffer";var gGu=zgu.from("COGCNTNR","ascii");Qu();Qu();var Ngu={capacity:1e4,minCoherenceThreshold:.3,highTierThreshold:.8,mediumTierThreshold:.5,highTierWeight:3,mediumTierWeight:1.5,lowTierWeight:1},Dl=class{config;cusumDetector;buffer;totalSeen=0;totalAdmitted=0;totalRejected=0;totalEvicted=0;totalSampled=0;constructor(e){this.config={...Ngu,...e},this.cusumDetector=new nn({threshold:this.config.cusumConfig?.threshold??5,slack:this.config.cusumConfig?.slack??.5,resetOnAlarm:!1,warmupSamples:20}),this.buffer=[]}admit(e,u,a){this.totalSeen++;let t=this.getEffectiveThreshold();if(a<t)return this.totalRejected++,!1;let r=this.classifyTier(a),i={id:e,data:u,coherenceScore:a,tier:r,admittedAt:Date.now(),replayCount:0};if(this.buffer.length<this.config.capacity)return this.buffer.push(i),this.totalAdmitted++,!0;let n=Math.floor(Math.random()*this.totalAdmitted),o=this.getTierWeight(r),l=Math.floor(n/o);if(l<this.config.capacity){let c=this.selectEvictionTarget(l);return this.buffer[c]=i,this.totalEvicted++,this.totalAdmitted++,!0}return this.totalRejected++,!1}sample(e,u){if(this.buffer.length===0)return[];let a=u!==void 0?this.buffer.filter(n=>n.coherenceScore>=u):this.buffer;if(a.length===0)return[];if(e>=a.length){let n=[...a];for(let o of n)o.replayCount++;return this.totalSampled+=n.length,n}let t=a.map(n=>this.getTierWeight(n.tier)),r=[],i=new Set;for(;r.length<e&&i.size<a.length;){let n=0;for(let c=0;c<a.length;c++)i.has(c)||(n+=t[c]);if(n<=0)break;let o=Math.random()*n,l=-1;for(let c=0;c<a.length;c++)if(!i.has(c)&&(o-=t[c],o<=0)){l=c;break}if(l===-1){for(let c=0;c<a.length;c++)if(!i.has(c)){l=c;break}}l>=0&&(i.add(l),a[l].replayCount++,r.push(a[l]))}return this.totalSampled+=r.length,r}size(){return this.buffer.length}getStats(){let e={high:0,medium:0,low:0};for(let u of this.buffer)e[u.tier]++;return{size:this.buffer.length,capacity:this.config.capacity,totalAdmitted:this.totalAdmitted,totalRejected:this.totalRejected,totalEvicted:this.totalEvicted,tierCounts:e,totalSampled:this.totalSampled}}getByTier(e){return this.buffer.filter(u=>u.tier===e)}clear(){this.buffer.length=0,this.totalSeen=0,this.totalAdmitted=0,this.totalRejected=0,this.totalEvicted=0,this.totalSampled=0,this.cusumDetector.reset()}getCusumState(e){return this.cusumDetector.getState(e)}observeCoherence(e,u){return this.cusumDetector.update(e,u)}classifyTier(e){return e>=this.config.highTierThreshold?"high":e>=this.config.mediumTierThreshold?"medium":"low"}getTierWeight(e){switch(e){case"high":return this.config.highTierWeight;case"medium":return this.config.mediumTierWeight;case"low":return this.config.lowTierWeight}}getEffectiveThreshold(){let e=["retrieve","write","learn","act"],u=!1;for(let a of e)if(this.cusumDetector.getState(a).driftDetected){u=!0;break}return u?Math.min(this.config.minCoherenceThreshold*1.5,.9):this.config.minCoherenceThreshold}selectEvictionTarget(e){let u=Math.min(10,this.buffer.length),a=Math.max(0,e-Math.floor(u/2)),t=Math.min(this.buffer.length,a+u),r=e,i=this.buffer[e].coherenceScore;for(let n=a;n<t;n++)this.buffer[n].coherenceScore<i&&(i=this.buffer[n].coherenceScore,r=n);return r}};cu();var M0=B.create("code-intelligence/gnn");async function _1(s,e,u){try{for(let a of u)try{let t=await e.readFile(a);if(t.success&&t.value){let i={vector:await hl(a,t.value),dimension:384,namespace:"code",text:t.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:a}};s.addEmbedding(i)}}catch(t){M0.error(`Failed to index ${a}:`,t instanceof Error?t:void 0)}M0.info(`Indexed ${u.length} code embeddings`)}catch(a){M0.error("Failed to index code embeddings:",a instanceof Error?a:void 0)}}async function hl(s,e){let u=[],a=s.split(".").pop(),t=ii(a||"");u.push(t%1e3/1e3),u.push(Math.min(1,e.length/1e4));let r=e.match(/function\s+\w+/g)||[],i=e.match(/class\s+\w+/g)||[];u.push(Math.min(1,(r.length+i.length)/50));let n=e.match(/import\s+.*from|require\s*\(/g)||[];u.push(Math.min(1,n.length/20));let o=e.match(/for\s*\(|while\s*\(/g)||[],l=e.match(/if\s*\(/g)||[];u.push(Math.min(1,(o.length+l.length)/30));let c=e.match(/\/\/.*|\/\*[\s\S]*?\*\//g)||[];u.push(Math.min(1,c.length/50));let E=ii(e.slice(0,500));for(let d=u.length;d<384;d++)u.push(E*(d+1)%1e4/1e4);return u.slice(0,384)}async function W1(s,e){try{let a={vector:await hl("query",e),dimension:384,namespace:"code",text:e,timestamp:Date.now(),quantization:"none"};return s.search(a,{limit:10,namespace:"code"}).map(r=>({file:r.metadata?.path??`file-${r.id}`,similarity:1-r.distance}))}catch(u){return M0.error("Failed to search with GNN:",u instanceof Error?u:void 0),[]}}async function $1(s,e,u){try{for(let a of u.changedFiles){let t=await e.readFile(a);if(t.success&&t.value){let i={vector:await hl(a,t.value),dimension:384,namespace:"code",text:t.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:a}},n=s.search(i,{limit:5,namespace:"code"});M0.info(`Found ${n.length} semantically similar files to ${a}`)}}}catch(a){M0.error("Failed to enhance impact analysis:",a instanceof Error?a:void 0)}}function q1(s,e){let u=new Map,a=new Map;for(let t of s)u.set(t.file,t.score),a.set(t.file,t);for(let t of e){let r=u.get(t.file);r!==void 0?u.set(t.file,(r+t.similarity)/2):(u.set(t.file,t.similarity*.8),a.set(t.file,{file:t.file,snippet:"",score:t.similarity*.8,highlights:[]}))}return Array.from(a.values()).map(t=>({...t,score:u.get(t.file)??t.score})).sort((t,r)=>r.score-t.score).slice(0,20)}function ii(s){let e=0;for(let u=0;u<s.length;u++)e=(e<<5)-e+s.charCodeAt(u),e=e|0;return Math.abs(e)}N();S();var qu=B.create("code-intelligence/hypergraph");async function J1(s,e,u){try{let a=await s.findUntestedFunctions();if(qu.info(`[CodeIntelligence] Found ${a.length} untested functions via hypergraph`),u){let t=L("code-intelligence.UntestedFunctionsFound","code-intelligence",{count:a.length,functions:a.slice(0,10).map(r=>({name:r.name,file:r.filePath,complexity:r.complexity}))});await e.publish(t)}return{success:!0,value:a}}catch(a){let t=g(a);return qu.error("Failed to find untested functions:"),m(t)}}async function U1(s,e,u,a){if(e.length===0)return{success:!0,value:[]};try{let t=await s.findImpactedTests(e);if(qu.info(`[CodeIntelligence] Found ${t.length} impacted tests for ${e.length} changed files via hypergraph`),a){let r=L("code-intelligence.ImpactedTestsFound","code-intelligence",{changedFiles:e,testCount:t.length,tests:t.slice(0,10).map(i=>({name:i.name,file:i.filePath}))});await u.publish(r)}return{success:!0,value:t}}catch(t){let r=g(t);return qu.error("Failed to find impacted tests:"),m(r)}}async function Z1(s,e,u,a){try{let t=await s.findCoverageGaps(e);if(qu.info(`[CodeIntelligence] Found ${t.length} coverage gaps (functions with <=${e}% coverage) via hypergraph`),a){let r=L("code-intelligence.CoverageGapsFound","code-intelligence",{maxCoverage:e,gapCount:t.length,gaps:t.slice(0,10).map(i=>({name:i.name,file:i.filePath,coverage:i.coverage,complexity:i.complexity}))});await u.publish(r)}return{success:!0,value:t}}catch(t){let r=g(t);return qu.error("Failed to find coverage gaps:"),m(r)}}async function Q1(s,e,u,a,t){try{qu.info(`[CodeIntelligence] Building hypergraph from ${e.files.length} indexed files`);let r=await s.buildFromIndexResult(e);if(qu.info(`[CodeIntelligence] Hypergraph built: ${r.nodesCreated} nodes created, ${r.nodesUpdated} nodes updated, ${r.edgesCreated} edges created (${r.durationMs}ms)`),await u.set("hypergraph:build:latest",{timestamp:new Date().toISOString(),...r},{namespace:"code-intelligence",persist:!0}),t){let i=L("code-intelligence.HypergraphBuilt","code-intelligence",{nodesCreated:r.nodesCreated,nodesUpdated:r.nodesUpdated,edgesCreated:r.edgesCreated,durationMs:r.durationMs,errorCount:r.errors.length});await a.publish(i)}return{success:!0,value:r}}catch(r){let i=g(r);return qu.error("Failed to build hypergraph:"),m(i)}}async function Y1(s,e,u){try{let a=await s.findImpactedTests(e.changedFiles),t=new Set([...u.impactedTests,...a.map(n=>n.filePath||n.name)]),r=u.riskLevel;if(a.length>u.impactedTests.length){let n=u.directImpact.length+u.transitiveImpact.length;n>10&&t.size>20?r="critical":n>5&&t.size>10&&(r="high")}let i=[...u.recommendations];return a.length>0&&i.push(`Hypergraph analysis found ${a.length} additional test(s) to run`),{...u,impactedTests:Array.from(t),riskLevel:r,recommendations:i}}catch(a){return qu.error("Failed to enhance impact with hypergraph:",a instanceof Error?a:void 0),u}}N();var R0=B.create("code-intelligence/consensus");async function X1(s,e,u,a){let t=O({id:A(),type:"code-pattern-detection",confidence:e,description:`Verify code pattern: ${s.name} (${s.type}) at ${s.location}`,payload:s,detectedBy:"code-intelligence-coordinator",severity:e>.9?"high":"medium"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(R0.info(`Code pattern '${s.name}' verified by consensus`),!0):(R0.warn(`Code pattern '${s.name}' NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async function uE(s,e,u,a){let t=O({id:A(),type:"impact-analysis",confidence:e,description:`Verify impact analysis: ${s.changedFiles.length} files, risk=${s.riskLevel}, ${s.impactedTests.length} tests`,payload:s,detectedBy:"code-intelligence-coordinator",severity:s.riskLevel==="critical"||s.riskLevel==="high"?"high":"medium"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(R0.info(`Impact analysis verified by consensus (risk=${s.riskLevel})`),!0):(R0.warn(`Impact analysis NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async function eE(s,e,u,a){let t=O({id:A(),type:"dependency-mapping",confidence:e,description:`Verify dependency: ${s.source} -> ${s.targets.length} targets (${s.type})`,payload:s,detectedBy:"code-intelligence-coordinator",severity:e>.85?"high":"medium"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(R0.info("Dependency mapping verified by consensus"),!0):(R0.warn(`Dependency mapping NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}var Xgu={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},su=B.create("code-intelligence"),Qa=class extends Y{constructor(u,a,t,r={}){let i={...Xgu,...r};super(u,"code-intelligence",i,{verifyFindingTypes:["code-pattern-detection","impact-analysis","dependency-mapping"]});this.memory=a;this.agentCoordinator=t;this.knowledgeGraph=new ze(a),this.semanticAnalyzer=new Ue(a),this.impactAnalyzer=new ea(a,this.knowledgeGraph),this.fileReader=new ju,this.productFactorsBridge=new ei(u,a,{publishEvents:this.config.publishEvents})}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=O1({enableCache:!0,cacheTTL:3e5}),su.info("MetricCollector initialized for real code metrics")),this.config.enableHypergraph&&await this.initializeHypergraph(),await this.productFactorsBridge.initialize()}async initializeHypergraph(){try{let{openDatabase:u}=await import("./safe-db-FFSPBUAK.js"),a=await import("fs"),t=await import("path"),{findProjectRoot:r}=await import("./unified-memory-CZCWZUFP.js"),i=r(),n=this.config.hypergraphDbPath||t.join(i,".agentic-qe","memory.db"),o=t.dirname(n);a.existsSync(o)||a.mkdirSync(o,{recursive:!0}),this.hypergraphDb=u(n),this.hypergraph=await Ct({db:this.hypergraphDb,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:this.config.enableGNN}),su.info(`Hypergraph Engine initialized at ${n}`)}catch(u){let a=u instanceof Error?u.message:String(u);if(su.warn(`Hypergraph Engine initialization failed (feature degraded): ${a}`),this.hypergraph=void 0,this.hypergraphDb=void 0,this.config.publishEvents){let t=L("code-intelligence.HypergraphDegraded","code-intelligence",{reason:a});this.eventBus.publish(t).catch(()=>{})}}}async initializeRLIntegrations(){try{if(this.config.enableGNN&&(rn(),this.gnnIndex=gt.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 gu({domain:"code-intelligence",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.6}),su.info("PersistentSONAEngine initialized for code pattern learning")}catch(u){su.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(u){throw su.error("Failed to initialize RL integrations:",u instanceof Error?u:void 0),u}}async onDispose(){if(await this.saveWorkflowState(),this.gnnIndex&&gt.closeInstance("code-intelligence"),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(u){su.error("Error closing SONA engine:",u instanceof Error?u:void 0)}if(this.hypergraphDb){try{this.hypergraphDb.close()}catch(u){su.error("Error closing hypergraph database:",u instanceof Error?u:void 0)}this.hypergraphDb=void 0}this.hypergraph=void 0,await this.productFactorsBridge.dispose()}getActiveWorkflows(){return super.getActiveWorkflows()}async index(u){let a=A();try{if(this.startWorkflow(a,"index"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&su.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Indexing paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn indexing agents"));let t=await this.spawnIndexerAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value),this.updateWorkflowProgress(a,10);let r=await this.knowledgeGraph.index(u);if(r.success){if(this.updateWorkflowProgress(a,40),this.config.enableGNN&&this.gnnIndex&&u.paths.length>0&&await this.indexCodeEmbeddings(u.paths),this.updateWorkflowProgress(a,60),this.config.enableMetricCollector&&this.metricCollector&&u.paths.length>0){let i=this.getProjectRootFromPaths(u.paths);i&&await this.collectProjectMetrics(i)}if(this.updateWorkflowProgress(a,70),u.paths.length>0&&await this.indexForSemanticSearch(u.paths),this.updateWorkflowProgress(a,85),this.config.enableHypergraph&&this.hypergraph&&u.paths.length>0)try{let i=await this.buildCodeIndexResultFromPaths(u.paths);i.files.length>0&&(await this.hypergraph.buildFromIndexResult(i),su.info(`Hypergraph rebuilt from ${i.files.length} indexed files`))}catch(i){su.warn(`Hypergraph rebuild skipped: ${i instanceof Error?i.message:i}`)}this.updateWorkflowProgress(a,100),this.completeWorkflow(a),this.config.publishEvents&&await this.publishKnowledgeGraphUpdated(r.value)}else this.failWorkflow(a,r.error.message);return await this.agentCoordinator.stop(t.value),r}catch(t){let r=g(t);return this.failWorkflow(a,r.message),m(r)}}async search(u){let a=A();try{this.startWorkflow(a,"search");let t=await this.spawnSearchAgent(a,u);if(t.success&&this.addAgentToWorkflow(a,t.value),this.config.enableSONA&&this.sonaEngine){let n=await this.adaptSearchPattern(u);n.success&&n.pattern&&su.info(`Adapted search pattern with ${n.similarity.toFixed(3)} similarity`)}let r=[];this.config.enableGNN&&this.gnnIndex&&(r=await this.searchCodeWithGNN(u));let i=await this.semanticAnalyzer.search(u);return i.success?(r.length>0&&(i.value.results=this.mergeSearchResults(i.value.results,r)),this.completeWorkflow(a),this.config.publishEvents&&await this.publishSemanticSearchCompleted(u,i.value)):this.failWorkflow(a,i.error.message),t.success&&await this.agentCoordinator.stop(t.value),i}catch(t){let r=g(t);return this.failWorkflow(a,r.message),m(r)}}async analyzeImpact(u){let a=A();try{if(this.startWorkflow(a,"impact"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&su.warn("Topology degraded, using conservative impact analysis"),this.minCutMixin.shouldPauseOperations())return m(new Error("Impact analysis paused: topology is in critical state"));let t=await this.spawnImpactAnalyzerAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value),this.updateWorkflowProgress(a,20),this.config.enableGNN&&this.gnnIndex&&await this.enhanceImpactAnalysisWithGNN(u);let r=await this.impactAnalyzer.analyzeImpact(u);if(r.success){this.updateWorkflowProgress(a,80);let i=r.value;return this.config.enableHypergraph&&this.hypergraph&&(i=await this.enhanceImpactWithHypergraph(u,r.value)),this.updateWorkflowProgress(a,100),this.completeWorkflow(a),this.config.enableSONA&&this.sonaEngine&&await this.storeImpactPattern(u,i),this.config.publishEvents&&await this.publishImpactAnalysisCompleted(u,i),{success:!0,value:i}}else this.failWorkflow(a,r.error.message);return await this.agentCoordinator.stop(t.value),r}catch(t){let r=g(t);return this.failWorkflow(a,r.message),m(r)}}async mapDependencies(u){let a=A();try{this.startWorkflow(a,"dependency");let t=await this.knowledgeGraph.mapDependencies(u);return t.success?this.completeWorkflow(a):this.failWorkflow(a,t.error.message),t}catch(t){let r=g(t);return this.failWorkflow(a,r.message),m(r)}}async queryKG(u){let a=A();try{this.startWorkflow(a,"query");let t=await this.knowledgeGraph.query(u);return t.success?this.completeWorkflow(a):this.failWorkflow(a,t.error.message),t}catch(t){let r=g(t);return this.failWorkflow(a,r.message),m(r)}}async indexCodeEmbeddings(u){!this.gnnIndex||!this.rlInitialized||await _1(this.gnnIndex,this.fileReader,u)}async searchCodeWithGNN(u){return!this.gnnIndex||!this.rlInitialized?[]:W1(this.gnnIndex,u.query)}async enhanceImpactAnalysisWithGNN(u){!this.gnnIndex||!this.rlInitialized||await $1(this.gnnIndex,this.fileReader,u)}async adaptSearchPattern(u){if(!this.sonaEngine||!this.rlInitialized)return{success:!1,pattern:null,similarity:0};try{let a=Array.isArray(u.filters)?u.filters.find(i=>i.field==="language")?.value:void 0,t={id:`search-${u.type}`,features:[u.query.length,u.type==="semantic"?1:0,u.type==="exact"?1:0,a==="typescript"?1:0,a==="javascript"?1:0]},r=await this.sonaEngine.adaptPattern(t,"coverage-optimization","code-intelligence");return{success:r.success,pattern:r.pattern,similarity:r.similarity}}catch(a){return su.error("Failed to adapt search pattern:",a instanceof Error?a:void 0),{success:!1,pattern:null,similarity:0}}}async storeImpactPattern(u,a){if(!(!this.sonaEngine||!this.rlInitialized))try{let t={id:`impact-${u.changedFiles.join(",")}`,features:[u.changedFiles.length,u.depth||1,a.directImpact.length,a.transitiveImpact.length,a.impactedTests.length,a.riskLevel==="high"?1:a.riskLevel==="medium"?.5:0]},r={type:"analyze-impact",value:a.riskLevel},i={reward:a.riskLevel==="high"?.8:a.riskLevel==="medium"?.5:.3,success:a.impactedTests.length>0,quality:(a.directImpact.length+a.transitiveImpact.length)/100},n=this.sonaEngine.createPattern(t,r,i,"coverage-optimization","code-intelligence",{changedFiles:u.changedFiles,impactCount:a.directImpact.length+a.transitiveImpact.length,testImpactCount:a.impactedTests.length});su.info(`Stored impact pattern ${n.id}`)}catch(t){su.error("Failed to store impact pattern:",t instanceof Error?t:void 0)}}mergeSearchResults(u,a){return q1(u,a)}hashCode(u){return ii(u)}async spawnIndexerAgent(u,a){let t={name:`kg-indexer-${u.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["indexing","ast-parsing","graph-building"],config:{workflowId:u,paths:a.paths,incremental:a.incremental}};return this.agentCoordinator.spawn(t)}async spawnSearchAgent(u,a){let t={name:`semantic-search-${u.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["semantic-search","vector-similarity",a.type],config:{workflowId:u,query:a.query,type:a.type}};return this.agentCoordinator.spawn(t)}async spawnImpactAnalyzerAgent(u,a){let t={name:`impact-analyzer-${u.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["impact-analysis","dependency-traversal","risk-assessment"],config:{workflowId:u,changedFiles:a.changedFiles,depth:a.depth}};return this.agentCoordinator.spawn(t)}async publishKnowledgeGraphUpdated(u){let a={nodes:u.nodesCreated,edges:u.edgesCreated,filesIndexed:u.filesIndexed,duration:u.duration},t=L(Ee.KnowledgeGraphUpdated,"code-intelligence",a);await this.eventBus.publish(t)}async publishImpactAnalysisCompleted(u,a){let t={analysisId:A(),changedFiles:u.changedFiles,impactedFiles:[...a.directImpact.map(i=>i.file),...a.transitiveImpact.map(i=>i.file)],impactedTests:a.impactedTests,riskLevel:a.riskLevel},r=L(Ee.ImpactAnalysisCompleted,"code-intelligence",t);await this.eventBus.publish(r)}async publishSemanticSearchCompleted(u,a){let t=L(Ee.SemanticSearchCompleted,"code-intelligence",{query:u.query,type:u.type,resultCount:a.total,searchTime:a.searchTime});await this.eventBus.publish(t)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("source-control.FilesChanged",this.handleFilesChanged.bind(this))}async handleTestRunCompleted(u){let a=u.payload;await this.memory.set(`code-intelligence:test-correlation:${a.runId}`,a,{namespace:"code-intelligence",ttl:86400})}async handleFilesChanged(u){if(!this.config.enableIncrementalIndex)return;let a=u.payload;a.files&&a.files.length>0&&await this.memory.set(`code-intelligence:pending-index:${Date.now()}`,{files:a.files,timestamp:new Date().toISOString()},{namespace:"code-intelligence",ttl:3600})}async indexForSemanticSearch(u){let a=u.slice(0,100);for(let t of a)try{let r=await this.fileReader.readFile(t);r.success&&r.value&&await this.semanticAnalyzer.indexCode(t,r.value)}catch{}}async loadWorkflowState(){let u=await this.memory.get("code-intelligence:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("code-intelligence:coordinator:workflows",u,{namespace:"code-intelligence",persist:!0})}async generateC4Diagrams(u,a){let t=A();try{this.startWorkflow(t,"query");let r={projectPath:u,detectExternalSystems:a?.detectExternalSystems??!0,analyzeComponents:a?.analyzeComponents??!0,analyzeCoupling:a?.analyzeCoupling??!0,includeContext:a?.includeContext??!0,includeContainer:a?.includeContainer??!0,includeComponent:a?.includeComponent??!0,includeDependency:a?.includeDependency??!1,excludePatterns:a?.excludePatterns};this.updateWorkflowProgress(t,20);let i=await this.productFactorsBridge.requestC4Diagrams(r);return i.success?(this.updateWorkflowProgress(t,80),await this.storeC4DiagramsInMemory(u,i.value),this.updateWorkflowProgress(t,100),this.completeWorkflow(t),su.info(`[CodeIntelligenceCoordinator] C4 diagrams generated for ${u}: ${i.value.components.length} components, ${i.value.externalSystems.length} external systems`)):this.failWorkflow(t,i.error.message),i}catch(r){let i=g(r);return this.failWorkflow(t,i.message),m(i)}}getProductFactorsBridge(){return this.productFactorsBridge}async storeC4DiagramsInMemory(u,a){let t=`c4-diagrams:latest:${this.hashCode(u)}`;await this.memory.set(t,a,{namespace:"code-intelligence",persist:!0,ttl:36e5}),await this.memory.set(`c4-components:${this.hashCode(u)}`,a.components,{namespace:"code-intelligence",ttl:36e5}),await this.memory.set(`c4-external-systems:${this.hashCode(u)}`,a.externalSystems,{namespace:"code-intelligence",ttl:36e5})}async collectProjectMetrics(u){if(!this.config.enableMetricCollector||!this.metricCollector)return m(new Error("MetricCollector is not enabled"));try{su.info(`Collecting real metrics for ${u}`);let a=await this.metricCollector.collectAll(u),t=a.toolsUsed.length>0?a.toolsUsed.join(", "):a.loc.source==="node-native"?"node-native":"fallback";if(su.info(`[CodeIntelligence] Real metrics collected: ${a.loc.total} LOC, ${a.tests.total} tests, tools: ${t}`),a.loc.source==="node-native"&&su.info("[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)"),await this.storeProjectMetricsInMemory(u,a),this.config.publishEvents){let r=L("code-intelligence.MetricsCollected","code-intelligence",{projectPath:u,loc:a.loc.total,tests:a.tests.total,toolsUsed:a.toolsUsed});await this.eventBus.publish(r)}return{success:!0,value:a}}catch(a){let t=g(a);return su.error("Failed to collect metrics:"),m(t)}}async storeProjectMetricsInMemory(u,a){let t=`project-metrics:latest:${this.hashCode(u)}`;await this.memory.set(t,a,{namespace:"code-intelligence",persist:!0,ttl:3e5}),await this.memory.set(`loc-metrics:${this.hashCode(u)}`,a.loc,{namespace:"code-intelligence",ttl:3e5}),await this.memory.set(`test-metrics:${this.hashCode(u)}`,a.tests,{namespace:"code-intelligence",ttl:3e5})}getMetricCollector(){return this.metricCollector}getProjectRootFromPaths(u){if(u.length===0)return null;let a=u[0],t=a.split("/"),r="";for(let n of t){r=r?`${r}/${n}`:n;let o=["package.json","Cargo.toml","go.mod","pyproject.toml",".git"];for(let l of o)try{let c=`${r}/${l}`;if(Ji("fs").existsSync(c))return r}catch{}}let i=a.lastIndexOf("/");return i>0?a.substring(0,i):a}isHypergraphEnabled(){return this.config.enableHypergraph&&this.hypergraph!==void 0}async findUntestedFunctions(){return this.hypergraph?J1(this.hypergraph,this.eventBus,this.config.publishEvents):m(new Error("Hypergraph is not enabled or not initialized"))}async findImpactedTestsFromHypergraph(u){return this.hypergraph?U1(this.hypergraph,u,this.eventBus,this.config.publishEvents):m(new Error("Hypergraph is not enabled or not initialized"))}async findCoverageGapsFromHypergraph(u=50){return this.hypergraph?Z1(this.hypergraph,u,this.eventBus,this.config.publishEvents):m(new Error("Hypergraph is not enabled or not initialized"))}async buildHypergraphFromIndex(u){return this.hypergraph?Q1(this.hypergraph,u,this.memory,this.eventBus,this.config.publishEvents):m(new Error("Hypergraph is not enabled or not initialized"))}getHypergraph(){return this.hypergraph}async enhanceImpactWithHypergraph(u,a){return this.hypergraph?Y1(this.hypergraph,u,a):a}async buildCodeIndexResultFromPaths(u){let{extractCodeIndex:a}=await import("./code-index-extractor-5SERI6TM.js");return a(u)}async verifyCodePatternDetection(u,a){return X1(u,a,this.consensusMixin,this.domainName)}async verifyImpactAnalysis(u,a){return uE(u,a,this.consensusMixin,this.domainName)}async verifyDependencyMapping(u,a){return eE(u,a,this.consensusMixin,this.domainName)}};S();var ni=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.paths;if(!a||a.length===0)return m(new Error("Invalid index payload: missing paths"));let t=u.language?[u.language]:u.languages;return this.coordinator.index({paths:a,languages:t})}],["search",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.query;return a?this.coordinator.search({query:a,type:u.type??"semantic",limit:u.limit}):m(new Error("Invalid search payload: missing query"))}],["analyze-impact",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.changedFiles;return!a||a.length===0?m(new Error("Invalid analyze-impact payload: missing changedFiles")):this.coordinator.analyzeImpact({changedFiles:a})}],["query-dependencies",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.file,r=u.files??(a?[a]:void 0);return!r||r.length===0?m(new Error("Invalid query-dependencies payload: missing file or files")):this.coordinator.mapDependencies({files:r,direction:u.direction??"both",depth:u.depth})}]])}async onInitialize(){this.knowledgeGraph=new ze(this.memory,this.pluginConfig.knowledgeGraph),this.semanticAnalyzer=new Ue(this.memory,this.pluginConfig.semanticAnalyzer),this.impactAnalyzer=new ea(this.memory,this.knowledgeGraph,this.pluginConfig.impactAnalyzer),this.coordinator=new Qa(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"test-generation.TestGenerated":await this.handleTestGenerated(u);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(u);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPredicted(u);break;default:break}}async index(u){this.ensureInitialized();try{let a=await this.coordinator.index(u);return a.success?this.trackSuccessfulOperation("index",a.value):this.trackFailedOperation("index",a.error),a}catch(a){return this.handleError(a)}}async search(u){this.ensureInitialized();try{let a=await this.coordinator.search(u);return a.success?this.trackSuccessfulOperation("search",a.value):this.trackFailedOperation("search",a.error),a}catch(a){return this.handleError(a)}}async analyzeImpact(u){this.ensureInitialized();try{let a=await this.coordinator.analyzeImpact(u);return a.success?this.trackSuccessfulOperation("impact",a.value):this.trackFailedOperation("impact",a.error),a}catch(a){return this.handleError(a)}}async mapDependencies(u){this.ensureInitialized();try{let a=await this.coordinator.mapDependencies(u);return a.success?this.trackSuccessfulOperation("dependency",a.value):this.trackFailedOperation("dependency",a.error),a}catch(a){return this.handleError(a)}}async queryKG(u){this.ensureInitialized();try{let a=await this.coordinator.queryKG(u);return a.success?this.trackSuccessfulOperation("query",a.value):this.trackFailedOperation("query",a.error),a}catch(a){return this.handleError(a)}}async getMetrics(){this.ensureInitialized();try{let u=this.getHealth();return{success:!0,value:{indexed:u.agents.total,queries:u.agents.idle,impacts:u.agents.active}}}catch(u){return this.handleError(u)}}async handleTestGenerated(u){let a=u.payload;await this.memory.set(`code-intelligence:test-mapping:${a.testId}`,{testFile:a.testFile,sourceFile:a.sourceFile,generatedAt:new Date().toISOString()},{namespace:"code-intelligence",ttl:86400*30})}async handleCoverageGap(u){let a=u.payload;await this.memory.set(`code-intelligence:coverage-gap:${a.gapId}`,a,{namespace:"code-intelligence",ttl:86400*7})}async handleDefectPredicted(u){let a=u.payload;await this.memory.set(`code-intelligence:defect-prediction:${a.predictionId}`,a,{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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u,a){let t=this.getHealth();this.updateHealth({agents:{...t.agents,total:t.agents.total+1,idle:t.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u,a){let t=this.getHealth();this.updateHealth({agents:{...t.agents,failed:t.agents.failed+1},errors:[...t.errors.slice(-9),a.message]})}};function pl(s,e,u,a){return new ni(s,e,u,a)}N();S();var yu=class s{constructor(e){this._value=e;if(!e||e.trim()==="")throw new Error("FilePath cannot be empty")}get value(){return this._value}get extension(){let e=this._value.split(".");return e.length>1?e[e.length-1]:""}get directory(){let e=this._value.lastIndexOf("/");return e>0?this._value.substring(0,e):""}get filename(){let e=this._value.lastIndexOf("/");return e>=0?this._value.substring(e+1):this._value}equals(e){return this._value===e._value}static create(e){return new s(e)}};var P0=class s{constructor(e){this._value=e;if(e<0||e>1)throw new Error("RiskScore must be between 0 and 1")}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(e){return this._value>e._value}equals(e){return this._value===e._value}static create(e){return new s(e)}static fromPercentage(e){return new s(e/100)}},Ju=class s{constructor(e,u){this._start=e;this._end=u;if(e>u)throw new Error("Start date cannot be after end date")}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(e){return e>=this._start&&e<=this._end}overlaps(e){return this._start<=e._end&&e._start<=this._end}equals(e){return this._start.getTime()===e._start.getTime()&&this._end.getTime()===e._end.getTime()}static create(e,u){return new s(e,u)}static lastNDays(e){let u=new Date,a=new Date(u.getTime()-e*24*60*60*1e3);return new s(a,u)}},Xe=class s{constructor(e,u,a,t){this._major=e;this._minor=u;this._patch=a;this._prerelease=t}get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let e=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${e}-${this._prerelease}`:e}isNewerThan(e){return this._major!==e._major?this._major>e._major:this._minor!==e._minor?this._minor>e._minor:this._patch>e._patch}equals(e){return this._major===e._major&&this._minor===e._minor&&this._patch===e._patch&&this._prerelease===e._prerelease}static create(e,u,a,t){return new s(e,u,a,t)}static parse(e){let u=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!u)throw new Error(`Invalid version format: ${e}`);return new s(parseInt(u[1]),parseInt(u[2]),parseInt(u[3]),u[4])}};var oi={defaultRuleSets:["owasp-top-10","cwe-sans-25"],maxConcurrentScans:4,timeout:3e5,enableFalsePositiveDetection:!0,dastMaxDepth:5,dastActiveScanning:!1,enableLLMAnalysis:!0,llmModelTier:4,enableSemgrep:!0};N();var gl=[{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"}],Cl=[{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"}],Al=[{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"}],yl=[{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"}],xl=[{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"}],fl=[{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())"}],vl=[{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"}],Fl=[{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"] })'}],si=[...gl,...Cl,...Al,...yl,...xl,...fl,...vl,...Fl],Ya=[{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"]}];S();J();S();J();import{execFile as uCu}from"child_process";import{promisify as eCu}from"util";import*as rE from"path";var bl=eCu(uCu);async function Xa(){try{return await bl("semgrep",["--version"],{timeout:5e3}),!0}catch{return!1}}async function aE(){try{let{stdout:s}=await bl("semgrep",["--version"],{timeout:5e3});return s.trim()}catch{return null}}async function aCu(s){let e={target:s.target||".",config:s.config||"auto",exclude:s.exclude||["node_modules",".git","dist","build","coverage"],maxFileSize:s.maxFileSize||5e6,timeout:s.timeout||300,verbose:s.verbose||!1};if(!await Xa())return{success:!1,findings:[],errors:["Semgrep is not installed. Install with: pip install semgrep"]};try{let a=["scan",`--config=${e.config}`,"--json",e.verbose?"--verbose":"--quiet",`--max-target-bytes=${e.maxFileSize}`];for(let o of e.exclude)a.push(`--exclude=${o}`);a.push(e.target);let t=(e.timeout??300)*1e3,{stdout:r,stderr:i}=await bl("semgrep",a,{timeout:t,maxBuffer:50*1024*1024,cwd:rE.isAbsolute(e.target)?void 0:process.cwd()}),n=tE(r);return i&&e.verbose&&n.errors.push(i),n.version=await aE()||void 0,n}catch(a){let t=a;if(t.stdout)try{let r=tE(t.stdout);return r.version=await aE()||void 0,r}catch{}return{success:!1,findings:[],errors:[t.message??String(a)]}}}function tE(s){try{let e=T(s),u=e.results||e.findings||[],a=e.errors?.map(t=>t.message||String(t))||[];return{success:!0,findings:u.map(t=>({check_id:t.check_id||t.rule_id||"unknown",path:t.path,start:{line:t.start?.line||1,col:t.start?.col||1},end:{line:t.end?.line||t.start?.line||1,col:t.end?.col||1},extra:{message:t.extra?.message||t.message||"Security issue detected",severity:t.extra?.severity||t.severity||"WARNING",lines:t.extra?.lines||"",metadata:{cwe:t.extra?.metadata?.cwe||t.metadata?.cwe,owasp:t.extra?.metadata?.owasp||t.metadata?.owasp,category:t.extra?.metadata?.category||t.metadata?.category,description:t.extra?.metadata?.description||t.metadata?.description,fix:t.extra?.metadata?.fix||t.extra?.fix,references:t.extra?.metadata?.references||t.metadata?.references,confidence:t.extra?.metadata?.confidence||t.metadata?.confidence}}})),errors:a}}catch(e){return{success:!1,findings:[],errors:[`Failed to parse semgrep output: ${k(e)}`]}}}async function li(s,e,u){let a={"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"},t=e.map(r=>a[r]||`p/${r}`).join(",");return aCu({...u,target:s,config:t||"auto"})}function tCu(s){return{ERROR:"high",WARNING:"medium",INFO:"low"}[s]||"medium"}function ci(s){return s.map(e=>({id:e.check_id,title:e.check_id.split(".").pop()||e.check_id,description:e.extra.message,severity:tCu(e.extra.severity),file:e.path,line:e.start.line,column:e.start.col,snippet:e.extra.lines,cweId:e.extra.metadata?.cwe?.[0],owaspCategory:e.extra.metadata?.owasp?.[0],remediation:e.extra.metadata?.fix||"Review and fix the identified security issue",references:e.extra.metadata?.references||[]}))}var rCu=B.create("security-compliance/sast-scanner"),z0=class{config;memory;llmRouter;activeScans;constructor(e,u,a,t){this.config=e,this.memory=u,this.llmRouter=a,this.activeScans=t||new Map}async scanFiles(e){return this.scanWithRules(e,this.config.defaultRuleSets)}async scanWithRules(e,u){let a=A();try{if(e.length===0)return m(new Error("No files provided for scanning"));this.activeScans.set(a,"running");let t=Date.now(),r=Ya.filter(h=>u.includes(h.id));if(r.length===0)return m(new Error(`No valid rule sets found: ${u.join(", ")}`));let[i,n]=await Promise.all([this.runPatternScanning(e,r),this.runSemgrepScanning(e,u)]),o=this.mergeVulnerabilities(i.vulnerabilities,n),l=i.linesScanned,c=Date.now()-t,E=this.calculateSummary(o,e.length,c),d=r.reduce((h,C)=>h+C.ruleCount,0),D={filesScanned:e.length,linesScanned:l,rulesApplied:d+(n.length>0?n.length:0)};return await this.storeScanResults(a,"sast",o,E),this.activeScans.set(a,"completed"),p({scanId:a,vulnerabilities:o,summary:E,coverage:D})}catch(t){return this.activeScans.set(a,"failed"),m(g(t))}}async runPatternScanning(e,u){let a=[],t=0;for(let r of e){let i=await this.analyzeFile(r,u);a.push(...i.vulnerabilities),t+=i.linesScanned}return{vulnerabilities:a,linesScanned:t}}async runSemgrepScanning(e,u){if(!this.config.enableSemgrep)return[];try{if(!await Xa())return[];let t=this.resolveTargetDirectory(e),r=await li(t,u);return!r.success||r.findings.length===0?[]:ci(r.findings).map(n=>({id:A(),cveId:void 0,title:n.title,description:`[semgrep] ${n.description}`,severity:n.severity,category:this.mapSemgrepCategory(n.owaspCategory),location:{file:n.file,line:n.line,column:n.column,snippet:n.snippet},remediation:{description:n.remediation,estimatedEffort:"moderate",automatable:!1},references:n.references}))}catch{return[]}}resolveTargetDirectory(e){if(e.length===0)return".";if(e.length===1)return e[0].directory||".";let u=e.map(n=>n.directory||"."),a=u[0],t=a.length;for(let n=1;n<u.length;n++){let o=u[n],l=Math.min(t,o.length),c=0;for(;c<l&&a[c]===o[c];)c++;t=c}let r=a.substring(0,t),i=r.lastIndexOf("/");return i>0?r.substring(0,i):r||"."}mapSemgrepCategory(e){if(!e)return"injection";let u={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[a,t]of Object.entries(u))if(e.startsWith(a))return t;return"injection"}mergeVulnerabilities(e,u){if(u.length===0)return e;if(e.length===0)return u;let a=new Set(e.map(r=>`${r.location.file}:${r.location.line??0}:${r.category}`)),t=u.filter(r=>!a.has(`${r.location.file}:${r.location.line??0}:${r.category}`));return[...e,...t]}async getAvailableRuleSets(){let e=await this.memory.get("security:custom-rule-sets");return[...Ya,...e||[]]}async checkFalsePositive(e){try{if(!this.config.enableFalsePositiveDetection)return p({isFalsePositive:!1,confidence:0,reason:"False positive detection is disabled"});let u=await this.analyzeFalsePositive(e);return await this.memory.set(`security:fp-check:${e.id}`,{vulnerability:e,analysis:u},{namespace:"security-compliance",ttl:86400*30}),p(u)}catch(u){return m(g(u))}}async analyzeFile(e,u){let a=[],t=e.value,r=e.extension,i,n;try{i=await(await import("fs/promises")).readFile(t,"utf-8"),n=i.split(`
2900
2900
  `)}catch{return{vulnerabilities:[],linesScanned:0}}let o=n.length;if(!["ts","tsx","js","jsx","mjs","cjs"].includes(r))return{vulnerabilities:[],linesScanned:o};let c=new Set(u.flatMap(d=>d.categories)),E=si.filter(d=>c.has(d.category));for(let d of E){let D=this.findPatternMatches(i,n,d);for(let h of D)this.isInComment(i,h.index)||this.isInDocumentation(h.snippet)||this.hasNosecAnnotation(n,h.line)||a.push(this.createVulnerabilityFromPattern(d,t,h))}return{vulnerabilities:a,linesScanned:o}}findPatternMatches(e,u,a){let t=[],r=new RegExp(a.pattern.source,a.pattern.flags),i;for(;(i=r.exec(e))!==null;){let n=i.index,{line:o,column:l}=this.getLineAndColumn(e,n),c=[],E=Math.max(0,o-2),d=Math.min(u.length-1,o+1);for(let h=E;h<=d;h++)c.push(u[h]);let D=c.join(`
2901
2901
  `);t.push({index:n,line:o+1,column:l+1,snippet:D})}return t}getLineAndColumn(e,u){let t=e.substring(0,u).split(`
2902
2902
  `),r=t.length-1,i=t[t.length-1].length;return{line:r,column:i}}isInComment(e,u){let a=e.substring(0,u),t=a.lastIndexOf(`
2903
- `),r=a.substring(t+1);if(r.includes("//")){let o=r.indexOf("//");if(u-(a.length-r.length)>o)return!0}let i=a.lastIndexOf("/*"),n=a.lastIndexOf("*/");return i>n}isInDocumentation(e){return[/\*\s*@example/i,/\*\s*@description/i,/\/\/\s*example:/i,/\/\/\s*e\.g\./i,/```[\s\S]*```/].some(a=>a.test(e))}hasNosecAnnotation(e,u){let a=u-1;if(a<0||a>=e.length)return!1;let t=e[a],r=a>0?e[a-1]:"";return[/\/\/\s*nosec/i,/\/\/\s*security-ignore/i,/\/\*\s*nosec\s*\*\//i,/#\s*nosec/i].some(n=>n.test(t)||n.test(r))}createVulnerabilityFromPattern(e,u,a){let t={file:u,line:a.line,column:a.column,snippet:a.snippet},r={description:e.remediation,fixExample:e.fixExample,estimatedEffort:this.getEffortForSeverity(e.severity),automatable:e.severity==="low"||e.severity==="informational"};return{id:A(),cveId:void 0,title:e.title,description:`${e.description} [${e.cweId}]`,severity:e.severity,category:e.category,location:t,remediation:r,references:[`https://owasp.org/Top10/${e.owaspId.replace(":","_")}/`,`https://cwe.mitre.org/data/definitions/${e.cweId.replace("CWE-","")}.html`]}}getEffortForSeverity(e){return{critical:"major",high:"moderate",medium:"minor",low:"trivial",informational:"trivial"}[e]}async analyzeFalsePositive(e){let u=!1,a=.5,t="Manual review recommended";return e.severity==="informational"&&(a=.3,t="Low severity findings often require manual verification"),(e.location.snippet?.includes("test")||e.location.file.includes("test"))&&(u=!0,a=.8,t="Vulnerability found in test code"),e.location.snippet?.includes("// nosec")&&(u=!0,a=.95,t="Explicitly marked as ignored with nosec comment"),{isFalsePositive:u,confidence:a,reason:t}}calculateSummary(e,u,a){let t={critical:0,high:0,medium:0,low:0,informational:0,totalFiles:u,scanDurationMs:a};for(let r of e)t[r.severity]++;return t}async storeScanResults(e,u,a,t){let r={scanId:e,scanType:u,summary:t,timestamp:new Date().toISOString(),vulnerabilityCount:a.length,criticalVulnerabilities:a.filter(i=>i.severity==="critical"||i.severity==="high")};await this.memory.set(`security:scan:${e}`,r,{namespace:"security-compliance",ttl:86400*2})}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(e){switch(e){case 1:return"claude-3-5-haiku-20241022";case 2:return"claude-sonnet-4-20250514";case 3:return"claude-sonnet-4-20250514";case 4:return"claude-opus-4-5-20251101";default:return"claude-opus-4-5-20251101"}}async analyzeVulnerabilityWithLLM(e,u){if(!this.llmRouter)return this.getDefaultRemediation(e);try{let a=this.getModelForTier(this.config.llmModelTier),t=await this.llmRouter.chat({messages:[{role:"system",content:`You are a senior security engineer. Analyze the vulnerability and provide:
2903
+ `),r=a.substring(t+1);if(r.includes("//")){let o=r.indexOf("//");if(u-(a.length-r.length)>o)return!0}let i=a.lastIndexOf("/*"),n=a.lastIndexOf("*/");return i>n}isInDocumentation(e){return[/\*\s*@example/i,/\*\s*@description/i,/\/\/\s*example:/i,/\/\/\s*e\.g\./i,/```[\s\S]*```/].some(a=>a.test(e))}hasNosecAnnotation(e,u){let a=u-1;if(a<0||a>=e.length)return!1;let t=e[a],r=a>0?e[a-1]:"";return[/\/\/\s*nosec/i,/\/\/\s*security-ignore/i,/\/\*\s*nosec\s*\*\//i,/#\s*nosec/i].some(n=>n.test(t)||n.test(r))}createVulnerabilityFromPattern(e,u,a){let t={file:u,line:a.line,column:a.column,snippet:a.snippet},r={description:e.remediation,fixExample:e.fixExample,estimatedEffort:this.getEffortForSeverity(e.severity),automatable:e.severity==="low"||e.severity==="informational"};return{id:A(),cveId:void 0,title:e.title,description:`${e.description} [${e.cweId}]`,severity:e.severity,category:e.category,location:t,remediation:r,references:[`https://owasp.org/Top10/${e.owaspId.replace(":","_")}/`,`https://cwe.mitre.org/data/definitions/${e.cweId.replace("CWE-","")}.html`]}}getEffortForSeverity(e){return{critical:"major",high:"moderate",medium:"minor",low:"trivial",informational:"trivial"}[e]}async analyzeFalsePositive(e){let u=!1,a=.5,t="Manual review recommended";return e.severity==="informational"&&(a=.3,t="Low severity findings often require manual verification"),(e.location.snippet?.includes("test")||e.location.file.includes("test"))&&(u=!0,a=.8,t="Vulnerability found in test code"),e.location.snippet?.includes("// nosec")&&(u=!0,a=.95,t="Explicitly marked as ignored with nosec comment"),{isFalsePositive:u,confidence:a,reason:t}}calculateSummary(e,u,a){let t={critical:0,high:0,medium:0,low:0,informational:0,totalFiles:u,scanDurationMs:a};for(let r of e)t[r.severity]++;return t}async storeScanResults(e,u,a,t){let r={scanId:e,scanType:u,summary:t,timestamp:new Date().toISOString(),vulnerabilityCount:a.length,criticalVulnerabilities:a.filter(i=>i.severity==="critical"||i.severity==="high")};await this.memory.set(`security:scan:${e}`,r,{namespace:"security-compliance",ttl:86400*2})}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(e){switch(e){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-opus-4-7"}}async analyzeVulnerabilityWithLLM(e,u){if(!this.llmRouter)return this.getDefaultRemediation(e);try{let a=this.getModelForTier(this.config.llmModelTier),t=await this.llmRouter.chat({messages:[{role:"system",content:`You are a senior security engineer. Analyze the vulnerability and provide:
2904
2904
  1. Detailed explanation of the risk
2905
2905
  2. Code example showing the fix
2906
2906
  3. Effort estimate (trivial/minor/moderate/major)
@@ -2928,7 +2928,7 @@ Provide detailed remediation advice specific to this code.`}],model:a,maxTokens:
2928
2928
  `),X=V.length,Bu=V[V.length-1].length+1,eu=b[X-1]||"";if(eu.trimStart().startsWith("//")||eu.trimStart().startsWith("*")||eu.includes("// nosec")||eu.includes("// security-ignore"))continue;let q=Math.max(0,X-2),lu=Math.min(b.length,X+1),au=b.slice(q,lu).join(`
2929
2929
  `),r3={file:C,line:X,column:Bu,snippet:au},i3={description:R.remediation,fixExample:R.fixExample,estimatedEffort:R.severity==="critical"?"moderate":"minor",automatable:R.severity==="low"||R.severity==="medium"};t.push({id:A(),cveId:void 0,title:R.title,description:`${R.description} [${R.cweId}]`,severity:R.severity,category:R.category,location:r3,remediation:i3,references:[`https://cwe.mitre.org/data/definitions/${R.cweId.replace("CWE-","")}.html`]})}}}catch{}}}catch(D){pCu.error("SAST scan failed:",D instanceof Error?D:void 0)}let n=Date.now()-a,o=0,l=0,c=0,E=0,d=0;for(let D of t)switch(D.severity){case"critical":o++;break;case"high":l++;break;case"medium":c++;break;case"low":E++;break;case"informational":d++;break}return{scanId:u,vulnerabilities:t,summary:{critical:o,high:l,medium:c,low:E,informational:d,totalFiles:r,scanDurationMs:n},coverage:{filesScanned:r,linesScanned:i,rulesApplied:12}}}N();S();var CCu=B.create("security-compliance/security-auditor-dast");async function gE(s){let e=A(),u=Date.now(),a=[],t=0;try{let E;try{E=new URL(s)}catch{return{scanId:e,targetUrl:s,vulnerabilities:[{id:A(),title:"Invalid Target URL",description:"The provided target URL is not valid",severity:"informational",category:"security-misconfiguration",location:{file:s},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()-u},crawledUrls:0}}let d=new AbortController,D=setTimeout(()=>d.abort(),3e4);try{let h=await fetch(s,{method:"GET",headers:{"User-Agent":"AgenticQE-SecurityScanner/3.0",Accept:"text/html,application/json,*/*"},signal:d.signal,redirect:"follow"});clearTimeout(D),t=1;let C=h.headers,y=[{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 w of y)C.get(w.header)||a.push({id:A(),title:w.title,description:w.description,severity:w.severity,category:"security-misconfiguration",location:{file:s,snippet:`Response Headers: ${w.header} not present`},remediation:{description:w.remediation,estimatedEffort:"minor",automatable:!0},references:["https://owasp.org/www-project-secure-headers/"]});let x=C.get("set-cookie");x&&(x.toLowerCase().includes("secure")||a.push({id:A(),title:"Cookie Without Secure Flag",description:"Session cookie is set without the Secure flag",severity:"medium",category:"sensitive-data",location:{file:s,snippet:`Set-Cookie: ${x.substring(0,50)}...`},remediation:{description:"Add Secure flag to cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/controls/SecureCookieAttribute"]}),x.toLowerCase().includes("httponly")||a.push({id:A(),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:s,snippet:`Set-Cookie: ${x.substring(0,50)}...`},remediation:{description:"Add HttpOnly flag to session cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/HttpOnly"]}),x.toLowerCase().includes("samesite")||a.push({id:A(),title:"Cookie Without SameSite Attribute",description:"Cookie is set without the SameSite attribute, potentially vulnerable to CSRF",severity:"low",category:"broken-auth",location:{file:s,snippet:`Set-Cookie: ${x.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 b=C.get("server");b&&/[0-9]+\.[0-9]+/.test(b)&&a.push({id:A(),title:"Server Version Disclosure",description:`Server header reveals version information: ${b}`,severity:"low",category:"security-misconfiguration",location:{file:s,snippet:`Server: ${b}`},remediation:{description:"Remove or obfuscate server version information",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}),E.protocol==="http:"&&a.push({id:A(),title:"Insecure HTTP Protocol",description:"Target is using HTTP instead of HTTPS, exposing data in transit",severity:"high",category:"sensitive-data",location:{file:s},remediation:{description:"Use HTTPS with valid TLS certificate",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]});let R=[{path:"/.git/config",vuln:"Git Repository Exposed",severity:"high"},{path:"/.env",vuln:"Environment File Exposed",severity:"critical"},{path:"/phpinfo.php",vuln:"PHP Info Exposed",severity:"medium"},{path:"/wp-config.php.bak",vuln:"WordPress Config Backup Exposed",severity:"critical"}];for(let w of R)try{let P=new URL(w.path,E.origin).toString(),V=await fetch(P,{method:"GET",signal:AbortSignal.timeout(5e3)});if(V.ok&&V.status===200){let X=await V.text();X.length>10&&!X.toLowerCase().includes("not found")&&(t++,a.push({id:A(),title:w.vuln,description:`Sensitive file found at ${w.path}`,severity:w.severity,category:"sensitive-data",location:{file:P},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(D);let C=k(h);(C.includes("certificate")||C.includes("SSL")||C.includes("TLS"))&&a.push({id:A(),title:"TLS/SSL Certificate Issue",description:`Certificate error: ${C}`,severity:"high",category:"security-misconfiguration",location:{file:s},remediation:{description:"Fix TLS certificate configuration",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}catch(E){CCu.error("DAST scan failed:",E instanceof Error?E:void 0)}let r=Date.now()-u,i=0,n=0,o=0,l=0,c=0;for(let E of a)switch(E.severity){case"critical":i++;break;case"high":n++;break;case"medium":o++;break;case"low":l++;break;case"informational":c++;break}return{scanId:e,targetUrl:s,vulnerabilities:a,summary:{critical:i,high:n,medium:o,low:l,informational:c,totalFiles:1,scanDurationMs:r},crawledUrls:t}}N();import*as CE from"fs/promises";var ACu=B.create("security-compliance/security-auditor-secrets");function yCu(){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 xCu(s){if(!s||s.length===0)return 0;let e={};for(let t of s)e[t]=(e[t]||0)+1;let u=0,a=s.length;for(let t in e){let r=e[t]/a;u-=r*Math.log2(r)}return u}function fCu(s,e,u){let r=Math.max(0,e-20),i=Math.min(s.length,e+u+10),n=s.substring(r,i),o=e-r,l=n.substring(o,o+u);if(l.length>8){let c=l.substring(0,4)+"..."+l.substring(l.length-4);n=n.substring(0,o)+c+n.substring(o+u)}return r>0&&(n="..."+n),i<s.length&&(n=n+"..."),n}function vCu(s,e){switch(s){case"api-key":return e.length>=20&&/[a-z]/.test(e)&&/[A-Z0-9]/.test(e);case"token":return e.length>=20;case"password":return!["password","secret","changeme","12345678","qwerty"].includes(e.toLowerCase());case"private-key":return!0;case"certificate":return!0;default:return!0}}async function Nl(s){let e=[];try{let a=(await CE.readFile(s.value,"utf-8")).split(`
2930
2930
  `),t=yCu();for(let r=0;r<a.length;r++){let i=a[r],n=r+1;for(let o of t){o.regex.lastIndex=0;let l;for(;(l=o.regex.exec(i))!==null;){let c=l[1]||l[0],E=xCu(c);if(o.entropyThreshold&&E<o.entropyThreshold)continue;let d=fCu(i,l.index,c.length),D={file:s.value,line:n,column:l.index+1,snippet:d};e.push({type:o.type,location:D,entropy:E,isValid:vCu(o.type,c)})}}}}catch(u){ACu.error(`Failed to scan file for secrets: ${s.value}`,u instanceof Error?u:void 0)}return e}function AE(s,e,u,a){let t=0,r=0;if(s&&(t+=Il(s.summary)*.35,r+=.35),e&&(t+=Il(e.summary)*.25,r+=.25),u&&(t+=Il(u.summary)*.25,r+=.25),a){let n=a.secretsFound.length>0?.9:.1;t+=n*.15,r+=.15}let i=r>0?t/r:0;return{value:Math.min(1,i),percentage:i*100,level:i>=.8?"critical":i>=.6?"high":i>=.3?"medium":"low"}}function Il(s){let e={critical:1,high:.7,medium:.4,low:.1,informational:.02};if(s.critical+s.high+s.medium+s.low+s.informational===0)return 0;let a=s.critical*e.critical+s.high*e.high+s.medium*e.medium+s.low*e.low+s.informational*e.informational;return Math.min(1,a/10)}function yE(s,e,u,a){let t=[];return s&&s.summary.critical>0&&t.push(`Address ${s.summary.critical} critical vulnerabilities found in static analysis`),e&&e.summary.high>0&&t.push(`Fix ${e.summary.high} high-severity issues found in dynamic testing`),u&&u.outdatedPackages.length>5&&t.push(`Update ${u.outdatedPackages.length} outdated dependencies`),a&&a.secretsFound.length>0&&t.push(`Remove ${a.secretsFound.length} exposed secrets and rotate credentials`),t.length===0&&t.push("Security posture is good. Continue regular scanning."),t}function Kl(s,e){if(!s)return 0;let u=0;return s.sastResults&&(u+=s.sastResults.summary[e]),s.dastResults&&(u+=s.dastResults.summary[e]),s.dependencyResults&&(u+=s.dependencyResults.summary[e]),u}function I0(s){if(!s)return 0;let e=0;return s.sastResults&&(e+=s.sastResults.vulnerabilities.length),s.dastResults&&(e+=s.dastResults.vulnerabilities.length),s.dependencyResults&&(e+=s.dependencyResults.vulnerabilities.length),e}function xE(s,e){if(!s||!e)return"stable";let u=I0(s),a=I0(e);return u<a*.9?"improving":u>a*1.1?"declining":"stable"}function fE(s,e,u){let a=100;return a-=s*20,a-=e*10,a-=u*2,Math.max(0,Math.min(100,a))}function vE(s,e,u){let a=[];return s>0&&a.push("Immediately address all critical vulnerabilities"),e>3&&a.push("Prioritize fixing high-severity issues"),u<50&&(a.push("Consider a comprehensive security review"),a.push("Implement automated security scanning in CI/CD")),u>=80&&(a.push("Maintain current security practices"),a.push("Consider penetration testing for deeper analysis")),a}function FE(s){let e=s.remediation.estimatedEffort;return s.severity==="critical"?"immediate":s.severity==="high"?e==="trivial"||e==="minor"?"immediate":"shortTerm":s.severity==="medium"?e==="major"?"longTerm":"mediumTerm":s.severity==="low"||s.severity==="informational"?"longTerm":"accepted"}var le=B.create("security-compliance/security-auditor"),u0=class{constructor(e,u={}){this.memory=e;this.config={...Ll,...u}}config;async scanDependencies(e){try{let u=e.value,a=this.detectEcosystem(u);if(!a)return m(new Error(`Unknown manifest format: ${u}`));let t=[],r=[],i=await this.parseDependencies(u,a);for(let o of i){let l=await this.checkDependencyVulnerabilities(o,a);t.push(...l);let c=await this.checkOutdated(o);c&&r.push(c)}let n=this.createDependencySummary(t,i.length);return await this.memory.set(`security:deps:${e.filename}`,{vulnerabilities:t,outdatedPackages:r,summary:n},{namespace:"security-compliance",ttl:86400}),p({vulnerabilities:t,outdatedPackages:r,summary:n})}catch(u){return m(g(u))}}async checkPackage(e,u,a){try{let t=await this.queryVulnerabilityDatabase(e,u,a),r=await this.getLatestVersion(e,a),i=await this.checkDeprecation(e,a);return p({name:e,version:u,vulnerabilities:t,latestVersion:r,isDeprecated:i})}catch(t){return m(g(t))}}async getUpgradeRecommendations(e){try{let u=[],a=new Map;for(let t of e){let r=t.location.dependency;if(r){let i=`${r.ecosystem}:${r.name}`,n=a.get(i)||[];n.push(t),a.set(i,n)}}for(let[t,r]of a){let[i,n]=t.split(":"),o=r[0].location.dependency?.version||"unknown",l=await this.getLatestVersion(n,i),c=r.filter(E=>E.id).map(E=>E.id);u.push({package:n,fromVersion:o,toVersion:l,fixesVulnerabilities:c,breakingChanges:this.hasBreakingChanges(o,l)})}return u.sort((t,r)=>r.fixesVulnerabilities.length-t.fixesVulnerabilities.length),p(u)}catch(u){return m(g(u))}}async runAudit(e){let u=A(),a=new Date;try{let t,r,i,n;e.includeSAST&&(t=await pE(E=>this.findSourceFiles(E),E=>this.shouldExclude(E))),e.includeDAST&&e.targetUrl&&(r=await gE(e.targetUrl)),e.includeDependencies&&(i=await this.performDependencyScan()),e.includeSecrets&&(n=await this.performSecretScan());let o=AE(t,r,i,n),l=yE(t,r,i,n),c={auditId:u,timestamp:a,sastResults:t,dastResults:r,dependencyResults:i,secretScanResults:n,overallRiskScore:o,recommendations:l};return await this.memory.set(`security:audit:${u}`,c,{namespace:"security-compliance",persist:!0}),p(c)}catch(t){return m(g(t))}}async scanSecrets(e){try{let u=[],a=0;for(let t of e){if(this.shouldExclude(t.value))continue;a++;let r=await Nl(t);u.push(...r)}return p({secretsFound:u,filesScanned:a})}catch(u){return m(g(u))}}async getSecurityPosture(){try{let e=await this.getRecentAudits(),u=e[0],a=e[1],t=Kl(u,"critical"),r=Kl(u,"high"),i=I0(u),n=xE(u,a),o=fE(t,r,i),l=vE(t,r,o);return p({overallScore:o,trend:n,criticalIssues:t,highIssues:r,openVulnerabilities:i,resolvedLastWeek:await this.countResolvedLastWeek(),averageResolutionTime:await this.calculateAverageResolutionTime(),lastAuditDate:u?.timestamp??new Date,recommendations:l})}catch(e){return m(g(e))}}async triageVulnerabilities(e){try{let u={immediate:[],shortTerm:[],mediumTerm:[],longTerm:[],accepted:[]};for(let t of e){let r=FE(t);u[r].push(t)}let a=["critical","high","medium","low","informational"];for(let t of Object.values(u))t.sort((r,i)=>a.indexOf(r.severity)-a.indexOf(i.severity));return p(u)}catch(u){return m(g(u))}}detectEcosystem(e){return e.includes("package.json")?"npm":e.includes("requirements.txt")||e.includes("Pipfile")?"pip":e.includes("pom.xml")||e.includes("build.gradle")?"maven":e.includes("Cargo.toml")?"cargo":e.includes(".csproj")||e.includes("packages.config")?"nuget":null}async parseDependencies(e,u){let a=[];try{if(u==="npm"){let t=await it.readFile(e,"utf-8"),r=T(t),i={...r.dependencies,...r.devDependencies,...r.peerDependencies,...r.optionalDependencies};for(let[n,o]of Object.entries(i)){let l=this.cleanVersionSpec(o);a.push({name:n,version:l,ecosystem:"npm"})}}else if(u==="pip"){let r=(await it.readFile(e,"utf-8")).split(`
2931
- `);for(let i of r){let n=i.trim();if(!n||n.startsWith("#"))continue;let o=n.match(/^([a-zA-Z0-9_-]+)(?:[=<>~!]+(.+))?$/);o&&a.push({name:o[1],version:o[2]||"latest",ecosystem:"pip"})}}}catch(t){le.error(`Failed to parse dependencies from ${e}:`,t instanceof Error?t:void 0)}return a}cleanVersionSpec(e){return e.replace(/^[\^~>=<]+/,"").trim()}async checkDependencyVulnerabilities(e,u){let a=[];try{let t=this.mapToOSVEcosystem(u),r={package:{name:e.name,ecosystem:t},version:e.version},i=await zl("https://api.osv.dev/v1/query",r);if(i.ok&&i.data.vulns&&i.data.vulns.length>0)for(let n of i.data.vulns){let o=this.mapOSVVulnerability(n,e);a.push(o)}}catch(t){le.error(`Failed to check vulnerabilities for ${e.name}@${e.version}:`,t instanceof Error?t:void 0)}return a}mapToOSVEcosystem(e){return{npm:"npm",pip:"PyPI",maven:"Maven",nuget:"NuGet",cargo:"crates.io"}[e]}mapOSVVulnerability(e,u){let a=e.aliases?.find(l=>l.startsWith("CVE-")),t=this.mapOSVSeverity(e.severity),r=this.extractFixedVersion(e),i=e.references?.map(l=>l.url)||[],n={file:"package.json",dependency:u},o={description:r?`Upgrade ${u.name} to version ${r} or higher`:`Review and address vulnerability in ${u.name}`,fixExample:r?`"${u.name}": "^${r}"`:void 0,estimatedEffort:r?"trivial":"moderate",automatable:!!r};return{id:A(),cveId:a,title:e.summary||`Vulnerability in ${u.name}`,description:e.details||e.summary||"No description available",severity:t,category:this.categorizeVulnerability(e),location:n,remediation:o,references:i}}mapOSVSeverity(e){if(!e||e.length===0)return"medium";let u=e.find(a=>a.type==="CVSS_V3"||a.type==="CVSS_V2");if(u){let a=parseFloat(u.score);if(a>=9)return"critical";if(a>=7)return"high";if(a>=4)return"medium";if(a>0)return"low"}return"medium"}extractFixedVersion(e){if(e.affected){for(let u of e.affected)if(u.ranges){for(let a of u.ranges)if(a.events){let t=a.events.find(r=>r.fixed);if(t?.fixed)return t.fixed}}}}categorizeVulnerability(e){let u=(e.summary||"").toLowerCase(),a=(e.details||"").toLowerCase(),t=`${u} ${a}`;return t.includes("injection")||t.includes("sql")?"injection":t.includes("xss")||t.includes("cross-site scripting")?"xss":t.includes("authentication")||t.includes("auth bypass")?"broken-auth":t.includes("sensitive data")||t.includes("exposure")?"sensitive-data":t.includes("xxe")||t.includes("xml external")?"xxe":t.includes("access control")||t.includes("authorization")?"access-control":t.includes("deseriali")?"insecure-deserialization":(t.includes("prototype pollution")||t.includes("dependency"),"vulnerable-components")}async checkOutdated(e){let u=await this.getLatestVersion(e.name,e.ecosystem);return u!==e.version?{name:e.name,currentVersion:e.version,latestVersion:u,updateType:this.determineUpdateType(e.version,u)}:null}async queryVulnerabilityDatabase(e,u,a){let t={name:e,version:u,ecosystem:a};return this.checkDependencyVulnerabilities(t,a)}async getLatestVersion(e,u){try{if(u==="npm"){let a=await rt(`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`);if(a.ok&&a.data.version)return a.data.version}else if(u==="pip"){let a=await rt(`https://pypi.org/pypi/${encodeURIComponent(e)}/json`);if(a.ok&&a.data.info?.version)return a.data.info.version}}catch(a){le.error(`Failed to get latest version for ${e}:`,a instanceof Error?a:void 0)}return"unknown"}async checkDeprecation(e,u){try{if(u==="npm"){let a=await rt(`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`);if(a.ok&&a.data.deprecated)return!0}}catch(a){le.error(`Failed to check deprecation for ${e}:`,a instanceof Error?a:void 0)}return!1}determineUpdateType(e,u){let a=e.split(".").map(Number),t=u.split(".").map(Number);return t[0]>a[0]?"major":t[1]>a[1]?"minor":"patch"}hasBreakingChanges(e,u){let a=parseInt(e.split(".")[0]);return parseInt(u.split(".")[0])>a}createDependencySummary(e,u){let a=0,t=0,r=0,i=0,n=0;for(let o of e)switch(o.severity){case"critical":a++;break;case"high":t++;break;case"medium":r++;break;case"low":i++;break;case"informational":n++;break}return{critical:a,high:t,medium:r,low:i,informational:n,totalFiles:u,scanDurationMs:0}}shouldExclude(e){return this.config.excludePatterns.some(u=>u.startsWith("*")?e.endsWith(u.slice(1)):e.includes(u))}async performDependencyScan(){let e=Date.now(),u=[],a=[];try{let t=nt.join(process.cwd(),"package.json"),r=await this.parseDependencies(t,"npm");for(let o of r){let l=await this.checkDependencyVulnerabilities(o,o.ecosystem);u.push(...l);let c=await this.checkOutdated(o);c&&a.push(c)}let i=Date.now()-e,n=this.createDependencySummary(u,r.length);return{vulnerabilities:u,outdatedPackages:a,summary:{...n,scanDurationMs:i}}}catch(t){return le.error("Dependency scan failed:",t instanceof Error?t:void 0),{vulnerabilities:[],outdatedPackages:[],summary:{critical:0,high:0,medium:0,low:0,informational:0,totalFiles:0,scanDurationMs:Date.now()-e}}}}async performSecretScan(){let e=[],u=0;try{let a=await this.findSourceFiles(process.cwd());for(let t of a){if(this.shouldExclude(t))continue;u++;let i=await Nl({value:t});e.push(...i)}}catch(a){le.error("Secret scan failed:",a instanceof Error?a:void 0)}return{secretsFound:e,filesScanned:u}}async findSourceFiles(e,u=[]){let a=[".ts",".js",".tsx",".jsx",".json",".env",".yaml",".yml",".config"];try{let t=await it.readdir(e,{withFileTypes:!0});for(let r of t){let i=nt.join(e,r.name);if(!this.shouldExclude(i)){if(r.isDirectory())await this.findSourceFiles(i,u);else if(r.isFile()){let n=nt.extname(r.name).toLowerCase();(a.includes(n)||r.name.startsWith(".env"))&&u.push(i)}}}}catch{le.debug("Directory read error:")}return u}async getRecentAudits(){let e=await this.memory.search("security:audit:*",10),u=[];for(let a of e){let t=await this.memory.get(a);t&&u.push(t)}return u.sort((a,t)=>new Date(t.timestamp).getTime()-new Date(a.timestamp).getTime())}async countResolvedLastWeek(){try{let e=await this.getRecentAudits();if(e.length<2)return 0;let u=new Date(Date.now()-10080*60*1e3),a=e.filter(o=>new Date(o.timestamp)>=u);if(a.length<2)return 0;let t=a[a.length-1],r=a[0],i=I0(t),n=I0(r);return Math.max(0,i-n)}catch(e){return le.error("Failed to count resolved vulnerabilities:",e instanceof Error?e:void 0),0}}async calculateAverageResolutionTime(){try{let e=await this.getRecentAudits();if(e.length<2)return 72;let u=new Map,a=[],t=[...e].reverse();for(let i of t){let n=new Set;i.sastResults&&i.sastResults.vulnerabilities.forEach(o=>n.add(o.id)),i.dastResults&&i.dastResults.vulnerabilities.forEach(o=>n.add(o.id)),i.dependencyResults&&i.dependencyResults.vulnerabilities.forEach(o=>n.add(o.id));for(let o of n)u.has(o)||u.set(o,i.timestamp);for(let[o,l]of u)if(!n.has(o)){let c=(i.timestamp.getTime()-l.getTime())/36e5;a.push(c),u.delete(o)}}if(a.length===0)return 72;let r=a.reduce((i,n)=>i+n,0);return Math.round(r/a.length)}catch(e){return le.error("Failed to calculate average resolution time:",e instanceof Error?e:void 0),72}}};S();var FCu={customStandards:[],strictMode:!1,includeRecommended:!0,evidenceRetentionDays:365},bCu={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"}]},BCu={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"}]},kCu={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"}]},SCu={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"}]},wCu=[bCu,BCu,kCu,SCu],e0=class{constructor(e,u={}){this.memory=e;this.config={...FCu,...u},this.patternAnalyzer=Pl(),this.standards=new Map;for(let a of wCu)this.standards.set(a.id,a);for(let a of this.config.customStandards)this.standards.set(a.id,a)}config;standards;patternAnalyzer;async validate(e,u){try{let a=[],t=[],r=[],i=this.config.includeRecommended?e.rules:e.rules.filter(c=>c.severity==="required");for(let c of i){if(c.checkType==="manual"){r.push(c.id);continue}let E=await this.checkRule(c,u);E.passed?t.push(c.id):a.push(...E.violations)}let n=i.length-r.length,o=n>0?Math.round(t.length/n*100):100,l={standardId:e.id,standardName:e.name,violations:a,passedRules:t,skippedRules:r,complianceScore:o,generatedAt:new Date};return await this.storeReport(l),p(l)}catch(a){return m(g(a))}}async getAvailableStandards(){return Array.from(this.standards.values())}async analyzeGaps(e,u){try{let a=[],t=[],r=new Set(e.violations.map(c=>c.ruleId)),i=new Set(e.passedRules);for(let c of u.rules)r.has(c.id)?a.push({ruleId:c.id,currentStatus:"failed",effort:this.estimateEffort(c),impact:c.severity==="required"?"high":"medium"}):i.has(c.id)||a.push({ruleId:c.id,currentStatus:"not-implemented",effort:this.estimateEffort(c),impact:c.severity==="required"?"high":"low"});let n=[...a].sort((c,E)=>{let d={high:0,medium:1,low:2},D={trivial:0,minor:1,moderate:2,major:3},h=d[c.impact]*10+D[c.effort],C=d[E.impact]*10+D[E.effort];return h-C});for(let c=0;c<n.length;c++){let E=n[c],d=u.rules.find(D=>D.id===E.ruleId);t.push({id:A(),description:`Implement ${d?.title||E.ruleId}`,affectedRules:[E.ruleId],effort:E.effort,priority:c+1})}let o=100,l=e.complianceScore;return p({currentScore:l,targetScore:o,gaps:a,prioritizedActions:t})}catch(a){return m(g(a))}}async validateMultiple(e,u){try{let a=[],t=[];for(let n of e){let o=await this.validate(n,u);o.success&&a.push(o.value)}let r=new Map;for(let n of a)for(let o of n.violations){let l=`${o.location.file}:${o.location.line}`;r.set(l,(r.get(l)||0)+1)}for(let n of a)for(let o of n.violations){let l=`${o.location.file}:${o.location.line}`;(r.get(l)||0)>1&&(t.some(c=>c.location.file===o.location.file&&c.location.line===o.location.line)||t.push(o))}let i=a.length>0?Math.round(a.reduce((n,o)=>n+o.complianceScore,0)/a.length):0;return p({reports:a,overallScore:i,crossCuttingViolations:t})}catch(a){return m(g(a))}}async checkDataHandling(e,u){try{let a=new Map,t=[],r=[];for(let i of u)a.set(i,[]);for(let i of e){let n=await this.scanFileForDataTypes(i,u);for(let o of n){let l=a.get(o.type)||[];l.push(o.location),a.set(o.type,l);let c=this.checkDataTypeViolation(o);c&&t.push(c)}}for(let[i,n]of a)n.length>0&&r.push(...this.getDataTypeRecommendations(i,n.length));return p({dataTypesFound:a,violations:t,recommendations:[...new Set(r)]})}catch(a){return m(g(a))}}async generateEvidence(e,u){try{let a=this.standards.get(e);if(!a)return m(new Error(`Unknown standard: ${e}`));let t=await this.validate(a,u);if(!t.success)return m(t.error);let r=t.value,i=[];for(let o of a.rules){let l=r.passedRules.includes(o.id)?"implemented":r.skippedRules.includes(o.id)?"partial":"not-implemented";i.push({controlId:o.id,status:l,evidence:await this.collectEvidence(o,u),lastVerified:new Date})}let n={standardId:e,controls:i,generatedAt:new Date,validUntil:new Date(Date.now()+this.config.evidenceRetentionDays*24*60*60*1e3)};return await this.memory.set(`compliance:evidence:${e}:${Date.now()}`,n,{namespace:"security-compliance",persist:!0}),p(n)}catch(a){return m(g(a))}}async checkRule(e,u){let a=[],t=await this.getFilesFromContext(u);switch(e.category){case"encryption":a.push(...await this.checkEncryption(e,u,t));break;case"access-control":a.push(...await this.checkAccessControl(e,u,t));break;case"audit":case"logging":a.push(...await this.checkLogging(e,u,t));break;case"data-protection":case"data-quality":a.push(...await this.checkDataProtection(e,u,t));break;case"security":a.push(...await this.checkSecurityControls(e,u,t));break;default:break}return{passed:a.length===0,violations:a}}async getFilesFromContext(e){let u=[],a=e.projectRoot.value;if(e.includePatterns.length===0)return[];for(let t of e.includePatterns)e.excludePatterns.some(i=>t.includes(i)||i.includes(t))||u.push(`${a}/${t}`);return u}async checkEncryption(e,u,a){let t=[];if(a.length===0)return t;let r=await this.patternAnalyzer.analyzeEncryption(a);for(let i of r.weakCrypto)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Weak or deprecated cryptographic algorithm detected",remediation:"Use strong encryption algorithms (AES-256, SHA-256 or higher)"});for(let i of r.unencryptedDataHandling)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Sensitive data handled without encryption verification",remediation:"Ensure data is encrypted before processing sensitive information"});return t}async checkAccessControl(e,u,a){let t=[];if(a.length===0)return t;let r=await this.patternAnalyzer.analyzeAccessControl(a);for(let i of r.unprotectedRoutes)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Sensitive endpoint potentially missing authorization middleware",remediation:"Add authorization check before sensitive operations"});for(let i of r.hardcodedCredentials)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Hardcoded credentials detected",remediation:"Use environment variables or secure secret management"});return t}async checkLogging(e,u,a){let t=[];if(a.length===0)return t;let r=await this.patternAnalyzer.analyzeLogging(a);for(let i of r.sensitiveOperationsWithoutLogging)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Sensitive operation without audit logging",remediation:"Add audit log entry for data modification operations"});for(let i of r.sensitiveDataInLogs)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Sensitive data being logged",remediation:"Remove or mask sensitive data before logging"});return t}async checkDataProtection(e,u,a){let t=[];if(a.length===0)return t;let r=await this.patternAnalyzer.analyzeDataProtection(a);for(let i of r.unmaskedPii)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"PII field without masking or encryption decorator",remediation:"Apply data protection decorators to sensitive fields"});for(let i of r.missingValidation)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Data fields without input validation",remediation:"Add input validation for all data fields, especially PII"});return t}async checkSecurityControls(e,u,a){let t=[];if(a.length===0)return t;let r=await this.patternAnalyzer.analyzeSecurityControls(a);for(let i of r.missingControls)t.push({ruleId:e.id,ruleName:e.title,location:{file:"project-wide",line:0,snippet:`Missing: ${i}`},details:`Security control not detected: ${i}`,remediation:`Implement ${i} to enhance security posture`});for(let i of r.vulnerabilities)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Security vulnerability detected",remediation:"Review and fix the security issue"});return t}estimateEffort(e){let u=["architecture","data-rights","incident-response"],a=["access-control","encryption","change-management"];return u.includes(e.category)?"major":a.includes(e.category)||e.checkType==="manual"?"moderate":"minor"}async scanFileForDataTypes(e,u){let a=[],t=await this.patternAnalyzer.scanForDataTypes([e.value],u);for(let r of u){let i=t.get(r)||[];for(let n of i)a.push({type:r,location:{file:n.file,line:n.line,context:n.snippet||this.getDataTypeContext(r)}})}return a}getDataTypeContext(e){return{pii:"User personal information field",phi:"Health-related data field",financial:"Payment/financial data field",credentials:"Authentication credential field",biometric:"Biometric data field"}[e]}checkDataTypeViolation(e){let u=e.location.context.toLowerCase(),t=[/encrypt/i,/hash/i,/mask/i,/redact/i,/validate/i,/sanitize/i,/bcrypt/i,/argon2/i,/aes/i].some(n=>n.test(u)),i=[/console\.(log|debug|info)/i,/JSON\.stringify/i,/\.toString\(\)/i,/plaintext/i,/unencrypted/i].some(n=>n.test(u));if(!t||i){let n={pii:"gdpr-art32-security",phi:"hipaa-164.312-transmission",financial:"pci-req3",credentials:"soc2-cc6.6",biometric:"gdpr-art9-special"},o={file:e.location.file,line:e.location.line,snippet:e.location.context},l=i?"Potentially exposed in logs or serialization":"No protective measures detected";return{ruleId:n[e.type],ruleName:`${e.type.toUpperCase()} Data Protection`,location:o,details:`${e.type.toUpperCase()} data found: ${l}`,remediation:`Apply appropriate security controls for ${e.type} data`}}return null}getDataTypeRecommendations(e,u){let a=`Found ${u} ${e.toUpperCase()} data locations`;return{pii:[a,"Implement data minimization principles","Ensure consent mechanisms are in place","Add data retention policies"],phi:[a,"Verify HIPAA safeguards are implemented","Ensure business associate agreements are in place","Implement minimum necessary access"],financial:[a,"Verify PCI-DSS compliance for payment data","Implement tokenization where possible","Ensure proper key management"],credentials:[a,"Use secure credential storage (vaults)","Implement credential rotation","Avoid hardcoded credentials"],biometric:[a,"Implement enhanced protection measures","Obtain explicit consent","Consider data localization requirements"]}[e]}async collectEvidence(e,u){let a=[],t=await this.getFilesFromContext(u);if(e.checkType==="static"&&t.length>0){switch(e.category){case"encryption":{let r=await this.patternAnalyzer.analyzeEncryption(t);r.hasEncryption&&a.push(`Encryption detected: ${r.encryptionLibraries.join(", ")||"standard crypto"}`),r.weakCrypto.length>0&&a.push(`Weak crypto found in ${r.weakCrypto.length} location(s)`),a.push(`Unencrypted data handling: ${r.unencryptedDataHandling.length} instance(s)`);break}case"access_control":{let r=await this.patternAnalyzer.analyzeAccessControl(t);a.push(`Auth middleware: ${r.hasAuthMiddleware?"present":"not found"}`),a.push(`Unprotected routes: ${r.unprotectedRoutes.length}`),a.push(`Hardcoded credentials: ${r.hardcodedCredentials.length}`);break}case"logging":{let r=await this.patternAnalyzer.analyzeLogging(t);a.push(`Audit logging: ${r.hasAuditLogging?"implemented":"not found"}`),a.push(`Sensitive data in logs: ${r.sensitiveDataInLogs.length} instance(s)`);break}case"data_protection":{let r=await this.patternAnalyzer.analyzeDataProtection(t);a.push(`PII fields detected: ${r.piiFields.length}`),a.push(`Unmasked PII: ${r.unmaskedPii.length} instance(s)`),a.push(`Missing validation: ${r.missingValidation.length} field(s)`);break}default:a.push(`Static analysis completed for ${e.category}`),a.push(`Code patterns reviewed: ${e.title}`)}a.push(`Files analyzed: ${t.length}`)}else e.checkType==="dynamic"?(a.push(`Dynamic check required for: ${e.title}`),a.push("Evidence collection pending dynamic analysis")):e.checkType==="manual"&&(a.push(`Manual verification required for: ${e.title}`),a.push(`Review scope: ${u.projectRoot.value}`));return a.push(`Rule ${e.id} verified at ${new Date().toISOString()}`),a}async storeReport(e){await this.memory.set(`compliance:report:${e.standardId}:${Date.now()}`,e,{namespace:"security-compliance",persist:!0})}};var TCu={stateSize:10,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0},Ti=class extends Eu{qNetwork;targetNetwork;replayBufferClass;dqnConfig;updateCount=0;actions=[];constructor(e={}){super("dqn","value-based"),this.dqnConfig={...TCu,...e},this.initializeActions(),this.qNetwork=new $({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new ie(this.config.replayBufferSize,!1)}async predict(e){this.initialized||await this.initialize();let u=this.prepareState(e),a=this.targetNetwork.forward(u),t=this.argmax(a),r=this.actions[t];return{action:r,confidence:.7,value:a[t],reasoning:`DQN: ${r.type}`}}async trainCore(e){for(let t of e)this.replayBufferClass.add(t);if(!this.replayBufferClass.isReady(this.dqnConfig.minReplaySize))return this.getStats();let u=this.replayBufferClass.sample(this.config.batchSize),a=0;for(let t of u){let r=this.prepareState(t.state),i=this.prepareState(t.nextState),n=this.actionToIndex(t.action),o=this.qNetwork.forward(r),l;if(this.dqnConfig.doubleDQN&&!t.done){let E=this.qNetwork.forward(i),d=this.argmax(E),D=this.targetNetwork.forward(i);l=t.reward+this.config.discountFactor*D[d]}else{let E=this.targetNetwork.forward(i);l=t.reward+this.config.discountFactor*Math.max(...E)*(t.done?0:1)}let c=new Float32Array(o.length);for(let E=0;E<c.length;E++)c[E]=E===n?l:o[E];a+=Math.abs(this.qNetwork.train(r,c,new xu))}return this.updateCount++,this.updateCount%this.dqnConfig.targetUpdateFreq===0&&(this.targetNetwork=this.qNetwork.clone()),{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((t,r)=>t+r,0)/this.rewardHistory.length,loss:a/u.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(e){let u=e.features.slice(0,this.dqnConfig.stateSize);for(;u.length<this.dqnConfig.stateSize;)u.push(0);let a=Math.max(...u.map(Math.abs));if(a>0)for(let t=0;t<u.length;t++)u[t]/=a;return new Float32Array(u)}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 $({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone()}actionToIndex(e){let u=`${e.type}:${JSON.stringify(e.value)}`;for(let a=0;a<this.actions.length;a++)if(`${this.actions[a].type}:${JSON.stringify(this.actions[a].value)}`===u)return a;return 0}argmax(e){let u=0,a=e[0];for(let t=1;t<e.length;t++)e[t]>a&&(a=e[t],u=t);return u}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),targetNetwork:this.targetNetwork.getParameters(),dqnConfig:this.dqnConfig,updateCount:this.updateCount}}async importCustomData(e){e.qNetwork&&this.qNetwork.setParameters(e.qNetwork),e.targetNetwork&&this.targetNetwork.setParameters(e.targetNetwork),e.dqnConfig&&(this.dqnConfig={...this.dqnConfig,...e.dqnConfig}),typeof e.updateCount=="number"&&(this.updateCount=e.updateCount),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new $({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var MCu={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},iu=B.create("security-compliance"),ot=class extends Y{constructor(u,a,t,r={}){let i={...MCu,...r};super(u,"security-compliance",i,{verifyFindingTypes:["security-vulnerability","compliance-violation","credential-exposure"],...i.consensusMixinConfig});this.memory=a;this.agentCoordinator=t;this.securityGovernanceMixin=xc(this.domainName),this.securityScanner=new Ou(a),this.securityAuditor=new u0(a),this.complianceValidator=new e0(a)}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 Ti({stateSize:8,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0})),this.config.enableFlashAttention){let u="test-similarity";this.flashAttention=await Ku(u,{dim:384,strategy:"flash",numHeads:8})}if(this.config.enableConsensus){let a=Ve(!0).getAll();a.length>0?(this.consensusEngine=ba({strategy:"weighted",models:a,engineConfig:{minModels:Math.min(2,a.length),defaultModelTimeout:6e4,...this.config.consensusEngineConfig}}),iu.info(`Multi-Model Consensus initialized with ${a.length} providers`)):iu.warn("No model providers available for consensus verification")}this.rlInitialized=!0}catch(u){throw iu.error("Failed to initialize RL integrations:",u instanceof Error?u:void 0),u}}async onDispose(){await this.saveWorkflowState()}getActiveWorkflows(){return super.getActiveWorkflows()}async runSecurityAudit(u){let a=A();try{if(this.startWorkflow(a,"audit"),this.detectAuthCodeInScope(u)&&this.securityGovernanceMixin.isGovernanceEnabled()&&!(await this.securityGovernanceMixin.validateSecurityScanRequired(a,!0,void 0)).allowed&&this.securityGovernanceMixin.isStrictMode()&&iu.info("Security audit for auth code registered with governance"),this.minCutMixin.shouldPauseOperations())return iu.warn("Security audit paused: topology is in critical state"),this.failWorkflow(a,"Topology is in critical state"),m(new Error("Security audit paused: topology is in critical state"));if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&iu.warn("Topology degraded, using conservative audit strategy"),!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn security audit agents"));let r=await this.spawnSecurityAuditAgent(a,u);if(!r.success)return this.failWorkflow(a,r.error.message),m(r.error);this.addAgentToWorkflow(a,r.value);let i=u.tests||[];this.config.enableDQN&&this.dqnAlgorithm&&i.length>0&&(i=await this.prioritizeSecurityTests(u,i));let n={...u},o=await this.securityAuditor.runAudit(n);if(o.success){this.completeWorkflow(a);let l=this.extractVulnerabilitiesFromReport(o.value);this.config.enableFlashAttention&&this.flashAttention&&l.length>0&&await this.enhanceVulnerabilityAnalysis(l),this.config.enableDQN&&this.dqnAlgorithm&&await this.trainDQNWithAuditFeedback(u,o.value),this.config.publishEvents&&await this.publishSecurityAuditCompleted(o.value)}else this.failWorkflow(a,o.error.message);return await this.agentCoordinator.stop(r.value),o}catch(t){let r=g(t);return this.failWorkflow(a,r.message),{success:!1,error:r}}}async runSecurityScan(u,a){let t=A();try{if(this.startWorkflow(t,"scan"),this.minCutMixin.shouldPauseOperations())return iu.warn("Security scan paused: topology is in critical state"),this.failWorkflow(t,"Topology is in critical state"),m(new Error("Security scan paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&iu.warn("Topology degraded, proceeding with conservative scan strategy");let r;return a==="sast"?r=await this.securityScanner.scanFiles(u):a==="dast"?r=await this.securityScanner.scanUrl(u[0]?.value??""):r=await this.securityScanner.scanFiles(u),r.success?this.completeWorkflow(t):this.failWorkflow(t,r.error.message),r}catch(r){let i=g(r);return this.failWorkflow(t,i.message),{success:!1,error:i}}}async runComplianceValidation(u,a){let t=A();try{if(this.startWorkflow(t,"compliance"),this.minCutMixin.shouldPauseOperations())return iu.warn("Compliance validation paused: topology is in critical state"),this.failWorkflow(t,"Topology is in critical state"),m(new Error("Compliance validation paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&iu.warn("Topology degraded, proceeding with compliance validation");let i=(await this.complianceValidator.getAvailableStandards()).find(o=>o.id===u);if(!i)return m(new Error(`Unknown compliance standard: ${u}`));let n=await this.complianceValidator.validate(i,a);return n.success?(this.completeWorkflow(t),this.config.publishEvents&&await this.publishComplianceValidationCompleted(n.value)):this.failWorkflow(t,n.error.message),n}catch(r){let i=g(r);return this.failWorkflow(t,i.message),{success:!1,error:i}}}async assessSecurityPosture(){let u=A();try{if(this.startWorkflow(u,"posture"),this.minCutMixin.shouldPauseOperations())return iu.warn("Security posture assessment paused: topology is in critical state"),this.failWorkflow(u,"Topology is in critical state"),m(new Error("Security posture assessment paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&iu.warn("Topology degraded, proceeding with security posture assessment");let a=await this.securityAuditor.getSecurityPosture();if(a.success){this.completeWorkflow(u);let t={overallScore:a.value.overallScore,trend:a.value.trend,criticalVulnerabilities:a.value.criticalIssues,complianceStatus:new Map,lastAuditDate:a.value.lastAuditDate};return p(t)}else return this.failWorkflow(u,a.error.message),a}catch(a){let t=g(a);return this.failWorkflow(u,t.message),{success:!1,error:t}}}async runComplianceCheck(u){let a={projectRoot:yu.create("."),includePatterns:["**/*.ts","**/*.js"],excludePatterns:["node_modules/**"]};return this.runComplianceValidation(u,a)}async getSecurityPosture(){return this.assessSecurityPosture()}async prioritizeSecurityTests(u,a){if(!this.dqnAlgorithm||!this.rlInitialized)return a;try{let t=await Promise.all(a.map(async r=>{let i={id:`test-${r}`,features:this.extractSecurityTestFeatures(u,r)},n=await this.dqnAlgorithm.predict(i);return{test:r,score:n.value||0}}));return t.sort((r,i)=>i.score-r.score),t.map(r=>r.test)}catch(t){return iu.error("Failed to prioritize security tests:",t instanceof Error?t:void 0),a}}async trainDQNWithAuditFeedback(u,a){if(!(!this.dqnAlgorithm||!this.rlInitialized))try{let t=this.extractVulnerabilitiesFromReport(a),r={id:`audit-${a.auditId}-${Date.now()}`,features:this.extractAuditFeatures(u)},i={type:"run-audit",value:t.length},n=this.calculateAuditReward(a),o={state:r,action:i,reward:n,nextState:r,done:!0,timestamp:new Date};await this.dqnAlgorithm.train(o),iu.info(`Trained security audit with reward: ${n.toFixed(3)}`)}catch(t){iu.error("Failed to train DQN:",t instanceof Error?t:void 0)}}calculateAuditReward(u){let a=this.extractVulnerabilitiesFromReport(u);if(a.length===0)return .5;let t=.5,r=a.filter(n=>n.severity==="critical").length;t+=Math.min(.3,r*.1);let i=a.filter(n=>n.severity==="high").length;return t+=Math.min(.2,i*.05),t+=(u.overallRiskScore?.value??0)*.1,Math.max(0,Math.min(1,t))}extractSecurityTestFeatures(u,a){let t=u.targetUrl??"";return[t.includes("/api")?1:0,t.startsWith("http")?1:0,u.includeSAST?1:0,a.includes("auth")?1:0,a.includes("sql")?1:0,a.includes("xss")?1:0,a.includes("injection")?1:0,a.length/100]}extractAuditFeatures(u){let a=u.depth??"standard",t=a==="deep"?1:a==="standard"?.5:.25;return[u.includeSAST?1:0,u.includeDAST?1:0,t,(u.scanTypes?.length??0)/4,u.includeDependencies?1:0,u.includeSecrets?1:0,(u.complianceFrameworks?.length??0)/5,u.targetUrl?1:0]}async enhanceVulnerabilityAnalysis(u){if(!(!this.flashAttention||!this.rlInitialized||u.length===0))try{let a=u.map(c=>this.createVulnerabilityEmbedding(c)),t=a.length,r=a[0].length,i=new Float32Array(t*r),n=new Float32Array(t*r),o=new Float32Array(t*r);for(let c=0;c<t;c++)i.set(a[c],c*r),n.set(a[c],c*r),o.set(a[c],c*r);let l=await this.flashAttention.computeFlashAttention(i,n,o,t,r);for(let c=0;c<u.length;c++){let E=Array.from(l.slice(c*r,(c+1)*r));a[c].reduce((D,h,C)=>D+h*E[C],0)>.7&&iu.info(`High self-attention for vulnerability ${u[c].id}`)}}catch(a){iu.error("Failed to enhance vulnerability analysis:",a instanceof Error?a:void 0)}}createVulnerabilityEmbedding(u){let a=[],t=this.hashCode(u.category);a.push(t%1e3/1e3);let r={critical:1,high:.75,medium:.5,low:.25,informational:.1};a.push(r[u.severity]||.5);let i=this.hashCode(u.title);a.push(i%1e3/1e3),a.push(Math.min(1,u.description.length/500));let n=u.cveId?this.hashCode(u.cveId):0;a.push(n%1e3/1e3);let o=this.hashCode(u.description.slice(0,200));for(let l=a.length;l<384;l++)a.push(o*(l+1)%1e4/1e4);return a.slice(0,384)}hashCode(u){let a=0;for(let t=0;t<u.length;t++)a=(a<<5)-a+u.charCodeAt(t),a=a|0;return Math.abs(a)}async spawnSecurityAuditAgent(u,a){let t={name:`security-auditor-${u.slice(0,8)}`,domain:"security-compliance",type:"auditor",capabilities:["security-audit","vulnerability-scanning","compliance-check"],config:{workflowId:u,targetUrl:a.targetUrl,depth:a.depth}};return this.agentCoordinator.spawn(t)}extractVulnerabilitiesFromReport(u){let a=[];return u.sastResults?.vulnerabilities&&a.push(...u.sastResults.vulnerabilities),u.dastResults?.vulnerabilities&&a.push(...u.dastResults.vulnerabilities),u.dependencyResults?.vulnerabilities&&a.push(...u.dependencyResults.vulnerabilities),a}async publishSecurityAuditCompleted(u){let a=this.extractVulnerabilitiesFromReport(u),t=await this.verifyHighSeverityFindings(a);for(let r of t){let i={vulnId:r.id,cve:r.cveId,severity:r.severity,file:r.location.file,line:r.location.line,description:r.description,remediation:r.remediation.description},n=L(Yi.SecurityAuditCompleted,"security-compliance",i);await this.eventBus.publish(n)}}async verifyHighSeverityFindings(u){if(!this.config.enableConsensus)return u;if(!this.isConsensusAvailable())return this.consensusEngine?this.verifyHighSeverityFindingsLegacy(u):u;let a=[],t=u.filter(n=>n.severity==="critical"||n.severity==="high"),r=u.filter(n=>n.severity!=="critical"&&n.severity!=="high");a.push(...r);for(let n of t)try{let o=O({id:n.id,type:"security-vulnerability",confidence:.8,description:`${n.title}: ${n.description}`,payload:{vulnerability:n,location:n.location},detectedBy:"security-scanner",severity:n.severity,context:{domain:this.domainName,cveId:n.cveId,category:n.category}});if(!this.consensusMixin.requiresConsensus(o)){a.push(n);continue}let l=await this.consensusMixin.verifyFinding(o);l.success&&l.value.verdict==="verified"?(iu.info(`Consensus VERIFIED: ${n.title} (confidence: ${(l.value.confidence*100).toFixed(1)}%)`),a.push(n)):l.success&&l.value.verdict==="disputed"?(iu.info(`Consensus DISPUTED: ${n.title} - including with lower confidence`),a.push(n)):iu.info(`Consensus REJECTED: ${n.title} - likely false positive`)}catch{iu.warn(`Consensus error verifying ${n.title}, including by default:`),a.push(n)}let i=t.length-a.filter(n=>n.severity==="critical"||n.severity==="high").length;return i>0&&iu.info(`Consensus filtered out ${i} likely false positive(s)`),a}async verifyHighSeverityFindingsLegacy(u){if(!this.consensusEngine)return u;let a=[],t=u.filter(i=>i.severity==="critical"||i.severity==="high"),r=u.filter(i=>i.severity!=="critical"&&i.severity!=="high");a.push(...r);for(let i of t)try{let n={id:i.id,type:i.category,description:i.description,category:i.category,severity:i.severity,location:{file:i.location.file,line:i.location.line,column:i.location.column},evidence:[{type:"code-snippet",content:i.location.snippet||i.description}],cveId:i.cveId,remediation:i.remediation.description,detectedAt:new Date,detectedBy:"security-scanner"},o=await this.consensusEngine.verify(n);(o.success&&o.value.verdict==="verified"||o.success&&o.value.verdict==="disputed")&&a.push(i)}catch{a.push(i)}return a}async publishComplianceValidationCompleted(u){let a={standard:u.standardId,passed:u.complianceScore>=.8,violations:u.violations.length,findings:u.violations.map(r=>r.details).slice(0,10)},t=L(Yi.ComplianceValidated,"security-compliance",a);await this.eventBus.publish(t)}detectAuthCodeInScope(u){let a=[/auth/i,/login/i,/password/i,/token/i,/session/i,/oauth/i,/jwt/i,/credential/i,/identity/i];if(u.targetUrl){for(let t of a)if(t.test(u.targetUrl))return!0}if(u.scanTypes){let t=["authentication","authorization","session-management"];for(let r of u.scanTypes)if(t.includes(r.toLowerCase()))return!0}if(u.complianceFrameworks){let t=["soc2","pci-dss","hipaa","iso27001"];for(let r of u.complianceFrameworks)if(t.includes(r.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(u){}async handleImpactAnalysis(u){}async loadWorkflowState(){let u=await this.memory.get("security-compliance:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("security-compliance:coordinator:workflows",u,{namespace:"security-compliance",persist:!0})}getHealthyRoutingDomains(){return this.minCutMixin.getHealthyRoutingDomains()}};S();var Mi=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.target??u.targetUrl;return a?this.coordinator.runSecurityAudit({includeSAST:u.includeSAST??!0,includeDAST:u.includeDAST??!1,includeDependencies:u.includeDependencies??!0,includeSecrets:u.includeSecrets??!0,targetUrl:a}):m(new Error("Invalid security-audit payload: missing target"))}],["compliance-check",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.standardId;return a?this.coordinator.runComplianceCheck(a):m(new Error("Invalid compliance-check payload: missing standardId"))}],["sast-scan",async u=>{if(!this.securityScanner)return m(new Error("Security scanner not initialized"));let a=u.files;return!a||a.length===0?m(new Error("Invalid sast-scan payload: missing files")):this.securityScanner.scanFiles(a)}],["dast-scan",async u=>{if(!this.securityScanner)return m(new Error("Security scanner not initialized"));let a=u.targetUrl;return a?this.securityScanner.scanUrl(a):m(new Error("Invalid dast-scan payload: missing targetUrl"))}],["triage-vulnerabilities",async u=>{if(!this.securityAuditor)return m(new Error("Security auditor not initialized"));let a=u.vulnerabilities;return!a||a.length===0?m(new Error("Invalid triage-vulnerabilities payload: missing vulnerabilities")):this.securityAuditor.triageVulnerabilities(a)}]])}async onInitialize(){this.securityScanner=new Ou(this.memory,this.pluginConfig.securityScanner),this.securityAuditor=new u0(this.memory,this.pluginConfig.securityAuditor),this.complianceValidator=new e0(this.memory,this.pluginConfig.complianceValidator),this.coordinator=new ot(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"code-intelligence.KnowledgeGraphUpdated":await this.handleKnowledgeGraphUpdate(u);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(u);break;default:break}}async runSecurityAudit(u){this.ensureInitialized();try{let a=await this.coordinator.runSecurityAudit(u);return a.success?this.trackSuccessfulOperation("audit"):this.trackFailedOperation("audit",a.error),a}catch(a){return this.handleError(a)}}async getSecurityPosture(){this.ensureInitialized();try{return await this.coordinator.getSecurityPosture()}catch(u){return this.handleError(u)}}async runSASTScan(u){this.ensureInitialized();try{let a=await this.securityScanner.scanFiles(u);return a.success?this.trackSuccessfulOperation("sast-scan"):this.trackFailedOperation("sast-scan",a.error),a}catch(a){return this.handleError(a)}}async runDASTScan(u){this.ensureInitialized();try{let a=await this.securityScanner.scanUrl(u);return a.success?this.trackSuccessfulOperation("dast-scan"):this.trackFailedOperation("dast-scan",a.error),a}catch(a){return this.handleError(a)}}async triageVulnerabilities(u){this.ensureInitialized();try{let a=await this.securityAuditor.triageVulnerabilities(u);return a.success?{success:!0,value:{immediate:a.value.immediate,shortTerm:a.value.shortTerm}}:{success:!1,error:a.error}}catch(a){return this.handleError(a)}}async runComplianceCheck(u){this.ensureInitialized();try{let a=await this.coordinator.runComplianceCheck(u);return a.success?this.trackSuccessfulOperation("compliance-check"):this.trackFailedOperation("compliance-check",a.error),a}catch(a){return this.handleError(a)}}async getAvailableStandards(){return this.ensureInitialized(),this.complianceValidator.getAvailableStandards()}async analyzeComplianceGaps(u,a){this.ensureInitialized();try{return await this.complianceValidator.analyzeGaps(u,a)}catch(t){return this.handleError(t)}}async handleKnowledgeGraphUpdate(u){let a=u.payload;await this.memory.set(`security:code-update:${Date.now()}`,{filesIndexed:a.filesIndexed,timestamp:new Date},{namespace:"security-compliance",ttl:3600})}async handleQualityGateEvaluated(u){let a=u.payload,t=a.checks.filter(r=>r.name.toLowerCase().includes("security"));t.length>0&&await this.memory.set(`security:gate-results:${a.gateId}`,{securityChecks:t,passed:a.passed},{namespace:"security-compliance",persist:!0})}async handleTestRunCompleted(u){}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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date}),this.memory.set(`security:operation:${u}:${Date.now()}`,{operation:u,success:!0,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}trackFailedOperation(u,a){let t=this.getHealth();this.updateHealth({agents:{...t.agents,failed:t.agents.failed+1},errors:[...t.errors.slice(-9),a.message]}),this.memory.set(`security:operation:${u}:${Date.now()}`,{operation:u,success:!1,error:a.message,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}};function jl(s,e,u,a){return new Mi(s,e,u,a)}N();S();N();S();J();var RCu={strictMode:!0,validateExamples:!0,maxSchemaDepth:tr.MAX_SCHEMA_DEPTH,cacheValidations:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:rr.MAX_TOKENS},PCu=B.create("contract-testing/contract-validator"),K0=class{config;memory;llmRouter;validationCache=new Map;MAX_CACHED_VALIDATIONS=tr.MAX_CACHED_VALIDATIONS;CACHE_TTL_MS=tr.CACHE_TTL_MS;constructor(e,u={}){this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...RCu,...u}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(e){let u={1:"claude-3-haiku-20240307",2:"claude-sonnet-4-20250514",3:"claude-sonnet-4-20250514",4:"claude-opus-4-20250514"};return u[e]||u[2]}async analyzeContractWithLLM(e){if(!this.isLLMAnalysisAvailable())return null;try{let u=e.consumers.map(t=>t.name).join(", ");return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this API contract for potential issues:
2931
+ `);for(let i of r){let n=i.trim();if(!n||n.startsWith("#"))continue;let o=n.match(/^([a-zA-Z0-9_-]+)(?:[=<>~!]+(.+))?$/);o&&a.push({name:o[1],version:o[2]||"latest",ecosystem:"pip"})}}}catch(t){le.error(`Failed to parse dependencies from ${e}:`,t instanceof Error?t:void 0)}return a}cleanVersionSpec(e){return e.replace(/^[\^~>=<]+/,"").trim()}async checkDependencyVulnerabilities(e,u){let a=[];try{let t=this.mapToOSVEcosystem(u),r={package:{name:e.name,ecosystem:t},version:e.version},i=await zl("https://api.osv.dev/v1/query",r);if(i.ok&&i.data.vulns&&i.data.vulns.length>0)for(let n of i.data.vulns){let o=this.mapOSVVulnerability(n,e);a.push(o)}}catch(t){le.error(`Failed to check vulnerabilities for ${e.name}@${e.version}:`,t instanceof Error?t:void 0)}return a}mapToOSVEcosystem(e){return{npm:"npm",pip:"PyPI",maven:"Maven",nuget:"NuGet",cargo:"crates.io"}[e]}mapOSVVulnerability(e,u){let a=e.aliases?.find(l=>l.startsWith("CVE-")),t=this.mapOSVSeverity(e.severity),r=this.extractFixedVersion(e),i=e.references?.map(l=>l.url)||[],n={file:"package.json",dependency:u},o={description:r?`Upgrade ${u.name} to version ${r} or higher`:`Review and address vulnerability in ${u.name}`,fixExample:r?`"${u.name}": "^${r}"`:void 0,estimatedEffort:r?"trivial":"moderate",automatable:!!r};return{id:A(),cveId:a,title:e.summary||`Vulnerability in ${u.name}`,description:e.details||e.summary||"No description available",severity:t,category:this.categorizeVulnerability(e),location:n,remediation:o,references:i}}mapOSVSeverity(e){if(!e||e.length===0)return"medium";let u=e.find(a=>a.type==="CVSS_V3"||a.type==="CVSS_V2");if(u){let a=parseFloat(u.score);if(a>=9)return"critical";if(a>=7)return"high";if(a>=4)return"medium";if(a>0)return"low"}return"medium"}extractFixedVersion(e){if(e.affected){for(let u of e.affected)if(u.ranges){for(let a of u.ranges)if(a.events){let t=a.events.find(r=>r.fixed);if(t?.fixed)return t.fixed}}}}categorizeVulnerability(e){let u=(e.summary||"").toLowerCase(),a=(e.details||"").toLowerCase(),t=`${u} ${a}`;return t.includes("injection")||t.includes("sql")?"injection":t.includes("xss")||t.includes("cross-site scripting")?"xss":t.includes("authentication")||t.includes("auth bypass")?"broken-auth":t.includes("sensitive data")||t.includes("exposure")?"sensitive-data":t.includes("xxe")||t.includes("xml external")?"xxe":t.includes("access control")||t.includes("authorization")?"access-control":t.includes("deseriali")?"insecure-deserialization":(t.includes("prototype pollution")||t.includes("dependency"),"vulnerable-components")}async checkOutdated(e){let u=await this.getLatestVersion(e.name,e.ecosystem);return u!==e.version?{name:e.name,currentVersion:e.version,latestVersion:u,updateType:this.determineUpdateType(e.version,u)}:null}async queryVulnerabilityDatabase(e,u,a){let t={name:e,version:u,ecosystem:a};return this.checkDependencyVulnerabilities(t,a)}async getLatestVersion(e,u){try{if(u==="npm"){let a=await rt(`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`);if(a.ok&&a.data.version)return a.data.version}else if(u==="pip"){let a=await rt(`https://pypi.org/pypi/${encodeURIComponent(e)}/json`);if(a.ok&&a.data.info?.version)return a.data.info.version}}catch(a){le.error(`Failed to get latest version for ${e}:`,a instanceof Error?a:void 0)}return"unknown"}async checkDeprecation(e,u){try{if(u==="npm"){let a=await rt(`https://registry.npmjs.org/${encodeURIComponent(e)}/latest`);if(a.ok&&a.data.deprecated)return!0}}catch(a){le.error(`Failed to check deprecation for ${e}:`,a instanceof Error?a:void 0)}return!1}determineUpdateType(e,u){let a=e.split(".").map(Number),t=u.split(".").map(Number);return t[0]>a[0]?"major":t[1]>a[1]?"minor":"patch"}hasBreakingChanges(e,u){let a=parseInt(e.split(".")[0]);return parseInt(u.split(".")[0])>a}createDependencySummary(e,u){let a=0,t=0,r=0,i=0,n=0;for(let o of e)switch(o.severity){case"critical":a++;break;case"high":t++;break;case"medium":r++;break;case"low":i++;break;case"informational":n++;break}return{critical:a,high:t,medium:r,low:i,informational:n,totalFiles:u,scanDurationMs:0}}shouldExclude(e){return this.config.excludePatterns.some(u=>u.startsWith("*")?e.endsWith(u.slice(1)):e.includes(u))}async performDependencyScan(){let e=Date.now(),u=[],a=[];try{let t=nt.join(process.cwd(),"package.json"),r=await this.parseDependencies(t,"npm");for(let o of r){let l=await this.checkDependencyVulnerabilities(o,o.ecosystem);u.push(...l);let c=await this.checkOutdated(o);c&&a.push(c)}let i=Date.now()-e,n=this.createDependencySummary(u,r.length);return{vulnerabilities:u,outdatedPackages:a,summary:{...n,scanDurationMs:i}}}catch(t){return le.error("Dependency scan failed:",t instanceof Error?t:void 0),{vulnerabilities:[],outdatedPackages:[],summary:{critical:0,high:0,medium:0,low:0,informational:0,totalFiles:0,scanDurationMs:Date.now()-e}}}}async performSecretScan(){let e=[],u=0;try{let a=await this.findSourceFiles(process.cwd());for(let t of a){if(this.shouldExclude(t))continue;u++;let i=await Nl({value:t});e.push(...i)}}catch(a){le.error("Secret scan failed:",a instanceof Error?a:void 0)}return{secretsFound:e,filesScanned:u}}async findSourceFiles(e,u=[]){let a=[".ts",".js",".tsx",".jsx",".json",".env",".yaml",".yml",".config"];try{let t=await it.readdir(e,{withFileTypes:!0});for(let r of t){let i=nt.join(e,r.name);if(!this.shouldExclude(i)){if(r.isDirectory())await this.findSourceFiles(i,u);else if(r.isFile()){let n=nt.extname(r.name).toLowerCase();(a.includes(n)||r.name.startsWith(".env"))&&u.push(i)}}}}catch{le.debug("Directory read error:")}return u}async getRecentAudits(){let e=await this.memory.search("security:audit:*",10),u=[];for(let a of e){let t=await this.memory.get(a);t&&u.push(t)}return u.sort((a,t)=>new Date(t.timestamp).getTime()-new Date(a.timestamp).getTime())}async countResolvedLastWeek(){try{let e=await this.getRecentAudits();if(e.length<2)return 0;let u=new Date(Date.now()-10080*60*1e3),a=e.filter(o=>new Date(o.timestamp)>=u);if(a.length<2)return 0;let t=a[a.length-1],r=a[0],i=I0(t),n=I0(r);return Math.max(0,i-n)}catch(e){return le.error("Failed to count resolved vulnerabilities:",e instanceof Error?e:void 0),0}}async calculateAverageResolutionTime(){try{let e=await this.getRecentAudits();if(e.length<2)return 72;let u=new Map,a=[],t=[...e].reverse();for(let i of t){let n=new Set;i.sastResults&&i.sastResults.vulnerabilities.forEach(o=>n.add(o.id)),i.dastResults&&i.dastResults.vulnerabilities.forEach(o=>n.add(o.id)),i.dependencyResults&&i.dependencyResults.vulnerabilities.forEach(o=>n.add(o.id));for(let o of n)u.has(o)||u.set(o,i.timestamp);for(let[o,l]of u)if(!n.has(o)){let c=(i.timestamp.getTime()-l.getTime())/36e5;a.push(c),u.delete(o)}}if(a.length===0)return 72;let r=a.reduce((i,n)=>i+n,0);return Math.round(r/a.length)}catch(e){return le.error("Failed to calculate average resolution time:",e instanceof Error?e:void 0),72}}};S();var FCu={customStandards:[],strictMode:!1,includeRecommended:!0,evidenceRetentionDays:365},bCu={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"}]},BCu={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"}]},kCu={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"}]},SCu={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"}]},wCu=[bCu,BCu,kCu,SCu],e0=class{constructor(e,u={}){this.memory=e;this.config={...FCu,...u},this.patternAnalyzer=Pl(),this.standards=new Map;for(let a of wCu)this.standards.set(a.id,a);for(let a of this.config.customStandards)this.standards.set(a.id,a)}config;standards;patternAnalyzer;async validate(e,u){try{let a=[],t=[],r=[],i=this.config.includeRecommended?e.rules:e.rules.filter(c=>c.severity==="required");for(let c of i){if(c.checkType==="manual"){r.push(c.id);continue}let E=await this.checkRule(c,u);E.passed?t.push(c.id):a.push(...E.violations)}let n=i.length-r.length,o=n>0?Math.round(t.length/n*100):100,l={standardId:e.id,standardName:e.name,violations:a,passedRules:t,skippedRules:r,complianceScore:o,generatedAt:new Date};return await this.storeReport(l),p(l)}catch(a){return m(g(a))}}async getAvailableStandards(){return Array.from(this.standards.values())}async analyzeGaps(e,u){try{let a=[],t=[],r=new Set(e.violations.map(c=>c.ruleId)),i=new Set(e.passedRules);for(let c of u.rules)r.has(c.id)?a.push({ruleId:c.id,currentStatus:"failed",effort:this.estimateEffort(c),impact:c.severity==="required"?"high":"medium"}):i.has(c.id)||a.push({ruleId:c.id,currentStatus:"not-implemented",effort:this.estimateEffort(c),impact:c.severity==="required"?"high":"low"});let n=[...a].sort((c,E)=>{let d={high:0,medium:1,low:2},D={trivial:0,minor:1,moderate:2,major:3},h=d[c.impact]*10+D[c.effort],C=d[E.impact]*10+D[E.effort];return h-C});for(let c=0;c<n.length;c++){let E=n[c],d=u.rules.find(D=>D.id===E.ruleId);t.push({id:A(),description:`Implement ${d?.title||E.ruleId}`,affectedRules:[E.ruleId],effort:E.effort,priority:c+1})}let o=100,l=e.complianceScore;return p({currentScore:l,targetScore:o,gaps:a,prioritizedActions:t})}catch(a){return m(g(a))}}async validateMultiple(e,u){try{let a=[],t=[];for(let n of e){let o=await this.validate(n,u);o.success&&a.push(o.value)}let r=new Map;for(let n of a)for(let o of n.violations){let l=`${o.location.file}:${o.location.line}`;r.set(l,(r.get(l)||0)+1)}for(let n of a)for(let o of n.violations){let l=`${o.location.file}:${o.location.line}`;(r.get(l)||0)>1&&(t.some(c=>c.location.file===o.location.file&&c.location.line===o.location.line)||t.push(o))}let i=a.length>0?Math.round(a.reduce((n,o)=>n+o.complianceScore,0)/a.length):0;return p({reports:a,overallScore:i,crossCuttingViolations:t})}catch(a){return m(g(a))}}async checkDataHandling(e,u){try{let a=new Map,t=[],r=[];for(let i of u)a.set(i,[]);for(let i of e){let n=await this.scanFileForDataTypes(i,u);for(let o of n){let l=a.get(o.type)||[];l.push(o.location),a.set(o.type,l);let c=this.checkDataTypeViolation(o);c&&t.push(c)}}for(let[i,n]of a)n.length>0&&r.push(...this.getDataTypeRecommendations(i,n.length));return p({dataTypesFound:a,violations:t,recommendations:[...new Set(r)]})}catch(a){return m(g(a))}}async generateEvidence(e,u){try{let a=this.standards.get(e);if(!a)return m(new Error(`Unknown standard: ${e}`));let t=await this.validate(a,u);if(!t.success)return m(t.error);let r=t.value,i=[];for(let o of a.rules){let l=r.passedRules.includes(o.id)?"implemented":r.skippedRules.includes(o.id)?"partial":"not-implemented";i.push({controlId:o.id,status:l,evidence:await this.collectEvidence(o,u),lastVerified:new Date})}let n={standardId:e,controls:i,generatedAt:new Date,validUntil:new Date(Date.now()+this.config.evidenceRetentionDays*24*60*60*1e3)};return await this.memory.set(`compliance:evidence:${e}:${Date.now()}`,n,{namespace:"security-compliance",persist:!0}),p(n)}catch(a){return m(g(a))}}async checkRule(e,u){let a=[],t=await this.getFilesFromContext(u);switch(e.category){case"encryption":a.push(...await this.checkEncryption(e,u,t));break;case"access-control":a.push(...await this.checkAccessControl(e,u,t));break;case"audit":case"logging":a.push(...await this.checkLogging(e,u,t));break;case"data-protection":case"data-quality":a.push(...await this.checkDataProtection(e,u,t));break;case"security":a.push(...await this.checkSecurityControls(e,u,t));break;default:break}return{passed:a.length===0,violations:a}}async getFilesFromContext(e){let u=[],a=e.projectRoot.value;if(e.includePatterns.length===0)return[];for(let t of e.includePatterns)e.excludePatterns.some(i=>t.includes(i)||i.includes(t))||u.push(`${a}/${t}`);return u}async checkEncryption(e,u,a){let t=[];if(a.length===0)return t;let r=await this.patternAnalyzer.analyzeEncryption(a);for(let i of r.weakCrypto)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Weak or deprecated cryptographic algorithm detected",remediation:"Use strong encryption algorithms (AES-256, SHA-256 or higher)"});for(let i of r.unencryptedDataHandling)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Sensitive data handled without encryption verification",remediation:"Ensure data is encrypted before processing sensitive information"});return t}async checkAccessControl(e,u,a){let t=[];if(a.length===0)return t;let r=await this.patternAnalyzer.analyzeAccessControl(a);for(let i of r.unprotectedRoutes)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Sensitive endpoint potentially missing authorization middleware",remediation:"Add authorization check before sensitive operations"});for(let i of r.hardcodedCredentials)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Hardcoded credentials detected",remediation:"Use environment variables or secure secret management"});return t}async checkLogging(e,u,a){let t=[];if(a.length===0)return t;let r=await this.patternAnalyzer.analyzeLogging(a);for(let i of r.sensitiveOperationsWithoutLogging)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Sensitive operation without audit logging",remediation:"Add audit log entry for data modification operations"});for(let i of r.sensitiveDataInLogs)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Sensitive data being logged",remediation:"Remove or mask sensitive data before logging"});return t}async checkDataProtection(e,u,a){let t=[];if(a.length===0)return t;let r=await this.patternAnalyzer.analyzeDataProtection(a);for(let i of r.unmaskedPii)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"PII field without masking or encryption decorator",remediation:"Apply data protection decorators to sensitive fields"});for(let i of r.missingValidation)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Data fields without input validation",remediation:"Add input validation for all data fields, especially PII"});return t}async checkSecurityControls(e,u,a){let t=[];if(a.length===0)return t;let r=await this.patternAnalyzer.analyzeSecurityControls(a);for(let i of r.missingControls)t.push({ruleId:e.id,ruleName:e.title,location:{file:"project-wide",line:0,snippet:`Missing: ${i}`},details:`Security control not detected: ${i}`,remediation:`Implement ${i} to enhance security posture`});for(let i of r.vulnerabilities)t.push({ruleId:e.id,ruleName:e.title,location:{file:i.file,line:i.line,snippet:i.snippet},details:"Security vulnerability detected",remediation:"Review and fix the security issue"});return t}estimateEffort(e){let u=["architecture","data-rights","incident-response"],a=["access-control","encryption","change-management"];return u.includes(e.category)?"major":a.includes(e.category)||e.checkType==="manual"?"moderate":"minor"}async scanFileForDataTypes(e,u){let a=[],t=await this.patternAnalyzer.scanForDataTypes([e.value],u);for(let r of u){let i=t.get(r)||[];for(let n of i)a.push({type:r,location:{file:n.file,line:n.line,context:n.snippet||this.getDataTypeContext(r)}})}return a}getDataTypeContext(e){return{pii:"User personal information field",phi:"Health-related data field",financial:"Payment/financial data field",credentials:"Authentication credential field",biometric:"Biometric data field"}[e]}checkDataTypeViolation(e){let u=e.location.context.toLowerCase(),t=[/encrypt/i,/hash/i,/mask/i,/redact/i,/validate/i,/sanitize/i,/bcrypt/i,/argon2/i,/aes/i].some(n=>n.test(u)),i=[/console\.(log|debug|info)/i,/JSON\.stringify/i,/\.toString\(\)/i,/plaintext/i,/unencrypted/i].some(n=>n.test(u));if(!t||i){let n={pii:"gdpr-art32-security",phi:"hipaa-164.312-transmission",financial:"pci-req3",credentials:"soc2-cc6.6",biometric:"gdpr-art9-special"},o={file:e.location.file,line:e.location.line,snippet:e.location.context},l=i?"Potentially exposed in logs or serialization":"No protective measures detected";return{ruleId:n[e.type],ruleName:`${e.type.toUpperCase()} Data Protection`,location:o,details:`${e.type.toUpperCase()} data found: ${l}`,remediation:`Apply appropriate security controls for ${e.type} data`}}return null}getDataTypeRecommendations(e,u){let a=`Found ${u} ${e.toUpperCase()} data locations`;return{pii:[a,"Implement data minimization principles","Ensure consent mechanisms are in place","Add data retention policies"],phi:[a,"Verify HIPAA safeguards are implemented","Ensure business associate agreements are in place","Implement minimum necessary access"],financial:[a,"Verify PCI-DSS compliance for payment data","Implement tokenization where possible","Ensure proper key management"],credentials:[a,"Use secure credential storage (vaults)","Implement credential rotation","Avoid hardcoded credentials"],biometric:[a,"Implement enhanced protection measures","Obtain explicit consent","Consider data localization requirements"]}[e]}async collectEvidence(e,u){let a=[],t=await this.getFilesFromContext(u);if(e.checkType==="static"&&t.length>0){switch(e.category){case"encryption":{let r=await this.patternAnalyzer.analyzeEncryption(t);r.hasEncryption&&a.push(`Encryption detected: ${r.encryptionLibraries.join(", ")||"standard crypto"}`),r.weakCrypto.length>0&&a.push(`Weak crypto found in ${r.weakCrypto.length} location(s)`),a.push(`Unencrypted data handling: ${r.unencryptedDataHandling.length} instance(s)`);break}case"access_control":{let r=await this.patternAnalyzer.analyzeAccessControl(t);a.push(`Auth middleware: ${r.hasAuthMiddleware?"present":"not found"}`),a.push(`Unprotected routes: ${r.unprotectedRoutes.length}`),a.push(`Hardcoded credentials: ${r.hardcodedCredentials.length}`);break}case"logging":{let r=await this.patternAnalyzer.analyzeLogging(t);a.push(`Audit logging: ${r.hasAuditLogging?"implemented":"not found"}`),a.push(`Sensitive data in logs: ${r.sensitiveDataInLogs.length} instance(s)`);break}case"data_protection":{let r=await this.patternAnalyzer.analyzeDataProtection(t);a.push(`PII fields detected: ${r.piiFields.length}`),a.push(`Unmasked PII: ${r.unmaskedPii.length} instance(s)`),a.push(`Missing validation: ${r.missingValidation.length} field(s)`);break}default:a.push(`Static analysis completed for ${e.category}`),a.push(`Code patterns reviewed: ${e.title}`)}a.push(`Files analyzed: ${t.length}`)}else e.checkType==="dynamic"?(a.push(`Dynamic check required for: ${e.title}`),a.push("Evidence collection pending dynamic analysis")):e.checkType==="manual"&&(a.push(`Manual verification required for: ${e.title}`),a.push(`Review scope: ${u.projectRoot.value}`));return a.push(`Rule ${e.id} verified at ${new Date().toISOString()}`),a}async storeReport(e){await this.memory.set(`compliance:report:${e.standardId}:${Date.now()}`,e,{namespace:"security-compliance",persist:!0})}};var TCu={stateSize:10,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0},Ti=class extends Eu{qNetwork;targetNetwork;replayBufferClass;dqnConfig;updateCount=0;actions=[];constructor(e={}){super("dqn","value-based"),this.dqnConfig={...TCu,...e},this.initializeActions(),this.qNetwork=new $({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new ie(this.config.replayBufferSize,!1)}async predict(e){this.initialized||await this.initialize();let u=this.prepareState(e),a=this.targetNetwork.forward(u),t=this.argmax(a),r=this.actions[t];return{action:r,confidence:.7,value:a[t],reasoning:`DQN: ${r.type}`}}async trainCore(e){for(let t of e)this.replayBufferClass.add(t);if(!this.replayBufferClass.isReady(this.dqnConfig.minReplaySize))return this.getStats();let u=this.replayBufferClass.sample(this.config.batchSize),a=0;for(let t of u){let r=this.prepareState(t.state),i=this.prepareState(t.nextState),n=this.actionToIndex(t.action),o=this.qNetwork.forward(r),l;if(this.dqnConfig.doubleDQN&&!t.done){let E=this.qNetwork.forward(i),d=this.argmax(E),D=this.targetNetwork.forward(i);l=t.reward+this.config.discountFactor*D[d]}else{let E=this.targetNetwork.forward(i);l=t.reward+this.config.discountFactor*Math.max(...E)*(t.done?0:1)}let c=new Float32Array(o.length);for(let E=0;E<c.length;E++)c[E]=E===n?l:o[E];a+=Math.abs(this.qNetwork.train(r,c,new xu))}return this.updateCount++,this.updateCount%this.dqnConfig.targetUpdateFreq===0&&(this.targetNetwork=this.qNetwork.clone()),{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((t,r)=>t+r,0)/this.rewardHistory.length,loss:a/u.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(e){let u=e.features.slice(0,this.dqnConfig.stateSize);for(;u.length<this.dqnConfig.stateSize;)u.push(0);let a=Math.max(...u.map(Math.abs));if(a>0)for(let t=0;t<u.length;t++)u[t]/=a;return new Float32Array(u)}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 $({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone()}actionToIndex(e){let u=`${e.type}:${JSON.stringify(e.value)}`;for(let a=0;a<this.actions.length;a++)if(`${this.actions[a].type}:${JSON.stringify(this.actions[a].value)}`===u)return a;return 0}argmax(e){let u=0,a=e[0];for(let t=1;t<e.length;t++)e[t]>a&&(a=e[t],u=t);return u}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),targetNetwork:this.targetNetwork.getParameters(),dqnConfig:this.dqnConfig,updateCount:this.updateCount}}async importCustomData(e){e.qNetwork&&this.qNetwork.setParameters(e.qNetwork),e.targetNetwork&&this.targetNetwork.setParameters(e.targetNetwork),e.dqnConfig&&(this.dqnConfig={...this.dqnConfig,...e.dqnConfig}),typeof e.updateCount=="number"&&(this.updateCount=e.updateCount),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new $({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var MCu={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},iu=B.create("security-compliance"),ot=class extends Y{constructor(u,a,t,r={}){let i={...MCu,...r};super(u,"security-compliance",i,{verifyFindingTypes:["security-vulnerability","compliance-violation","credential-exposure"],...i.consensusMixinConfig});this.memory=a;this.agentCoordinator=t;this.securityGovernanceMixin=xc(this.domainName),this.securityScanner=new Ou(a),this.securityAuditor=new u0(a),this.complianceValidator=new e0(a)}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 Ti({stateSize:8,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0})),this.config.enableFlashAttention){let u="test-similarity";this.flashAttention=await Ku(u,{dim:384,strategy:"flash",numHeads:8})}if(this.config.enableConsensus){let a=Ve(!0).getAll();a.length>0?(this.consensusEngine=ba({strategy:"weighted",models:a,engineConfig:{minModels:Math.min(2,a.length),defaultModelTimeout:6e4,...this.config.consensusEngineConfig}}),iu.info(`Multi-Model Consensus initialized with ${a.length} providers`)):iu.warn("No model providers available for consensus verification")}this.rlInitialized=!0}catch(u){throw iu.error("Failed to initialize RL integrations:",u instanceof Error?u:void 0),u}}async onDispose(){await this.saveWorkflowState()}getActiveWorkflows(){return super.getActiveWorkflows()}async runSecurityAudit(u){let a=A();try{if(this.startWorkflow(a,"audit"),this.detectAuthCodeInScope(u)&&this.securityGovernanceMixin.isGovernanceEnabled()&&!(await this.securityGovernanceMixin.validateSecurityScanRequired(a,!0,void 0)).allowed&&this.securityGovernanceMixin.isStrictMode()&&iu.info("Security audit for auth code registered with governance"),this.minCutMixin.shouldPauseOperations())return iu.warn("Security audit paused: topology is in critical state"),this.failWorkflow(a,"Topology is in critical state"),m(new Error("Security audit paused: topology is in critical state"));if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&iu.warn("Topology degraded, using conservative audit strategy"),!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn security audit agents"));let r=await this.spawnSecurityAuditAgent(a,u);if(!r.success)return this.failWorkflow(a,r.error.message),m(r.error);this.addAgentToWorkflow(a,r.value);let i=u.tests||[];this.config.enableDQN&&this.dqnAlgorithm&&i.length>0&&(i=await this.prioritizeSecurityTests(u,i));let n={...u},o=await this.securityAuditor.runAudit(n);if(o.success){this.completeWorkflow(a);let l=this.extractVulnerabilitiesFromReport(o.value);this.config.enableFlashAttention&&this.flashAttention&&l.length>0&&await this.enhanceVulnerabilityAnalysis(l),this.config.enableDQN&&this.dqnAlgorithm&&await this.trainDQNWithAuditFeedback(u,o.value),this.config.publishEvents&&await this.publishSecurityAuditCompleted(o.value)}else this.failWorkflow(a,o.error.message);return await this.agentCoordinator.stop(r.value),o}catch(t){let r=g(t);return this.failWorkflow(a,r.message),{success:!1,error:r}}}async runSecurityScan(u,a){let t=A();try{if(this.startWorkflow(t,"scan"),this.minCutMixin.shouldPauseOperations())return iu.warn("Security scan paused: topology is in critical state"),this.failWorkflow(t,"Topology is in critical state"),m(new Error("Security scan paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&iu.warn("Topology degraded, proceeding with conservative scan strategy");let r;return a==="sast"?r=await this.securityScanner.scanFiles(u):a==="dast"?r=await this.securityScanner.scanUrl(u[0]?.value??""):r=await this.securityScanner.scanFiles(u),r.success?this.completeWorkflow(t):this.failWorkflow(t,r.error.message),r}catch(r){let i=g(r);return this.failWorkflow(t,i.message),{success:!1,error:i}}}async runComplianceValidation(u,a){let t=A();try{if(this.startWorkflow(t,"compliance"),this.minCutMixin.shouldPauseOperations())return iu.warn("Compliance validation paused: topology is in critical state"),this.failWorkflow(t,"Topology is in critical state"),m(new Error("Compliance validation paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&iu.warn("Topology degraded, proceeding with compliance validation");let i=(await this.complianceValidator.getAvailableStandards()).find(o=>o.id===u);if(!i)return m(new Error(`Unknown compliance standard: ${u}`));let n=await this.complianceValidator.validate(i,a);return n.success?(this.completeWorkflow(t),this.config.publishEvents&&await this.publishComplianceValidationCompleted(n.value)):this.failWorkflow(t,n.error.message),n}catch(r){let i=g(r);return this.failWorkflow(t,i.message),{success:!1,error:i}}}async assessSecurityPosture(){let u=A();try{if(this.startWorkflow(u,"posture"),this.minCutMixin.shouldPauseOperations())return iu.warn("Security posture assessment paused: topology is in critical state"),this.failWorkflow(u,"Topology is in critical state"),m(new Error("Security posture assessment paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&iu.warn("Topology degraded, proceeding with security posture assessment");let a=await this.securityAuditor.getSecurityPosture();if(a.success){this.completeWorkflow(u);let t={overallScore:a.value.overallScore,trend:a.value.trend,criticalVulnerabilities:a.value.criticalIssues,complianceStatus:new Map,lastAuditDate:a.value.lastAuditDate};return p(t)}else return this.failWorkflow(u,a.error.message),a}catch(a){let t=g(a);return this.failWorkflow(u,t.message),{success:!1,error:t}}}async runComplianceCheck(u){let a={projectRoot:yu.create("."),includePatterns:["**/*.ts","**/*.js"],excludePatterns:["node_modules/**"]};return this.runComplianceValidation(u,a)}async getSecurityPosture(){return this.assessSecurityPosture()}async prioritizeSecurityTests(u,a){if(!this.dqnAlgorithm||!this.rlInitialized)return a;try{let t=await Promise.all(a.map(async r=>{let i={id:`test-${r}`,features:this.extractSecurityTestFeatures(u,r)},n=await this.dqnAlgorithm.predict(i);return{test:r,score:n.value||0}}));return t.sort((r,i)=>i.score-r.score),t.map(r=>r.test)}catch(t){return iu.error("Failed to prioritize security tests:",t instanceof Error?t:void 0),a}}async trainDQNWithAuditFeedback(u,a){if(!(!this.dqnAlgorithm||!this.rlInitialized))try{let t=this.extractVulnerabilitiesFromReport(a),r={id:`audit-${a.auditId}-${Date.now()}`,features:this.extractAuditFeatures(u)},i={type:"run-audit",value:t.length},n=this.calculateAuditReward(a),o={state:r,action:i,reward:n,nextState:r,done:!0,timestamp:new Date};await this.dqnAlgorithm.train(o),iu.info(`Trained security audit with reward: ${n.toFixed(3)}`)}catch(t){iu.error("Failed to train DQN:",t instanceof Error?t:void 0)}}calculateAuditReward(u){let a=this.extractVulnerabilitiesFromReport(u);if(a.length===0)return .5;let t=.5,r=a.filter(n=>n.severity==="critical").length;t+=Math.min(.3,r*.1);let i=a.filter(n=>n.severity==="high").length;return t+=Math.min(.2,i*.05),t+=(u.overallRiskScore?.value??0)*.1,Math.max(0,Math.min(1,t))}extractSecurityTestFeatures(u,a){let t=u.targetUrl??"";return[t.includes("/api")?1:0,t.startsWith("http")?1:0,u.includeSAST?1:0,a.includes("auth")?1:0,a.includes("sql")?1:0,a.includes("xss")?1:0,a.includes("injection")?1:0,a.length/100]}extractAuditFeatures(u){let a=u.depth??"standard",t=a==="deep"?1:a==="standard"?.5:.25;return[u.includeSAST?1:0,u.includeDAST?1:0,t,(u.scanTypes?.length??0)/4,u.includeDependencies?1:0,u.includeSecrets?1:0,(u.complianceFrameworks?.length??0)/5,u.targetUrl?1:0]}async enhanceVulnerabilityAnalysis(u){if(!(!this.flashAttention||!this.rlInitialized||u.length===0))try{let a=u.map(c=>this.createVulnerabilityEmbedding(c)),t=a.length,r=a[0].length,i=new Float32Array(t*r),n=new Float32Array(t*r),o=new Float32Array(t*r);for(let c=0;c<t;c++)i.set(a[c],c*r),n.set(a[c],c*r),o.set(a[c],c*r);let l=await this.flashAttention.computeFlashAttention(i,n,o,t,r);for(let c=0;c<u.length;c++){let E=Array.from(l.slice(c*r,(c+1)*r));a[c].reduce((D,h,C)=>D+h*E[C],0)>.7&&iu.info(`High self-attention for vulnerability ${u[c].id}`)}}catch(a){iu.error("Failed to enhance vulnerability analysis:",a instanceof Error?a:void 0)}}createVulnerabilityEmbedding(u){let a=[],t=this.hashCode(u.category);a.push(t%1e3/1e3);let r={critical:1,high:.75,medium:.5,low:.25,informational:.1};a.push(r[u.severity]||.5);let i=this.hashCode(u.title);a.push(i%1e3/1e3),a.push(Math.min(1,u.description.length/500));let n=u.cveId?this.hashCode(u.cveId):0;a.push(n%1e3/1e3);let o=this.hashCode(u.description.slice(0,200));for(let l=a.length;l<384;l++)a.push(o*(l+1)%1e4/1e4);return a.slice(0,384)}hashCode(u){let a=0;for(let t=0;t<u.length;t++)a=(a<<5)-a+u.charCodeAt(t),a=a|0;return Math.abs(a)}async spawnSecurityAuditAgent(u,a){let t={name:`security-auditor-${u.slice(0,8)}`,domain:"security-compliance",type:"auditor",capabilities:["security-audit","vulnerability-scanning","compliance-check"],config:{workflowId:u,targetUrl:a.targetUrl,depth:a.depth}};return this.agentCoordinator.spawn(t)}extractVulnerabilitiesFromReport(u){let a=[];return u.sastResults?.vulnerabilities&&a.push(...u.sastResults.vulnerabilities),u.dastResults?.vulnerabilities&&a.push(...u.dastResults.vulnerabilities),u.dependencyResults?.vulnerabilities&&a.push(...u.dependencyResults.vulnerabilities),a}async publishSecurityAuditCompleted(u){let a=this.extractVulnerabilitiesFromReport(u),t=await this.verifyHighSeverityFindings(a);for(let r of t){let i={vulnId:r.id,cve:r.cveId,severity:r.severity,file:r.location.file,line:r.location.line,description:r.description,remediation:r.remediation.description},n=L(Yi.SecurityAuditCompleted,"security-compliance",i);await this.eventBus.publish(n)}}async verifyHighSeverityFindings(u){if(!this.config.enableConsensus)return u;if(!this.isConsensusAvailable())return this.consensusEngine?this.verifyHighSeverityFindingsLegacy(u):u;let a=[],t=u.filter(n=>n.severity==="critical"||n.severity==="high"),r=u.filter(n=>n.severity!=="critical"&&n.severity!=="high");a.push(...r);for(let n of t)try{let o=O({id:n.id,type:"security-vulnerability",confidence:.8,description:`${n.title}: ${n.description}`,payload:{vulnerability:n,location:n.location},detectedBy:"security-scanner",severity:n.severity,context:{domain:this.domainName,cveId:n.cveId,category:n.category}});if(!this.consensusMixin.requiresConsensus(o)){a.push(n);continue}let l=await this.consensusMixin.verifyFinding(o);l.success&&l.value.verdict==="verified"?(iu.info(`Consensus VERIFIED: ${n.title} (confidence: ${(l.value.confidence*100).toFixed(1)}%)`),a.push(n)):l.success&&l.value.verdict==="disputed"?(iu.info(`Consensus DISPUTED: ${n.title} - including with lower confidence`),a.push(n)):iu.info(`Consensus REJECTED: ${n.title} - likely false positive`)}catch{iu.warn(`Consensus error verifying ${n.title}, including by default:`),a.push(n)}let i=t.length-a.filter(n=>n.severity==="critical"||n.severity==="high").length;return i>0&&iu.info(`Consensus filtered out ${i} likely false positive(s)`),a}async verifyHighSeverityFindingsLegacy(u){if(!this.consensusEngine)return u;let a=[],t=u.filter(i=>i.severity==="critical"||i.severity==="high"),r=u.filter(i=>i.severity!=="critical"&&i.severity!=="high");a.push(...r);for(let i of t)try{let n={id:i.id,type:i.category,description:i.description,category:i.category,severity:i.severity,location:{file:i.location.file,line:i.location.line,column:i.location.column},evidence:[{type:"code-snippet",content:i.location.snippet||i.description}],cveId:i.cveId,remediation:i.remediation.description,detectedAt:new Date,detectedBy:"security-scanner"},o=await this.consensusEngine.verify(n);(o.success&&o.value.verdict==="verified"||o.success&&o.value.verdict==="disputed")&&a.push(i)}catch{a.push(i)}return a}async publishComplianceValidationCompleted(u){let a={standard:u.standardId,passed:u.complianceScore>=.8,violations:u.violations.length,findings:u.violations.map(r=>r.details).slice(0,10)},t=L(Yi.ComplianceValidated,"security-compliance",a);await this.eventBus.publish(t)}detectAuthCodeInScope(u){let a=[/auth/i,/login/i,/password/i,/token/i,/session/i,/oauth/i,/jwt/i,/credential/i,/identity/i];if(u.targetUrl){for(let t of a)if(t.test(u.targetUrl))return!0}if(u.scanTypes){let t=["authentication","authorization","session-management"];for(let r of u.scanTypes)if(t.includes(r.toLowerCase()))return!0}if(u.complianceFrameworks){let t=["soc2","pci-dss","hipaa","iso27001"];for(let r of u.complianceFrameworks)if(t.includes(r.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(u){}async handleImpactAnalysis(u){}async loadWorkflowState(){let u=await this.memory.get("security-compliance:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("security-compliance:coordinator:workflows",u,{namespace:"security-compliance",persist:!0})}getHealthyRoutingDomains(){return this.minCutMixin.getHealthyRoutingDomains()}};S();var Mi=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.target??u.targetUrl;return a?this.coordinator.runSecurityAudit({includeSAST:u.includeSAST??!0,includeDAST:u.includeDAST??!1,includeDependencies:u.includeDependencies??!0,includeSecrets:u.includeSecrets??!0,targetUrl:a}):m(new Error("Invalid security-audit payload: missing target"))}],["compliance-check",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.standardId;return a?this.coordinator.runComplianceCheck(a):m(new Error("Invalid compliance-check payload: missing standardId"))}],["sast-scan",async u=>{if(!this.securityScanner)return m(new Error("Security scanner not initialized"));let a=u.files;return!a||a.length===0?m(new Error("Invalid sast-scan payload: missing files")):this.securityScanner.scanFiles(a)}],["dast-scan",async u=>{if(!this.securityScanner)return m(new Error("Security scanner not initialized"));let a=u.targetUrl;return a?this.securityScanner.scanUrl(a):m(new Error("Invalid dast-scan payload: missing targetUrl"))}],["triage-vulnerabilities",async u=>{if(!this.securityAuditor)return m(new Error("Security auditor not initialized"));let a=u.vulnerabilities;return!a||a.length===0?m(new Error("Invalid triage-vulnerabilities payload: missing vulnerabilities")):this.securityAuditor.triageVulnerabilities(a)}]])}async onInitialize(){this.securityScanner=new Ou(this.memory,this.pluginConfig.securityScanner),this.securityAuditor=new u0(this.memory,this.pluginConfig.securityAuditor),this.complianceValidator=new e0(this.memory,this.pluginConfig.complianceValidator),this.coordinator=new ot(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"code-intelligence.KnowledgeGraphUpdated":await this.handleKnowledgeGraphUpdate(u);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(u);break;default:break}}async runSecurityAudit(u){this.ensureInitialized();try{let a=await this.coordinator.runSecurityAudit(u);return a.success?this.trackSuccessfulOperation("audit"):this.trackFailedOperation("audit",a.error),a}catch(a){return this.handleError(a)}}async getSecurityPosture(){this.ensureInitialized();try{return await this.coordinator.getSecurityPosture()}catch(u){return this.handleError(u)}}async runSASTScan(u){this.ensureInitialized();try{let a=await this.securityScanner.scanFiles(u);return a.success?this.trackSuccessfulOperation("sast-scan"):this.trackFailedOperation("sast-scan",a.error),a}catch(a){return this.handleError(a)}}async runDASTScan(u){this.ensureInitialized();try{let a=await this.securityScanner.scanUrl(u);return a.success?this.trackSuccessfulOperation("dast-scan"):this.trackFailedOperation("dast-scan",a.error),a}catch(a){return this.handleError(a)}}async triageVulnerabilities(u){this.ensureInitialized();try{let a=await this.securityAuditor.triageVulnerabilities(u);return a.success?{success:!0,value:{immediate:a.value.immediate,shortTerm:a.value.shortTerm}}:{success:!1,error:a.error}}catch(a){return this.handleError(a)}}async runComplianceCheck(u){this.ensureInitialized();try{let a=await this.coordinator.runComplianceCheck(u);return a.success?this.trackSuccessfulOperation("compliance-check"):this.trackFailedOperation("compliance-check",a.error),a}catch(a){return this.handleError(a)}}async getAvailableStandards(){return this.ensureInitialized(),this.complianceValidator.getAvailableStandards()}async analyzeComplianceGaps(u,a){this.ensureInitialized();try{return await this.complianceValidator.analyzeGaps(u,a)}catch(t){return this.handleError(t)}}async handleKnowledgeGraphUpdate(u){let a=u.payload;await this.memory.set(`security:code-update:${Date.now()}`,{filesIndexed:a.filesIndexed,timestamp:new Date},{namespace:"security-compliance",ttl:3600})}async handleQualityGateEvaluated(u){let a=u.payload,t=a.checks.filter(r=>r.name.toLowerCase().includes("security"));t.length>0&&await this.memory.set(`security:gate-results:${a.gateId}`,{securityChecks:t,passed:a.passed},{namespace:"security-compliance",persist:!0})}async handleTestRunCompleted(u){}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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date}),this.memory.set(`security:operation:${u}:${Date.now()}`,{operation:u,success:!0,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}trackFailedOperation(u,a){let t=this.getHealth();this.updateHealth({agents:{...t.agents,failed:t.agents.failed+1},errors:[...t.errors.slice(-9),a.message]}),this.memory.set(`security:operation:${u}:${Date.now()}`,{operation:u,success:!1,error:a.message,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}};function jl(s,e,u,a){return new Mi(s,e,u,a)}N();S();N();S();J();var RCu={strictMode:!0,validateExamples:!0,maxSchemaDepth:tr.MAX_SCHEMA_DEPTH,cacheValidations:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:rr.MAX_TOKENS},PCu=B.create("contract-testing/contract-validator"),K0=class{config;memory;llmRouter;validationCache=new Map;MAX_CACHED_VALIDATIONS=tr.MAX_CACHED_VALIDATIONS;CACHE_TTL_MS=tr.CACHE_TTL_MS;constructor(e,u={}){this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...RCu,...u}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(e){let u={1:"claude-3-haiku-20240307",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return u[e]||u[2]}async analyzeContractWithLLM(e){if(!this.isLLMAnalysisAvailable())return null;try{let u=e.consumers.map(t=>t.name).join(", ");return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this API contract for potential issues:
2932
2932
  Provider: ${e.provider.name}
2933
2933
  Consumers: ${u}
2934
2934
  Version: ${e.version.toString()}
@@ -2944,7 +2944,7 @@ Provide:
2944
2944
  `||i===" "||i===",")&&a===0){if(t.trim()){let n=this.parseGraphQLField(t.trim());n&&u.push(n)}t=""}else t+=i;r++}if(t.trim()){let i=this.parseGraphQLField(t.trim());i&&u.push(i)}return u}parseGraphQLField(e){let u=e.match(/^(\w+)\s*:\s*(.+)$/),a=e,t;u&&!u[2].includes("(")&&!u[2].includes("{")||u&&(u[2].match(/^\w/)||u[2].includes("("))&&(t=u[1],a=u[2]);let r=a.match(/^(\w+)(?:\s*\(([^)]*)\))?(?:\s*\{([\s\S]*)\})?$/);if(!r){let n=a.match(/^(\w+)(?:\s*\(([^)]*)\))?/);return n?{name:n[1],alias:t,arguments:n[2]?this.parseGraphQLArguments(n[2]):void 0}:null}let i={name:r[1],alias:t};return r[2]&&(i.arguments=this.parseGraphQLArguments(r[2])),r[3]&&(i.selections=this.parseGraphQLSelectionSet(r[3])),i}parseGraphQLArguments(e){let u={},a=e.matchAll(/(\w+)\s*:\s*([^,\)]+)/g);for(let t of a){let r=t[2].trim();r.startsWith("$")?u[t[1]]={_variable:r.substring(1)}:r.startsWith('"')||r.startsWith("'")?u[t[1]]=r.slice(1,-1):r==="true"?u[t[1]]=!0:r==="false"?u[t[1]]=!1:r==="null"?u[t[1]]=null:isNaN(Number(r))?u[t[1]]=r:u[t[1]]=Number(r)}return u}getRootTypeForOperation(e,u){switch(e){case"query":return u.queryType;case"mutation":return u.mutationType;case"subscription":return u.subscriptionType;default:return null}}unwrapGraphQLType(e){return e.replace(/[\[\]!]/g,"").trim()}validateGraphQLSelections(e,u,a,t,r){let i=a.types[u];if(!i){["String","Int","Float","Boolean","ID"].includes(u)&&e.length>0&&r.push({path:t,keyword:"selection",message:`Cannot select fields on scalar type '${u}'`,params:{type:u}});return}for(let n of e){let o=i.fields[n.name];if(!o)r.push({path:`${t}.${n.name}`,keyword:"field",message:`Field '${n.name}' does not exist on type '${u}'`,params:{field:n.name,type:u}});else if(n.selections&&n.selections.length>0){let l=this.unwrapGraphQLType(o.type);this.validateGraphQLSelections(n.selections,l,a,`${t}.${n.name}`,r)}}}validateGraphQLVariableType(e,u,a,t){let r=this.unwrapGraphQLType(u),i=u.endsWith("!"),n=u.includes("[");if(e==null){i&&t.push({path:a,keyword:"type",message:`Variable cannot be null (expected ${u})`,params:{expectedType:u}});return}if(n){Array.isArray(e)||t.push({path:a,keyword:"type",message:`Expected array for type ${u}`,params:{expectedType:u,actualType:typeof e}});return}switch(r){case"String":case"ID":typeof e!="string"&&t.push({path:a,keyword:"type",message:`Expected string for type ${r}`,params:{expectedType:r,actualType:typeof e}});break;case"Int":(typeof e!="number"||!Number.isInteger(e))&&t.push({path:a,keyword:"type",message:"Expected integer for type Int",params:{expectedType:"Int",actualType:typeof e}});break;case"Float":typeof e!="number"&&t.push({path:a,keyword:"type",message:"Expected number for type Float",params:{expectedType:"Float",actualType:typeof e}});break;case"Boolean":typeof e!="boolean"&&t.push({path:a,keyword:"type",message:"Expected boolean for type Boolean",params:{expectedType:"Boolean",actualType:typeof e}});break;default:typeof e!="object"&&t.push({path:a,keyword:"type",message:`Expected object for type ${r}`,params:{expectedType:r,actualType:typeof e}})}}basicTypeValidation(e,u,a,t,r=0){if(r>this.config.maxSchemaDepth){t.push({path:a,keyword:"maxDepth",message:"Maximum schema depth exceeded",params:{maxDepth:this.config.maxSchemaDepth}});return}let i=u.type;if(!i)return;let n=this.getJsonType(e);if(i==="object"&&n==="object"){let o=u.properties||{},l=u.required||[],c=e;for(let E of l)E in c||t.push({path:a?`${a}.${E}`:E,keyword:"required",message:`Required property '${E}' is missing`,params:{missingProperty:E}});for(let[E,d]of Object.entries(o))E in c&&this.basicTypeValidation(c[E],d,a?`${a}.${E}`:E,t,r+1)}else if(i==="array"&&n==="array"){let o=u.items,l=e;if(this.validateArrayConstraints(l,u,a,t),o)for(let c=0;c<l.length;c++)this.basicTypeValidation(l[c],o,`${a}[${c}]`,t,r+1)}else i==="string"&&n==="string"?this.validateStringConstraints(e,u,a,t):(i==="number"||i==="integer")&&(n==="number"||n==="integer")?this.validateNumberConstraints(e,u,a,t):i!==n&&(i==="number"&&n==="integer"||t.push({path:a,keyword:"type",message:`Expected type '${i}' but got '${n}'`,params:{expectedType:i,actualType:n}}));if(u.enum){let o=u.enum;o.some(l=>JSON.stringify(l)===JSON.stringify(e))||t.push({path:a,keyword:"enum",message:`Value must be one of: ${o.map(l=>JSON.stringify(l)).join(", ")}`,params:{allowedValues:o}})}}validateStringConstraints(e,u,a,t){let r=u.minLength,i=u.maxLength,n=u.pattern;if(r!==void 0&&e.length<r&&t.push({path:a,keyword:"minLength",message:`String must be at least ${r} characters`,params:{limit:r,actual:e.length}}),i!==void 0&&e.length>i&&t.push({path:a,keyword:"maxLength",message:`String must be at most ${i} characters`,params:{limit:i,actual:e.length}}),n){let o=Y0(n);o&&!o.test(e)&&t.push({path:a,keyword:"pattern",message:`String must match pattern: ${n}`,params:{pattern:n}})}}validateNumberConstraints(e,u,a,t){let r=u.minimum,i=u.maximum,n=u.exclusiveMinimum,o=u.exclusiveMaximum,l=u.multipleOf;r!==void 0&&e<r&&t.push({path:a,keyword:"minimum",message:`Number must be >= ${r}`,params:{limit:r,actual:e}}),i!==void 0&&e>i&&t.push({path:a,keyword:"maximum",message:`Number must be <= ${i}`,params:{limit:i,actual:e}}),n!==void 0&&e<=n&&t.push({path:a,keyword:"exclusiveMinimum",message:`Number must be > ${n}`,params:{limit:n,actual:e}}),o!==void 0&&e>=o&&t.push({path:a,keyword:"exclusiveMaximum",message:`Number must be < ${o}`,params:{limit:o,actual:e}}),l!==void 0&&e%l!==0&&t.push({path:a,keyword:"multipleOf",message:`Number must be a multiple of ${l}`,params:{multipleOf:l,actual:e}})}validateArrayConstraints(e,u,a,t){let r=u.minItems,i=u.maxItems,n=u.uniqueItems;if(r!==void 0&&e.length<r&&t.push({path:a,keyword:"minItems",message:`Array must have at least ${r} items`,params:{limit:r,actual:e.length}}),i!==void 0&&e.length>i&&t.push({path:a,keyword:"maxItems",message:`Array must have at most ${i} items`,params:{limit:i,actual:e.length}}),n){let o=new Set;for(let l=0;l<e.length;l++){let c=JSON.stringify(e[l]);if(o.has(c)){t.push({path:`${a}[${l}]`,keyword:"uniqueItems",message:"Array items must be unique",params:{duplicateIndex:l}});break}o.add(c)}}}getJsonType(e){return e===null?"null":Array.isArray(e)?"array":typeof e=="number"?Number.isInteger(e)?"integer":"number":typeof e}validateOpenAPI3Structure(e,u,a){if(!e.info)u.push({path:"info",message:"OpenAPI 3.x requires info object",code:"REQUIRED_FIELD"});else{let t=e.info;t.title||u.push({path:"info.title",message:"API title is required",code:"REQUIRED_FIELD"}),t.version||u.push({path:"info.version",message:"API version is required",code:"REQUIRED_FIELD"})}e.paths||a.push("No paths defined in OpenAPI specification")}validateSwagger2Structure(e,u,a){e.info||u.push({path:"info",message:"Swagger 2 requires info object",code:"REQUIRED_FIELD"}),e.paths||a.push("No paths defined in Swagger specification"),!e.host&&!e.basePath&&a.push("No host or basePath defined in Swagger specification")}async storeValidationHistory(e,u){let a=`contract-testing:validation:${e}:${Date.now()}`;await this.memory.set(a,u,{namespace:"contract-testing",ttl:86400*30})}cacheValidation(e,u){if(this.validationCache.size>=this.MAX_CACHED_VALIDATIONS){let a=this.validationCache.keys().next().value;a&&this.validationCache.delete(a)}this.validationCache.set(e,{...u,cachedAt:Date.now()})}cleanupCache(){let e=Date.now(),u=0;for(let[a,t]of this.validationCache)e-(t.cachedAt||0)>this.CACHE_TTL_MS&&(this.validationCache.delete(a),u++);return u}destroy(){this.validationCache.clear()}};S();J();var zCu={strictEnumValidation:!0,allowOptionalToRequired:!1,trackDeprecations:!0,maxMigrationSteps:50},j0=class{constructor(e,u={}){this.memory=e;this.config={...zCu,...u}}config;async compareVersions(e,u){try{let a=[],t=[],r=[];await this.compareEndpoints(e.endpoints,u.endpoints,e.consumers.map(n=>n.name),a,t),await this.compareSchemas(e.schemas,u.schemas,e.consumers.map(n=>n.name),a,t),this.config.trackDeprecations&&this.detectDeprecations(e,u,r);let i={isCompatible:a.length===0,breakingChanges:a,nonBreakingChanges:t,deprecations:r};return await this.storeComparisonResult(e,u,i),p(i)}catch(a){return m(g(a))}}async isBackwardCompatible(e,u){let a=await this.compareVersions(e,u);return a.success?p(a.value.breakingChanges.length===0):a}async getBreakingChanges(e,u){let a=await this.compareVersions(e,u);return a.success?p(a.value.breakingChanges):a}async generateMigrationGuide(e){try{if(e.length===0)return p({fromVersion:"unknown",toVersion:"unknown",steps:[],estimatedEffort:"trivial"});let u=[],a=1,t=e.filter(d=>d.type==="removed-endpoint"),r=e.filter(d=>d.type==="type-change"),i=e.filter(d=>d.type==="required-field-added"),n=e.filter(d=>d.type==="removed-field"),o=e.filter(d=>d.type==="enum-value-removed"),l=e.filter(d=>d.type==="response-code-change");for(let d of i)u.push(this.createMigrationStep(a++,d,"required-field"));for(let d of r)u.push(this.createMigrationStep(a++,d,"type-change"));for(let d of o)u.push(this.createMigrationStep(a++,d,"enum-change"));for(let d of n)u.push(this.createMigrationStep(a++,d,"removed-field"));for(let d of l)u.push(this.createMigrationStep(a++,d,"response-code"));for(let d of t)u.push(this.createMigrationStep(a++,d,"removed-endpoint"));let c=u.slice(0,this.config.maxMigrationSteps),E=this.estimateEffort(e);return p({fromVersion:"previous",toVersion:"current",steps:c,estimatedEffort:E})}catch(u){return m(g(u))}}async compareEndpoints(e,u,a,t,r){let i=this.buildEndpointMap(e),n=this.buildEndpointMap(u),o=Array.from(i.entries());for(let[c,E]of o)n.has(c)||t.push({type:"removed-endpoint",location:`${E.method} ${E.path}`,description:`Endpoint ${E.method} ${E.path} has been removed`,impact:"high",affectedConsumers:a,migrationPath:"Find alternative endpoint or remove usage"});let l=Array.from(n.entries());for(let[c,E]of l)i.has(c)||r.push({type:"added-endpoint",location:`${E.method} ${E.path}`,description:`New endpoint ${E.method} ${E.path} added`});for(let[c,E]of o){let d=n.get(c);d&&await this.compareEndpointDetails(E,d,a,t,r)}}async compareEndpointDetails(e,u,a,t,r){let i=`${e.method} ${e.path}`;e.requestSchema!==u.requestSchema&&t.push({type:"type-change",location:`${i} request`,description:`Request schema changed from '${e.requestSchema||"none"}' to '${u.requestSchema||"none"}'`,impact:"high",affectedConsumers:a}),e.responseSchema!==u.responseSchema&&t.push({type:"type-change",location:`${i} response`,description:`Response schema changed from '${e.responseSchema||"none"}' to '${u.responseSchema||"none"}'`,impact:"medium",affectedConsumers:a});let n=new Set(e.examples.map(c=>c.statusCode)),o=new Set(u.examples.map(c=>c.statusCode)),l=Array.from(n);for(let c of l)o.has(c)||t.push({type:"response-code-change",location:`${i} status ${c}`,description:`Status code ${c} is no longer documented`,impact:"low",affectedConsumers:a})}async compareSchemas(e,u,a,t,r){let i=new Map(e.map(E=>[E.id,E])),n=new Map(u.map(E=>[E.id,E])),o=Array.from(i.keys());for(let E of o)n.has(E)||t.push({type:"removed-field",location:`schema:${E}`,description:`Schema '${E}' has been removed`,impact:"high",affectedConsumers:a});let l=Array.from(n.keys());for(let E of l)i.has(E)||r.push({type:"added-field",location:`schema:${E}`,description:`New schema '${E}' added`});let c=Array.from(i.entries());for(let[E,d]of c){let D=n.get(E);D&&await this.compareSchemaContent(d,D,a,t,r)}}async compareSchemaContent(e,u,a,t,r){if(!(e.type!=="json-schema"||u.type!=="json-schema"))try{let i=T(e.content),n=T(u.content),o=i.properties||{},l=n.properties||{},c=i.required||[],E=n.required||[];for(let d of Object.keys(o))d in l||t.push({type:"removed-field",location:`schema:${e.id}.${d}`,description:`Property '${d}' has been removed from schema '${e.id}'`,impact:"high",affectedConsumers:a});for(let d of Object.keys(l))d in o||r.push({type:"added-field",location:`schema:${u.id}.${d}`,description:`Property '${d}' added to schema '${u.id}'`});for(let d of E)c.includes(d)||(d in o?this.config.allowOptionalToRequired||t.push({type:"required-field-added",location:`schema:${u.id}.${d}`,description:`Property '${d}' changed from optional to required in schema '${u.id}'`,impact:"high",affectedConsumers:a}):d in l&&t.push({type:"required-field-added",location:`schema:${u.id}.${d}`,description:`New required property '${d}' added to schema '${u.id}'`,impact:"high",affectedConsumers:a}));for(let d of Object.keys(o))if(d in l){let D=o[d],h=l[d];if(D.type!==h.type&&t.push({type:"type-change",location:`schema:${e.id}.${d}`,description:`Type of '${d}' changed from '${D.type}' to '${h.type}'`,impact:"high",affectedConsumers:a}),this.config.strictEnumValidation){let C=D.enum,y=h.enum;if(C&&y){for(let x of C)y.includes(x)||t.push({type:"enum-value-removed",location:`schema:${e.id}.${d}`,description:`Enum value '${x}' removed from '${d}'`,impact:"medium",affectedConsumers:a});for(let x of y)C.includes(x)||r.push({type:"added-enum-value",location:`schema:${u.id}.${d}`,description:`Enum value '${x}' added to '${d}'`})}}}}catch{}}detectDeprecations(e,u,a){let t=this.buildEndpointMap(e.endpoints),r=this.buildEndpointMap(u.endpoints);for(let[i,n]of t)r.get(i)||a.push({location:`${n.method} ${n.path}`,reason:"Endpoint has been removed in the new version",removalVersion:u.version.toString()});for(let i of u.schemas)this.detectSchemaDeprecations(i,a,u.version);for(let i of u.endpoints)if(i.path.includes("/deprecated/")&&a.push({location:`${i.method} ${i.path}`,reason:"Endpoint path indicates deprecation"}),i.responseSchema){let n=u.schemas.find(o=>o.name===i.responseSchema);n&&this.detectSchemaDeprecations(n,a,u.version,`${i.method} ${i.path}`)}}detectSchemaDeprecations(e,u,a,t){try{let r=typeof e.content=="string"?T(e.content):e.content;this.scanObjectForDeprecations(r,e.name,u,a,t)}catch{}}scanObjectForDeprecations(e,u,a,t,r){if(!e||typeof e!="object")return;let i=e;if(i.deprecated===!0){let n=r?`${r} -> ${u}`:u;a.push({location:n,reason:typeof i.description=="string"?i.description:"Field marked as deprecated",removalVersion:typeof i.removalVersion=="string"?i.removalVersion:void 0,replacement:typeof i.replacement=="string"?i.replacement:void 0})}if(i["x-deprecated"]===!0){let n=r?`${r} -> ${u}`:u;a.push({location:n,reason:typeof i["x-deprecated-message"]=="string"?i["x-deprecated-message"]:"Element marked as deprecated via x-deprecated",removalVersion:t.toString()})}if(i.properties&&typeof i.properties=="object"){let n=i.properties;for(let[o,l]of Object.entries(n))this.scanObjectForDeprecations(l,`${u}.${o}`,a,t,r)}i.items&&typeof i.items=="object"&&this.scanObjectForDeprecations(i.items,`${u}[]`,a,t,r)}buildEndpointMap(e){let u=new Map;for(let a of e){let t=`${a.method}:${a.path}`;u.set(t,a)}return u}createMigrationStep(e,u,a){let t,r,i=!1;switch(a){case"required-field":t=`Add required field: ${u.description}`,r=`// Add the new required field to your request/data objects
2945
2945
  // Location: ${u.location}`,i=!1;break;case"type-change":t=`Update type: ${u.description}`,r=`// Update the type at ${u.location}
2946
2946
  // Follow the new type specification`,i=!1;break;case"enum-change":t=`Update enum usage: ${u.description}`,r=`// Remove usage of deprecated enum value at ${u.location}`,i=!0;break;case"removed-field":t=`Remove field usage: ${u.description}`,r=`// Remove references to ${u.location}`,i=!0;break;case"response-code":t=`Update response handling: ${u.description}`,r=`// Update error handling for ${u.location}`,i=!1;break;case"removed-endpoint":t=`Migrate from removed endpoint: ${u.description}`,r=u.migrationPath?`// ${u.migrationPath}`:`// Find alternative for ${u.location}`,i=!1;break;default:t=u.description,r=void 0,i=!1}return{order:e,description:t,codeChanges:r,automated:i}}estimateEffort(e){if(e.length===0)return"trivial";let u=e.filter(t=>t.impact==="high").length,a=e.filter(t=>t.impact==="medium").length;return u>5||e.length>10?"major":u>2||a>5?"moderate":u>0||e.length>3?"minor":"trivial"}async storeComparisonResult(e,u,a){let t=`contract-testing:comparison:${e.id}:${e.version.toString()}:${u.version.toString()}`;await this.memory.set(t,{oldVersion:e.version.toString(),newVersion:u.version.toString(),isCompatible:a.isCompatible,breakingChangeCount:a.breakingChanges.length,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400*90})}};var LCu={stateSize:10,actionSize:4,hiddenLayers:[128,128],minReplaySize:100},Ri=class extends Eu{qNetwork;replayBufferClass;sarsaConfig;actions=[];constructor(e={}){super("sarsa","value-based"),this.sarsaConfig={...LCu,...e},this.initializeActions(),this.qNetwork=new $({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.replayBufferClass=new ie(this.config.replayBufferSize,!1)}async predict(e){this.initialized||await this.initialize();let u=this.prepareState(e),a=this.qNetwork.forward(u),t=this.argmax(a),r=this.actions[t];return{action:r,confidence:.7,value:a[t],reasoning:`SARSA: ${r.type}`}}async trainCore(e){for(let t of e)this.replayBufferClass.add(t);if(!this.replayBufferClass.isReady(this.sarsaConfig.minReplaySize))return this.getStats();let u=this.replayBufferClass.sample(this.config.batchSize),a=0;for(let t=0;t<u.length;t++){let r=u[t],i=u[t+1],n=this.prepareState(r.state),o=this.actionToIndex(r.action),l=this.qNetwork.forward(n),c=l[o],E=0;if(i&&!r.done){let h=this.prepareState(i.state),C=this.actionToIndex(i.action);E=this.qNetwork.forward(h)[C]}let d=r.reward+this.config.discountFactor*E,D=new Float32Array(l.length);for(let h=0;h<D.length;h++)D[h]=h===o?d:l[h];a+=Math.abs(this.qNetwork.train(n,D,new xu))}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((t,r)=>t+r,0)/this.rewardHistory.length,loss:a/u.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural SARSA for Defect Prediction Sequencing",capabilities:["On-policy learning","Neural Q-network"],hyperparameters:{stateSize:this.sarsaConfig.stateSize,actionSize:this.sarsaConfig.actionSize,hiddenLayers:this.sarsaConfig.hiddenLayers.join(",")},stats:this.stats}}prepareState(e){let u=e.features.slice(0,this.sarsaConfig.stateSize);for(;u.length<this.sarsaConfig.stateSize;)u.push(0);let a=Math.max(...u.map(Math.abs));if(a>0)for(let t=0;t<u.length;t++)u[t]/=a;return new Float32Array(u)}initializeActions(){this.actions=[{type:"predict-high",value:1},{type:"predict-low",value:0},{type:"sequence-early",value:"high-risk"},{type:"sequence-late",value:"low-risk"}],this.sarsaConfig.actionSize=this.actions.length,this.qNetwork=new $({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate})}actionToIndex(e){let u=`${e.type}:${JSON.stringify(e.value)}`;for(let a=0;a<this.actions.length;a++)if(`${this.actions[a].type}:${JSON.stringify(this.actions[a].value)}`===u)return a;return 0}argmax(e){let u=0,a=e[0];for(let t=1;t<e.length;t++)e[t]>a&&(a=e[t],u=t);return u}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),sarsaConfig:this.sarsaConfig}}async importCustomData(e){e.qNetwork&&this.qNetwork.setParameters(e.qNetwork),e.sarsaConfig&&(this.sarsaConfig={...this.sarsaConfig,...e.sarsaConfig}),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new $({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.replayBufferClass.clear()}};Qu();J();var Pi={ContractVerified:"contract-testing.ContractVerified",BreakingChangeDetected:"contract-testing.BreakingChangeDetected",ContractPublished:"contract-testing.ContractPublished",ConsumerContractCreated:"contract-testing.ConsumerContractCreated",VerificationFailed:"contract-testing.VerificationFailed"},NCu={maxConcurrentWorkflows:5,defaultTimeout:6e4,enableAutoVerification:!0,publishEvents:!0,enableSARSA:!0,enableQESONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},tu=B.create("contract-testing"),zi=class extends Y{constructor(u,a,t,r={}){let i={...NCu,...r};super(u,"contract-testing",i,{verifyFindingTypes:["contract-violation","breaking-change","schema-incompatibility"]});this.memory=a;this.agentCoordinator=t;this.contractValidator=new K0({memory:a}),this.apiCompatibility=new j0(a),this.httpClient=ut(),this.fileReader=new ju}contractValidator;apiCompatibility;httpClient;fileReader;contractStore=new Map;sarsaAlgorithm;qesona;async onInitialize(){if(this.config.enableSARSA)try{this.sarsaAlgorithm=new Ri({stateSize:10,actionSize:4,hiddenLayers:[64,64]}),tu.info("SARSA algorithm created successfully")}catch(u){throw tu.error("Failed to create SARSA:",u instanceof Error?u:void 0),new Error(`SARSA creation failed: ${k(u)}`)}if(this.config.enableQESONA)try{this.qesona=await gu({domain:"contract-testing",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),tu.info("PersistentSONAEngine initialized successfully")}catch(u){tu.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),tu.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadContracts()}async onDispose(){await this.saveContracts(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.sarsaAlgorithm=void 0,this.contractStore.clear()}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async registerContract(u){try{let a=await this.contractValidator.validateContract(u);if(!a.success)return a;if(!a.value.isValid){let t=a.value.errors.map(r=>r.message).join("; ");return m(new Error(`Contract validation failed: ${t}`))}return this.contractStore.set(u.id,u),await this.memory.set(`contract-testing:contract:${u.id}`,u,{namespace:"contract-testing",persist:!0}),this.config.publishEvents&&await this.publishContractRegistered(u),p(u.id)}catch(a){return m(g(a))}}async verifyAllConsumers(u,a){let t=A();try{if(this.startWorkflow(t,"verify"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&tu.warn("Topology degraded, using conservative verification strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Contract verification paused: topology is in critical state"));let r=await this.findContractsByProvider(u);if(r.length===0)return this.completeWorkflow(t),p({provider:u,totalConsumers:0,passedConsumers:0,failedConsumers:[],results:[],canDeploy:!0});if(this.config.enableSARSA&&r.length>1){let E={urgency:5,providerLoad:50,consumerCount:r.reduce((D,h)=>D+h.consumers.length,0)},d=await this.prioritizeContracts(r,E);d.success&&(r=d.value.orderedContracts,tu.info(`[contract-testing] Using ${d.value.strategy} strategy for contract verification order (confidence: ${d.value.confidence.toFixed(2)})`))}let i=await this.spawnVerificationAgent(t,u);if(!i.success)return this.failWorkflow(t,i.error.message),i;this.addAgentToWorkflow(t,i.value);let n=[],o=[];for(let E of r){for(let d of E.consumers){let D=await this.verifyConsumerContract(E,d.name,a);n.push(D),D.passed?this.config.publishEvents&&await this.publishContractVerified(E,d.name,D):(o.push(d.name),this.config.publishEvents&&await this.publishVerificationFailed(E,d.name,D))}this.updateWorkflowProgress(t,n.length/r.length*100)}await this.agentCoordinator.stop(i.value),this.completeWorkflow(t);let l=Array.from(new Set(o)),c=r.flatMap(E=>E.consumers.map(d=>d.name)).filter(E=>!l.includes(E)).length;return p({provider:u,totalConsumers:r.reduce((E,d)=>E+d.consumers.length,0),passedConsumers:c,failedConsumers:l,results:n,canDeploy:l.length===0})}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async preReleaseCheck(u,a){let t=A();try{if(this.startWorkflow(t,"compare"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&tu.warn("Topology degraded, using conservative pre-release check"),this.minCutMixin.shouldPauseOperations())return m(new Error("Pre-release check paused: topology is in critical state"));let r=await this.loadContractFromPath(a);if(!r)return this.failWorkflow(t,"Failed to load contract from path"),m(new Error("Failed to load contract from path"));let i=await this.findContractsByProvider(u),n=i.length>0?i[0]:null;if(!n)return this.completeWorkflow(t),p({breakingChanges:[],affectedConsumers:[],canRelease:!0,recommendations:["No existing contract found. This will be the first version."]});let o=await this.apiCompatibility.compareVersions(n,r);if(!o.success)return this.failWorkflow(t,o.error.message),o;let{breakingChanges:l,deprecations:c}=o.value,E=[];for(let D of n.consumers){let h=l.filter(C=>C.affectedConsumers.includes(D.name));h.length>0&&E.push({name:D.name,team:D.team,breakingChanges:h,notified:!1})}let d=[];if(l.length>0){d.push(`${l.length} breaking changes detected. Coordinate with affected consumers before release.`);let D=await this.apiCompatibility.generateMigrationGuide(l);D.success&&d.push(`Migration effort estimated as: ${D.value.estimatedEffort}`)}return c.length>0&&d.push(`${c.length} deprecations detected. Consider communicating removal timeline.`),l.length===0&&c.length===0&&d.push("No breaking changes detected. Safe to release."),this.config.publishEvents&&l.length>0&&await this.publishBreakingChangeDetected(r.id,l,E.map(D=>D.name)),this.completeWorkflow(t),p({breakingChanges:l,affectedConsumers:E,canRelease:l.length===0,recommendations:d})}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async importFromOpenAPI(u){let a=A();try{this.startWorkflow(a,"import");let t=await this.loadFileContent(u);if(!t)return this.failWorkflow(a,"Failed to load OpenAPI spec"),m(new Error("Failed to load OpenAPI spec"));let r=await this.contractValidator.validateOpenAPI(t);if(!r.success)return this.failWorkflow(a,r.error.message),r;if(!r.value.isValid){let n=r.value.errors.map(o=>o.message).join("; ");return this.failWorkflow(a,n),m(new Error(`Invalid OpenAPI spec: ${n}`))}let i=this.parseOpenAPIToContract(t);return this.contractStore.set(i.id,i),await this.memory.set(`contract-testing:contract:${i.id}`,i,{namespace:"contract-testing",persist:!0}),this.completeWorkflow(a),p(i)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async exportToOpenAPI(u){let a=A();try{this.startWorkflow(a,"export");let t=this.contractStore.get(u);if(!t)return this.failWorkflow(a,"Contract not found"),m(new Error(`Contract not found: ${u}`));let r=this.contractToOpenAPI(t);return this.completeWorkflow(a),p(r)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async verifyConsumerContract(u,a,t){let r=[],i=[],n=t.startsWith("http://")||t.startsWith("https://");for(let o of u.endpoints){let l=`${t}${o.path}`,c=`${o.method} ${o.path}`;if(n)try{let E=await this.verifyEndpoint(l,o.method,o);E.success?E.warning&&i.push({endpoint:c,message:E.warning,severity:"low"}):r.push({endpoint:c,type:E.errorType,expected:E.expected,actual:E.actual,message:E.message})}catch(E){r.push({endpoint:c,type:"connection-error",expected:"reachable",actual:"error",message:`Failed to verify endpoint: ${k(E)}`})}else t||r.push({endpoint:c,type:"connection-error",expected:"reachable",actual:"unreachable",message:`Endpoint ${c} is not reachable (no provider URL)`})}return{contractId:u.id,provider:u.provider.name,consumer:a,passed:r.length===0,failures:r,warnings:i,timestamp:new Date}}async verifyEndpoint(u,a,t){let i={timeout:1e4,retries:1,circuitBreaker:!1},n;switch(a){case"GET":case"HEAD":n=await this.httpClient.get(u,i);break;case"POST":n=await this.httpClient.post(u,{},i);break;case"PUT":n=await this.httpClient.put(u,{},i);break;case"PATCH":n=await this.httpClient.patch(u,{},i);break;case"DELETE":n=await this.httpClient.delete(u,i);break;case"OPTIONS":n=await this.httpClient.get(u,i);break;default:n=await this.httpClient.get(u,i)}if(!n.success)return{success:!1,errorType:"connection-error",expected:"successful response",actual:`error: ${n.error.message}`,message:`Endpoint unreachable: ${n.error.message}`};let o=n.value;if(t.examples&&t.examples.length>0){let E=t.examples.map(d=>d.statusCode);if(!E.includes(o.status))return{success:!1,errorType:"status-mismatch",expected:E.join(" or "),actual:String(o.status),message:`Expected status ${E.join("/")} but got ${o.status}`}}let l,c=o.headers.get("Deprecation");return c&&(l=`Endpoint is deprecated: ${c}`),{success:!0,errorType:"",expected:"",actual:"",message:"Endpoint verified successfully",warning:l}}async findContractsByProvider(u){let a=[],t=Array.from(this.contractStore.values());for(let i of t)i.provider.name===u&&a.push(i);let r=await this.memory.search("contract-testing:contract:*",100);for(let i of r){let n=await this.memory.get(i);n&&n.provider.name===u&&(this.contractStore.has(n.id)||a.push(n))}return a}async loadContractFromPath(u){let a=await this.loadFileContent(u);if(!a)return null;try{let t=u.value.toLowerCase();if(t.endsWith(".json")){let r=T(a);return r.openapi||r.swagger?this.parseOpenAPIToContract(a):r}else if(t.endsWith(".yaml")||t.endsWith(".yml"))return tu.warn("YAML contract files not yet supported:"),null;return T(a)}catch(t){return tu.error(`Failed to parse contract from ${u.value}: ${k(t)}`),null}}async loadFileContent(u){let a=await this.fileReader.readFile(u.value);return a.success?a.value:(tu.error(`Failed to read file ${u.value}:`,a.error),null)}parseOpenAPIToContract(u){let a=T(u),t=a.info||{},r=a.paths||{},i=[],n=[];for(let[c,E]of Object.entries(r)){let d=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let D of d){let h=E[D.toLowerCase()];h&&i.push({path:c,method:D,requestSchema:this.extractRequestSchema(h),responseSchema:this.extractResponseSchema(h),headers:{},examples:[]})}}let l=(a.components||{}).schemas||{};for(let[c,E]of Object.entries(l))n.push({id:c,name:c,type:"openapi",content:JSON.stringify(E)});return{id:A(),name:t.title||"Imported Contract",version:Xe.parse(t.version||"1.0.0"),type:"rest",provider:{name:t.title||"Unknown Provider",version:t.version||"1.0.0"},consumers:[],endpoints:i,schemas:n}}extractRequestSchema(u){let a=u.requestBody;if(a){let t=a.content;if(t){let r=t["application/json"];if(r?.schema){let i=r.schema.$ref;if(i)return i.split("/").pop()}}}}extractResponseSchema(u){let a=u.responses;if(a){let t=a[200]||a[201];if(t){let r=t.content;if(r){let i=r["application/json"];if(i?.schema){let n=i.schema.$ref;if(n)return n.split("/").pop()}}}}}contractToOpenAPI(u){let a={};for(let i of u.endpoints){a[i.path]||(a[i.path]={});let n={summary:`${i.method} ${i.path}`,responses:{200:{description:"Success",content:i.responseSchema?{"application/json":{schema:{$ref:`#/components/schemas/${i.responseSchema}`}}}:void 0}}};i.requestSchema&&(n.requestBody={content:{"application/json":{schema:{$ref:`#/components/schemas/${i.requestSchema}`}}}}),a[i.path][i.method.toLowerCase()]=n}let t={};for(let i of u.schemas)try{t[i.id]=T(i.content)}catch{t[i.id]={type:"object"}}let r={openapi:"3.0.3",info:{title:u.name,version:u.version.toString()},paths:a,components:{schemas:t}};return JSON.stringify(r,null,2)}async spawnVerificationAgent(u,a){let t={name:`contract-verifier-${u.slice(0,8)}`,domain:"contract-testing",type:"validator",capabilities:["contract-verification","http-testing"],config:{workflowId:u,providerName:a}};return this.agentCoordinator.spawn(t)}async publishContractRegistered(u){let a=L(Pi.ContractPublished,"contract-testing",{contractId:u.id,version:u.version.toString(),provider:u.provider.name});await this.eventBus.publish(a)}async publishContractVerified(u,a,t){let r=L(Pi.ContractVerified,"contract-testing",{contractId:u.id,provider:u.provider.name,consumer:a,passed:t.passed,failureCount:t.failures.length});await this.eventBus.publish(r)}async publishVerificationFailed(u,a,t){let r=L(Pi.VerificationFailed,"contract-testing",{contractId:u.id,provider:u.provider.name,consumer:a,failures:t.failures.map(i=>({endpoint:i.endpoint,type:i.type,message:i.message}))});await this.eventBus.publish(r)}async publishBreakingChangeDetected(u,a,t){let r=L(Pi.BreakingChangeDetected,"contract-testing",{contractId:u,changes:a,affectedConsumers:t});await this.eventBus.publish(r)}async prioritizeContracts(u,a){if(!this.sarsaAlgorithm||!this.config.enableSARSA)return p({orderedContracts:u,strategy:"default",confidence:1});if(u.length===0)return p({orderedContracts:[],strategy:"empty",confidence:1});try{let t={id:`contract-priority-${Date.now()}`,features:[a.urgency/10,a.providerLoad/100,a.consumerCount/50,u.length/100,u.filter(c=>c.version.major>=2).length/Math.max(1,u.length),u.reduce((c,E)=>c+E.endpoints.length,0)/1e3,u.reduce((c,E)=>c+E.consumers.length,0)/100,u.filter(c=>c.type==="graphql").length/Math.max(1,u.length),u.filter(c=>c.type==="rest").length/Math.max(1,u.length),u.filter(c=>c.schemas.length>5).length/Math.max(1,u.length)]},r=await this.sarsaAlgorithm.predict(t),i=[...u],n="default";switch(r.action.type){case"sequence-early":i.sort((c,E)=>{let d=c.version.major*10+c.version.minor+c.endpoints.length*.1;return E.version.major*10+E.version.minor+E.endpoints.length*.1-d}),n="high-risk-first";break;case"sequence-late":i.sort((c,E)=>{let d=c.version.major*10+c.version.minor+c.endpoints.length*.1,D=E.version.major*10+E.version.minor+E.endpoints.length*.1;return d-D}),n="low-risk-first";break;case"predict-high":i.sort((c,E)=>E.consumers.length-c.consumers.length),n="high-consumer-first";break;default:n="default";break}let o=await this.calculateOrderingReward(i,a),l=r.action;return await this.sarsaAlgorithm.train({state:t,action:l,reward:o,nextState:t,done:!0}),tu.info(`[contract-testing] SARSA prioritized ${u.length} contracts using ${n} strategy (confidence: ${r.confidence.toFixed(2)})`),p({orderedContracts:i,strategy:n,confidence:r.confidence})}catch(t){return tu.error("SARSA prioritization failed:",t instanceof Error?t:void 0),p({orderedContracts:u,strategy:"fallback",confidence:.5})}}async calculateOrderingReward(u,a){let t=.5,r=u.slice(0,Math.ceil(u.length/3)),i=r.reduce((n,o)=>n+o.consumers.length,0)/r.length;if(t+=Math.min(.3,i/50),a.urgency>7){let n=r.filter(o=>o.version.major===0).length;t+=Math.min(.2,n/r.length)}return a.providerLoad>80&&(t-=.1),Math.max(0,Math.min(1,t))}async storeContractPattern(u,a,t){if(!(!this.qesona||!this.config.enableQESONA))try{let r={id:`contract-${u.id}`,features:[u.version.major/10,u.version.minor/10,u.endpoints.length/100,u.consumers.length/50,u.schemas.length/50,u.type==="rest"?1:0,u.type==="graphql"?1:0,u.endpoints.filter(n=>n.method==="GET").length/100,u.endpoints.filter(n=>n.method==="POST").length/100,u.endpoints.filter(n=>n.responseSchema).length/100]};if(Me()&&this.qesona.isThreeLoopEnabled()){this.qesona.instantAdapt([u.endpoints.length/100,u.consumers.length/50,u.schemas.length/50,t,a?1:0,u.version.major/10]);try{if(this.qesona.recordOutcome(a?t:-t),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}let i={type:a?"validate":"reject",value:t};this.qesona.createPattern(r,i,{reward:a?t:-t,success:a,quality:t},"test-generation","contract-testing",{contractId:u.id,provider:u.provider.name,version:u.version.toString()}),tu.info(`Stored pattern for contract ${u.id} (success: ${a}, quality: ${t.toFixed(2)})`)}catch(r){tu.error("Failed to store contract pattern:",r instanceof Error?r:void 0)}}async adaptContractPatterns(u){if(!this.qesona||!this.config.enableQESONA)return{shouldValidate:!0,confidence:.5,strategy:"default"};try{let a={id:`contract-${u.id}`,features:[u.version.major/10,u.version.minor/10,u.endpoints.length/100,u.consumers.length/50,u.schemas.length/50,u.type==="rest"?1:0,u.type==="graphql"?1:0,u.endpoints.filter(r=>r.method==="GET").length/100,u.endpoints.filter(r=>r.method==="POST").length/100,u.endpoints.filter(r=>r.responseSchema).length/100]},t=await this.qesona.adaptPattern(a,"test-generation","contract-testing");if(t.success&&t.pattern){let r=t.pattern.outcome.success,i=t.pattern.action.type;return tu.info(`[contract-testing] QESONA adapted pattern for ${u.id}: shouldValidate=${r}, confidence=${t.similarity.toFixed(2)}`),{shouldValidate:r,confidence:t.similarity,strategy:i}}return{shouldValidate:!0,confidence:.5,strategy:"default"}}catch(a){return tu.error("QESONA pattern adaptation failed:",a instanceof Error?a:void 0),{shouldValidate:!0,confidence:.5,strategy:"default"}}}async handleImpactAnalysis(u){let t=u.payload.changedFiles.filter(r=>r.includes("contract")||r.includes("api")||r.includes("openapi"));t.length>0&&this.config.enableAutoVerification&&await this.memory.set(`contract-testing:pending-verification:${Date.now()}`,{changedFiles:t,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:3600})}async loadContracts(){let u=await this.memory.search("contract-testing:contract:*",100);for(let a of u){let t=await this.memory.get(a);t&&this.contractStore.set(t.id,t)}}async saveContracts(){let u=Array.from(this.contractStore.entries());for(let[a,t]of u)await this.memory.set(`contract-testing:contract:${a}`,t,{namespace:"contract-testing",persist:!0})}async verifyContractViolation(u,a){let t=O({id:A(),type:"contract-violation",confidence:a,description:`Verify contract violation: ${u.consumer} -> ${u.provider} (${u.endpoint}, ${u.type})`,payload:u,detectedBy:"contract-testing-coordinator",severity:a>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(tu.info("Contract violation verified by consensus"),!0):(tu.warn(`Contract violation NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async verifyBreakingChange(u,a){let t=O({id:A(),type:"breaking-change",confidence:a,description:`Verify breaking change: ${u.path} (${u.type}) affecting ${u.affectedConsumers.length} consumers`,payload:u,detectedBy:"contract-testing-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(tu.info(`Breaking change at '${u.path}' verified by consensus`),!0):(tu.warn(`Breaking change NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async verifySchemaIncompatibility(u,a){let t=O({id:A(),type:"schema-incompatibility",confidence:a,description:`Verify schema incompatibility: ${u.schema}.${u.field} (expected ${u.expected}, got ${u.actual})`,payload:u,detectedBy:"contract-testing-coordinator",severity:a>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(tu.info("Schema incompatibility verified by consensus"),!0):(tu.warn(`Schema incompatibility NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}};S();S();J();var ICu={strictMode:!1,allowAdditionalProperties:!0,maxRecursionDepth:10,inferenceMinSamples:3},Li=class{constructor(e,u={}){this.memory=e;this.config={...ICu,...u}}config;async validateJsonSchema(e,u){try{let a=[];this.validateValue(e,u,"",a,0);let t={isValid:a.length===0,errors:a};return p(t)}catch(a){return m(g(a))}}async validateGraphQLSchema(e){try{let u=[],a=0,t=0,r=0,i=e.split(`
2947
- `),n=!1,o=!1,l=!1,c=0;for(let E=0;E<i.length;E++){let d=i[E].trim();if(!(d.startsWith("#")||d==="")){if(d.startsWith("type ")){let D=d.split(/\s+/)[1]?.replace(/{.*/,"").trim();D==="Query"?o=!0:D==="Mutation"?l=!0:a++,n=!0}c+=(d.match(/{/g)||[]).length,c-=(d.match(/}/g)||[]).length,o&&d.includes(":")&&!d.startsWith("type")&&t++,l&&d.includes(":")&&!d.startsWith("type")&&r++,c===0&&n&&(n=!1,o=!1,l=!1),d.includes("::")&&u.push({message:"Invalid double colon in type definition",locations:[{line:E+1,column:d.indexOf("::")+1}]})}}return c!==0&&u.push({message:"Unbalanced braces in schema",locations:[{line:i.length,column:1}]}),!e.includes("type Query")&&!e.includes("schema {")&&u.push({message:"GraphQL schema must have a Query type or schema definition",locations:[{line:1,column:1}]}),p({isValid:u.length===0,errors:u,typeCount:a,queryCount:t,mutationCount:r})}catch(u){return m(g(u))}}async compareSchemas(e,u){try{let a=[],t=[],r=[];if(e.type!==u.type)return p({isCompatible:!1,additions:[],removals:[],modifications:[{path:"type",oldType:e.type,newType:u.type,isBreaking:!0}]});switch(e.type){case"json-schema":case"openapi":this.compareJsonSchemas(e.content,u.content,a,t,r);break;case"graphql":this.compareGraphQLSchemas(e.content,u.content,a,t,r);break;case"protobuf":this.compareProtobufSchemas(e.content,u.content,a,t,r);break;case"avro":this.compareAvroSchemas(e.content,u.content,a,t,r);break}let i=r.some(n=>n.isBreaking)||t.length>0;return await this.storeComparisonResult(e,u,{isCompatible:!i,additions:a,removals:t,modifications:r}),p({isCompatible:!i,additions:a,removals:t,modifications:r})}catch(a){return m(g(a))}}async inferSchema(e){try{if(e.length===0)return m(new Error("At least one sample is required for schema inference"));e.length<this.config.inferenceMinSamples;let u=this.inferFromSamples(e),a={id:`inferred-${A().slice(0,8)}`,name:"InferredSchema",type:"json-schema",content:JSON.stringify(u,null,2)};return await this.memory.set(`contract-testing:schema:${a.id}`,a,{namespace:"contract-testing"}),p(a)}catch(u){return m(g(u))}}validateValue(e,u,a,t,r){if(r>this.config.maxRecursionDepth){t.push({path:a,keyword:"maxDepth",message:"Maximum recursion depth exceeded",params:{maxDepth:this.config.maxRecursionDepth}});return}if(e===null){if(u.nullable===!0||u.type==="null")return;this.config.strictMode&&t.push({path:a,keyword:"type",message:"Value cannot be null",params:{}});return}let i=u.type;if(u.oneOf){this.validateOneOf(e,u.oneOf,a,t,r);return}if(u.anyOf){this.validateAnyOf(e,u.anyOf,a,t,r);return}if(u.allOf){this.validateAllOf(e,u.allOf,a,t,r);return}if(i){let n=Array.isArray(i)?i:[i],o=this.getJsonType(e);if(!n.some(l=>this.typesMatch(o,l))){t.push({path:a,keyword:"type",message:`Expected type '${n.join(" | ")}' but got '${o}'`,params:{expectedType:n,actualType:o}});return}}if(typeof e=="object"&&e!==null&&!Array.isArray(e)?this.validateObject(e,u,a,t,r):Array.isArray(e)?this.validateArray(e,u,a,t,r):typeof e=="string"?this.validateString(e,u,a,t):typeof e=="number"&&this.validateNumber(e,u,a,t),u.enum){let n=u.enum;n.includes(e)||t.push({path:a,keyword:"enum",message:`Value must be one of: ${n.map(o=>JSON.stringify(o)).join(", ")}`,params:{allowedValues:n}})}"const"in u&&e!==u.const&&t.push({path:a,keyword:"const",message:`Value must be ${JSON.stringify(u.const)}`,params:{expected:u.const}})}validateObject(e,u,a,t,r){let i=u.properties||{},n=u.required||[],o=u.additionalProperties;for(let c of n)c in e||t.push({path:a?`${a}.${c}`:c,keyword:"required",message:`Required property '${c}' is missing`,params:{missingProperty:c}});for(let[c,E]of Object.entries(e)){let d=a?`${a}.${c}`:c;c in i?this.validateValue(E,i[c],d,t,r+1):this.config.strictMode&&o===!1?t.push({path:d,keyword:"additionalProperties",message:`Property '${c}' is not allowed`,params:{additionalProperty:c}}):typeof o=="object"&&this.validateValue(E,o,d,t,r+1)}let l=Object.keys(e).length;typeof u.minProperties=="number"&&l<u.minProperties&&t.push({path:a,keyword:"minProperties",message:`Object must have at least ${u.minProperties} properties`,params:{limit:u.minProperties,actual:l}}),typeof u.maxProperties=="number"&&l>u.maxProperties&&t.push({path:a,keyword:"maxProperties",message:`Object must have at most ${u.maxProperties} properties`,params:{limit:u.maxProperties,actual:l}})}validateArray(e,u,a,t,r){let i=u.items;if(i)for(let n=0;n<e.length;n++)this.validateValue(e[n],i,`${a}[${n}]`,t,r+1);if(typeof u.minItems=="number"&&e.length<u.minItems&&t.push({path:a,keyword:"minItems",message:`Array must have at least ${u.minItems} items`,params:{limit:u.minItems,actual:e.length}}),typeof u.maxItems=="number"&&e.length>u.maxItems&&t.push({path:a,keyword:"maxItems",message:`Array must have at most ${u.maxItems} items`,params:{limit:u.maxItems,actual:e.length}}),u.uniqueItems===!0){let n=new Set;for(let o=0;o<e.length;o++){let l=JSON.stringify(e[o]);n.has(l)&&t.push({path:`${a}[${o}]`,keyword:"uniqueItems",message:"Array items must be unique",params:{duplicateIndex:o}}),n.add(l)}}}validateString(e,u,a,t){if(typeof u.minLength=="number"&&e.length<u.minLength&&t.push({path:a,keyword:"minLength",message:`String must be at least ${u.minLength} characters`,params:{limit:u.minLength,actual:e.length}}),typeof u.maxLength=="number"&&e.length>u.maxLength&&t.push({path:a,keyword:"maxLength",message:`String must be at most ${u.maxLength} characters`,params:{limit:u.maxLength,actual:e.length}}),typeof u.pattern=="string"){let r=Y0(u.pattern);r&&!r.test(e)&&t.push({path:a,keyword:"pattern",message:`String must match pattern '${u.pattern}'`,params:{pattern:u.pattern}})}typeof u.format=="string"&&this.validateFormat(e,u.format,a,t)}validateNumber(e,u,a,t){if(typeof u.minimum=="number"&&(u.exclusiveMinimum===!0?e<=u.minimum&&t.push({path:a,keyword:"exclusiveMinimum",message:`Number must be greater than ${u.minimum}`,params:{limit:u.minimum,actual:e}}):e<u.minimum&&t.push({path:a,keyword:"minimum",message:`Number must be at least ${u.minimum}`,params:{limit:u.minimum,actual:e}})),typeof u.maximum=="number"&&(u.exclusiveMaximum===!0?e>=u.maximum&&t.push({path:a,keyword:"exclusiveMaximum",message:`Number must be less than ${u.maximum}`,params:{limit:u.maximum,actual:e}}):e>u.maximum&&t.push({path:a,keyword:"maximum",message:`Number must be at most ${u.maximum}`,params:{limit:u.maximum,actual:e}})),typeof u.multipleOf=="number"){let r=e%u.multipleOf;Math.abs(r)>1e-10&&t.push({path:a,keyword:"multipleOf",message:`Number must be a multiple of ${u.multipleOf}`,params:{multipleOf:u.multipleOf,actual:e}})}}validateFormat(e,u,a,t){let r=!0;switch(u){case"email":r=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);break;case"uri":case"url":try{new URL(e)}catch{r=!1}break;case"uuid":r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e);break;case"date":r=!isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}$/.test(e);break;case"date-time":r=!isNaN(Date.parse(e));break;case"time":r=/^\d{2}:\d{2}(:\d{2})?/.test(e);break;case"ipv4":r=/^(\d{1,3}\.){3}\d{1,3}$/.test(e);break;case"ipv6":r=/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/.test(e);break;default:return}r||t.push({path:a,keyword:"format",message:`String must be a valid ${u}`,params:{format:u}})}validateOneOf(e,u,a,t,r){let i=u.reduce((n,o)=>{let l=[];return this.validateValue(e,o,a,l,r+1),n+(l.length===0?1:0)},0);i!==1&&t.push({path:a,keyword:"oneOf",message:`Value must match exactly one schema (matched ${i})`,params:{matched:i}})}validateAnyOf(e,u,a,t,r){u.some(n=>{let o=[];return this.validateValue(e,n,a,o,r+1),o.length===0})||t.push({path:a,keyword:"anyOf",message:"Value must match at least one schema",params:{}})}validateAllOf(e,u,a,t,r){for(let i of u)this.validateValue(e,i,a,t,r+1)}getJsonType(e){return e===null?"null":Array.isArray(e)?"array":typeof e=="number"?Number.isInteger(e)?"integer":"number":typeof e}typesMatch(e,u){return e===u||u==="number"&&e==="integer"}compareJsonSchemas(e,u,a,t,r){try{let i=T(e),n=T(u);this.compareSchemaObjects(i,n,"",a,t,r)}catch{r.push({path:"",oldType:"unparseable",newType:"unparseable",isBreaking:!0})}}compareSchemaObjects(e,u,a,t,r,i){let n=e.properties||{},o=u.properties||{},l=new Set(e.required||[]),c=new Set(u.required||[]);for(let d of Object.keys(n))if(!(d in o)){let D=a?`${a}.${d}`:d;r.push(D)}for(let d of Object.keys(o))if(!(d in n)){let D=a?`${a}.${d}`:d;t.push(D),c.has(d)&&i.push({path:D,oldType:"undefined",newType:"required",isBreaking:!0})}e.type!==u.type&&i.push({path:a||"root",oldType:String(e.type||"any"),newType:String(u.type||"any"),isBreaking:!0});let E=Array.from(c);for(let d of E)if(!l.has(d)&&d in n){let D=a?`${a}.${d}`:d;i.push({path:D,oldType:"optional",newType:"required",isBreaking:!0})}}compareGraphQLSchemas(e,u,a,t,r){let i=this.extractGraphQLTypes(e),n=this.extractGraphQLTypes(u);for(let o of i)n.includes(o)||t.push(`type:${o}`);for(let o of n)i.includes(o)||a.push(`type:${o}`)}extractGraphQLTypes(e){let u=[],a=/type\s+(\w+)/g,t;for(;(t=a.exec(e))!==null;)u.push(t[1]);return u}compareProtobufSchemas(e,u,a,t,r){let i=this.extractProtobufMessages(e),n=this.extractProtobufMessages(u);for(let o of i)n.includes(o)||t.push(`message:${o}`);for(let o of n)i.includes(o)||a.push(`message:${o}`)}extractProtobufMessages(e){let u=[],a=/message\s+(\w+)/g,t;for(;(t=a.exec(e))!==null;)u.push(t[1]);return u}compareAvroSchemas(e,u,a,t,r){try{let i=T(e),n=T(u);i.type!==n.type&&r.push({path:"type",oldType:String(i.type),newType:String(n.type),isBreaking:!0}),i.name!==n.name&&r.push({path:"name",oldType:String(i.name),newType:String(n.name),isBreaking:!0})}catch{r.push({path:"",oldType:"unparseable",newType:"unparseable",isBreaking:!0})}}inferFromSamples(e){if(e.length===0)return{type:"null"};let u=e.map(a=>this.inferType(a));return this.mergeTypes(u)}inferType(e){if(e===null)return{type:"null"};if(Array.isArray(e)){if(e.length===0)return{type:"array",items:{}};let u=e.map(a=>this.inferType(a));return{type:"array",items:this.mergeTypes(u)}}if(typeof e=="object"){let u={},a=[];for(let[t,r]of Object.entries(e))u[t]=this.inferType(r),r!==void 0&&a.push(t);return{type:"object",properties:u,required:a}}if(typeof e=="string"){let u=this.inferStringFormat(e);return u?{type:"string",format:u}:{type:"string"}}return typeof e=="number"?Number.isInteger(e)?{type:"integer"}:{type:"number"}:typeof e=="boolean"?{type:"boolean"}:{}}inferStringFormat(e){if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return"email";if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))return"uuid";if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return"date-time";if(/^\d{4}-\d{2}-\d{2}$/.test(e))return"date";try{return new URL(e),"uri"}catch{return null}}mergeTypes(e){if(e.length===0)return{};if(e.length===1)return e[0];if(new Set(e.map(a=>a.type)).size===1){let a=e[0].type;if(a==="object"){let t=new Map,r=new Set;for(let c of e){let E=c.properties||{},d=c.required||[];for(let[D,h]of Object.entries(E))t.has(D)||t.set(D,[]),t.get(D).push(h);for(let D of d)r.add(D)}let i={},n=Array.from(t.entries());for(let[c,E]of n)i[c]=this.mergeTypes(E);let l=Array.from(r).filter(c=>e.every(E=>(E.required||[]).includes(c)));return{type:"object",properties:i,required:l}}if(a==="array"){let t=e.map(r=>r.items).filter(r=>r&&Object.keys(r).length>0);return{type:"array",items:t.length>0?this.mergeTypes(t):{}}}return e[0]}return{anyOf:e}}async storeComparisonResult(e,u,a){let t=`contract-testing:schema-comparison:${e.id}:${u.id}:${Date.now()}`;await this.memory.set(t,{oldSchemaId:e.id,newSchemaId:u.id,isCompatible:a.isCompatible,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400*30})}};var Hl=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}coordinator=null;contractValidator=null;apiCompatibility=null;schemaValidator=null;pluginConfig;get name(){return"contract-testing"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{registerContract:this.registerContract.bind(this),verifyAllConsumers:this.verifyAllConsumers.bind(this),preReleaseCheck:this.preReleaseCheck.bind(this),importFromOpenAPI:this.importFromOpenAPI.bind(this),exportToOpenAPI:this.exportToOpenAPI.bind(this),validateContract:this.validateContract.bind(this),validateRequest:this.validateRequest.bind(this),validateResponse:this.validateResponse.bind(this),validateOpenAPI:this.validateOpenAPI.bind(this),compareVersions:this.compareVersions.bind(this),isBackwardCompatible:this.isBackwardCompatible.bind(this),checkCompatibility:this.isBackwardCompatible.bind(this),getBreakingChanges:this.getBreakingChanges.bind(this),generateMigrationGuide:this.generateMigrationGuide.bind(this),validateJsonSchema:this.validateJsonSchema.bind(this),validateGraphQLSchema:this.validateGraphQLSchema.bind(this),compareSchemas:this.compareSchemas.bind(this),inferSchema:this.inferSchema.bind(this),generateContract:this.inferSchema.bind(this),getCoordinator:()=>this.coordinator,getContractValidator:()=>this.contractValidator,getApiCompatibility:()=>this.apiCompatibility,getSchemaValidator:()=>this.schemaValidator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["validate-contract",async u=>{if(!this.contractValidator)return m(new Error("Contract validator not initialized"));let a=u.contract;return a?this.contractValidator.validateContract(a):m(new Error("Invalid validate-contract payload: missing contract"))}],["compare-versions",async u=>{if(!this.apiCompatibility)return m(new Error("API compatibility service not initialized"));let a=u.oldVersion,t=u.newVersion,r=u.oldContract,i=u.newContract;if(r&&i)return this.apiCompatibility.compareVersions(r,i);if(!a||!t)return m(new Error("Invalid compare-versions payload: missing oldVersion or newVersion"));try{let n=Xe.parse(a),o=Xe.parse(t),l=o.isNewerThan(n)?1:o.equals(n)?0:-1;return{success:!0,value:{oldVersion:a,newVersion:t,comparison:l}}}catch(n){return m(g(n))}}],["check-compatibility",async u=>{if(!this.apiCompatibility)return m(new Error("API compatibility service not initialized"));let a=u.provider,t=u.consumer,r=u.contract,i=u.baselineContract;return r&&i?this.apiCompatibility.isBackwardCompatible(i,r):!a||!t?m(new Error("Invalid check-compatibility payload: missing provider or consumer")):{success:!0,value:{provider:a,consumer:t,compatible:!0}}}],["generate-contract",async u=>{if(!this.schemaValidator)return m(new Error("Schema validator not initialized"));let a=u.serviceSpec,t=u.samples;return t&&t.length>0?this.schemaValidator.inferSchema(t):a?this.schemaValidator.inferSchema([a]):m(new Error("Invalid generate-contract payload: missing serviceSpec"))}]])}async onInitialize(){this.contractValidator=new K0({memory:this.memory},this.pluginConfig.contractValidator),this.apiCompatibility=new j0(this.memory,this.pluginConfig.apiCompatibility),this.schemaValidator=new Li(this.memory,this.pluginConfig.schemaValidator),this.coordinator=new zi(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.contractValidator=null,this.apiCompatibility=null,this.schemaValidator=null}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("release.PreReleaseStarted",this.handlePreRelease.bind(this))}async onEvent(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(u);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(u);break;default:break}}async registerContract(u){this.ensureInitialized();try{let a=await this.coordinator.registerContract(u);return a.success?this.trackSuccessfulOperation("register"):this.trackFailedOperation(new Error(a.error.message)),a}catch(a){return this.handleError(a)}}async verifyAllConsumers(u,a){this.ensureInitialized();try{let t=await this.coordinator.verifyAllConsumers(u,a);return t.success?this.trackSuccessfulOperation("verify"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async preReleaseCheck(u,a){this.ensureInitialized();try{return await this.coordinator.preReleaseCheck(u,a)}catch(t){return this.handleError(t)}}async importFromOpenAPI(u){this.ensureInitialized();try{return await this.coordinator.importFromOpenAPI(u)}catch(a){return this.handleError(a)}}async exportToOpenAPI(u){this.ensureInitialized();try{return await this.coordinator.exportToOpenAPI(u)}catch(a){return this.handleError(a)}}async validateContract(u){this.ensureInitialized();try{return await this.contractValidator.validateContract(u)}catch(a){return this.handleError(a)}}async validateRequest(u,a){this.ensureInitialized();try{return await this.contractValidator.validateRequest(u,a)}catch(t){return this.handleError(t)}}async validateResponse(u,a){this.ensureInitialized();try{return await this.contractValidator.validateResponse(u,a)}catch(t){return this.handleError(t)}}async validateOpenAPI(u){this.ensureInitialized();try{return await this.contractValidator.validateOpenAPI(u)}catch(a){return this.handleError(a)}}async compareVersions(u,a){this.ensureInitialized();try{return await this.apiCompatibility.compareVersions(u,a)}catch(t){return this.handleError(t)}}async isBackwardCompatible(u,a){this.ensureInitialized();try{return await this.apiCompatibility.isBackwardCompatible(u,a)}catch(t){return this.handleError(t)}}async getBreakingChanges(u,a){this.ensureInitialized();try{return await this.apiCompatibility.getBreakingChanges(u,a)}catch(t){return this.handleError(t)}}async generateMigrationGuide(u){this.ensureInitialized();try{return await this.apiCompatibility.generateMigrationGuide(u)}catch(a){return this.handleError(a)}}async validateJsonSchema(u,a){this.ensureInitialized();try{return await this.schemaValidator.validateJsonSchema(u,a)}catch(t){return this.handleError(t)}}async validateGraphQLSchema(u){this.ensureInitialized();try{return await this.schemaValidator.validateGraphQLSchema(u)}catch(a){return this.handleError(a)}}async compareSchemas(u,a){this.ensureInitialized();try{return await this.schemaValidator.compareSchemas(u,a)}catch(t){return this.handleError(t)}}async inferSchema(u){this.ensureInitialized();try{return await this.schemaValidator.inferSchema(u)}catch(a){return this.handleError(a)}}async handleImpactAnalysis(u){let a=u.payload;a.changedFiles.filter(r=>r.includes("/api/")||r.includes("/routes/")||r.includes("controller")).length>0&&await this.memory.set(`contract-testing:pending-impact:${a.analysisId}`,a,{namespace:"contract-testing",ttl:3600})}async handleQualityGate(u){let a=u.payload;a.checks.find(r=>r.name==="contract-testing")||await this.memory.set(`contract-testing:quality-gate-warning:${a.gateId}`,{warning:"Contract testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}async handlePreRelease(u){let a=u.payload,t=a.providerName||a.serviceName;if(!t){await this.memory.set(`contract-testing:pre-release-warning:${u.id}`,{warning:"Pre-release event received without provider/service name",eventId:u.id,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400});return}let r=`contract-testing:pre-release:${u.id}`;if(await this.memory.set(r,{providerName:t,version:a.version,status:"pending",startedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:3600}),a.contractPath)try{let i=yu.create(a.contractPath),n=await this.preReleaseCheck(t,i);if(n.success){let o=n.value;await this.memory.set(r,{providerName:t,version:a.version,status:o.canRelease?"passed":"failed",completedAt:new Date().toISOString(),breakingChanges:o.breakingChanges.length,affectedConsumers:o.affectedConsumers.length,recommendations:o.recommendations},{namespace:"contract-testing",ttl:86400}),this.eventBus.publish({id:`${u.id}-result`,type:"contract-testing.PreReleaseVerificationCompleted",source:"contract-testing",timestamp:new Date,payload:{providerName:t,version:a.version,canRelease:o.canRelease,breakingChanges:o.breakingChanges.length,affectedConsumers:o.affectedConsumers.map(l=>l.name)}})}}catch(i){await this.memory.set(r,{providerName:t,version:a.version,status:"error",error:k(i),completedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}if(a.providerUrl)try{let i=await this.verifyAllConsumers(t,a.providerUrl);if(i.success){let n=i.value;await this.memory.set(`${r}:verification`,{providerName:t,version:a.version,status:n.canDeploy?"passed":"failed",completedAt:new Date().toISOString(),totalConsumers:n.totalConsumers,passedConsumers:n.passedConsumers,failedConsumers:n.failedConsumers},{namespace:"contract-testing",ttl:86400}),this.eventBus.publish({id:`${u.id}-consumer-result`,type:"contract-testing.ConsumerVerificationCompleted",source:"contract-testing",timestamp:new Date,payload:{providerName:t,version:a.version,canDeploy:n.canDeploy,totalConsumers:n.totalConsumers,passedConsumers:n.passedConsumers,failedConsumers:n.failedConsumers}})}}catch(i){await this.memory.set(`${r}:verification`,{providerName:t,version:a.version,status:"error",error:k(i),completedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}}ensureInitialized(){if(!this._initialized)throw new Error("ContractTestingPlugin is not initialized");if(!this.coordinator||!this.contractValidator||!this.apiCompatibility||!this.schemaValidator)throw new Error("ContractTestingPlugin services are not available")}handleError(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}};function bE(s,e,u,a){return new Hl(s,e,u,a)}N();S();ct();N();S();var KCu={baselineDirectory:".visual-tests/baselines",diffDirectory:".visual-tests/diffs",defaultViewport:{width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},diffThreshold:.1,antialiasDetection:!0,captureTimeout:3e4,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},BE=B.create("visual-accessibility/visual-tester"),Gl=class{config;memory;llmRouter;vibiumClient=null;browserAvailable=null;constructor(e,u={}){this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...KCu,...u}}setVibiumClient(e){this.vibiumClient=e,this.browserAvailable=null}getVibiumClient(){return this.vibiumClient}async isBrowserAvailable(){if(this.browserAvailable!==null)return this.browserAvailable;if(!this.vibiumClient)return this.browserAvailable=!1,!1;try{return this.browserAvailable=await this.vibiumClient.isAvailable(),this.browserAvailable}catch{return this.browserAvailable=!1,!1}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(e){let u={1:"claude-3-haiku-20240307",2:"claude-sonnet-4-20250514",3:"claude-sonnet-4-20250514",4:"claude-opus-4-20250514"};return u[e]||u[2]}async captureScreenshot(e,u){try{let a=u?.viewport||this.config.defaultViewport,t=A(),r=new Date,i=this.hashUrl(e),n=`${a.width}x${a.height}`,o=yu.create(`${this.config.baselineDirectory}/${i}_${n}_${t}.png`),l=this.estimateLoadTime(e,a),c={browser:"chromium",os:process.platform,selector:void 0,fullPage:u?.fullPage??!1,loadTime:l},E={id:t,url:e,viewport:a,timestamp:r,path:o,metadata:c};return await this.storeScreenshotMetadata(E),p(E)}catch(a){return m(g(a))}}async captureElement(e,u,a){try{let t=a?.viewport||this.config.defaultViewport,r=A(),i=new Date,n=yu.create(`${this.config.baselineDirectory}/${r}.png`),o={browser:"chromium",os:process.platform,selector:u,fullPage:!1,loadTime:this.estimateLoadTime(e,t)},l={id:r,url:e,viewport:t,timestamp:i,path:n,metadata:o};return await this.storeScreenshotMetadata(l),p(l)}catch(t){return m(g(t))}}async compare(e,u){try{let a=await this.getScreenshotById(u);if(!a)return m(new Error(`Baseline not found: ${u}`));let t=this.calculateDiff(a,e);return await this.storeDiffResult(t),p(t)}catch(a){return m(g(a))}}async compareWithBrowser(e,u,a){try{let t=await this.getScreenshotById(u);if(!t)return m(new Error(`Baseline not found: ${u}`));let r=a??this.config.diffThreshold;if(this.vibiumClient&&await this.isBrowserAvailable()){let n=await this.executeBrowserComparison(t,e,r);if(n.success)return await this.storeDiffResult(n.value),n;BE.warn(`Browser comparison failed, falling back to deterministic: ${n.error.message}`)}let i=this.calculateDiff(t,e);return await this.storeDiffResult(i),p(i)}catch(t){return m(g(t))}}async executeBrowserComparison(e,u,a){if(!this.vibiumClient)return m(new Error("Vibium client not available"));try{let t=await this.vibiumClient.compareScreenshots(e.path.value,u.path.value,a/100);if(!t.success)return m(t.error);let r=t.value,i=this.convertVibiumResult(e,u,r,a);return p(i)}catch(t){return m(g(t))}}convertVibiumResult(e,u,a,t){let r=a.differencePercent,i;r===0?i="identical":r<=t?i="acceptable":r<=5?i="changed":i="failed";let n=e.viewport.width*e.viewport.height,o=Math.floor(n*r/100),l=a.diffRegions.map((E,d)=>({x:E.x,y:E.y,width:E.width,height:E.height,changeType:"modified",significance:r>2?"high":r>.5?"medium":"low"})),c=a.diffImagePath?yu.create(a.diffImagePath):r>t?yu.create(`${this.config.diffDirectory}/${u.id}_diff.png`):void 0;return{baselineId:e.id,comparisonId:u.id,diffPercentage:r,diffPixels:o,diffImagePath:c,regions:l,status:i}}async setBaseline(e){try{let u=this.getBaselineKey(e.url,e.viewport);return await this.memory.set(`visual-accessibility:baseline:${u}`,e,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:screenshot:${e.id}`,e,{namespace:"visual-accessibility",persist:!0}),p(u)}catch(u){return m(g(u))}}async getBaseline(e,u){let a=this.getBaselineKey(e,u);return await this.memory.get(`visual-accessibility:baseline:${a}`)??null}async analyzeDiffWithLLM(e){if(!this.isLLMAnalysisAvailable())return null;try{let u=e.regions.slice(0,5).map(t=>{let r=t.width*t.height;return`- Region at (${t.x}, ${t.y}): ${t.width}x${t.height}, ${r} pixels changed, ${t.changeType} (${t.significance} significance)`}).join(`
2947
+ `),n=!1,o=!1,l=!1,c=0;for(let E=0;E<i.length;E++){let d=i[E].trim();if(!(d.startsWith("#")||d==="")){if(d.startsWith("type ")){let D=d.split(/\s+/)[1]?.replace(/{.*/,"").trim();D==="Query"?o=!0:D==="Mutation"?l=!0:a++,n=!0}c+=(d.match(/{/g)||[]).length,c-=(d.match(/}/g)||[]).length,o&&d.includes(":")&&!d.startsWith("type")&&t++,l&&d.includes(":")&&!d.startsWith("type")&&r++,c===0&&n&&(n=!1,o=!1,l=!1),d.includes("::")&&u.push({message:"Invalid double colon in type definition",locations:[{line:E+1,column:d.indexOf("::")+1}]})}}return c!==0&&u.push({message:"Unbalanced braces in schema",locations:[{line:i.length,column:1}]}),!e.includes("type Query")&&!e.includes("schema {")&&u.push({message:"GraphQL schema must have a Query type or schema definition",locations:[{line:1,column:1}]}),p({isValid:u.length===0,errors:u,typeCount:a,queryCount:t,mutationCount:r})}catch(u){return m(g(u))}}async compareSchemas(e,u){try{let a=[],t=[],r=[];if(e.type!==u.type)return p({isCompatible:!1,additions:[],removals:[],modifications:[{path:"type",oldType:e.type,newType:u.type,isBreaking:!0}]});switch(e.type){case"json-schema":case"openapi":this.compareJsonSchemas(e.content,u.content,a,t,r);break;case"graphql":this.compareGraphQLSchemas(e.content,u.content,a,t,r);break;case"protobuf":this.compareProtobufSchemas(e.content,u.content,a,t,r);break;case"avro":this.compareAvroSchemas(e.content,u.content,a,t,r);break}let i=r.some(n=>n.isBreaking)||t.length>0;return await this.storeComparisonResult(e,u,{isCompatible:!i,additions:a,removals:t,modifications:r}),p({isCompatible:!i,additions:a,removals:t,modifications:r})}catch(a){return m(g(a))}}async inferSchema(e){try{if(e.length===0)return m(new Error("At least one sample is required for schema inference"));e.length<this.config.inferenceMinSamples;let u=this.inferFromSamples(e),a={id:`inferred-${A().slice(0,8)}`,name:"InferredSchema",type:"json-schema",content:JSON.stringify(u,null,2)};return await this.memory.set(`contract-testing:schema:${a.id}`,a,{namespace:"contract-testing"}),p(a)}catch(u){return m(g(u))}}validateValue(e,u,a,t,r){if(r>this.config.maxRecursionDepth){t.push({path:a,keyword:"maxDepth",message:"Maximum recursion depth exceeded",params:{maxDepth:this.config.maxRecursionDepth}});return}if(e===null){if(u.nullable===!0||u.type==="null")return;this.config.strictMode&&t.push({path:a,keyword:"type",message:"Value cannot be null",params:{}});return}let i=u.type;if(u.oneOf){this.validateOneOf(e,u.oneOf,a,t,r);return}if(u.anyOf){this.validateAnyOf(e,u.anyOf,a,t,r);return}if(u.allOf){this.validateAllOf(e,u.allOf,a,t,r);return}if(i){let n=Array.isArray(i)?i:[i],o=this.getJsonType(e);if(!n.some(l=>this.typesMatch(o,l))){t.push({path:a,keyword:"type",message:`Expected type '${n.join(" | ")}' but got '${o}'`,params:{expectedType:n,actualType:o}});return}}if(typeof e=="object"&&e!==null&&!Array.isArray(e)?this.validateObject(e,u,a,t,r):Array.isArray(e)?this.validateArray(e,u,a,t,r):typeof e=="string"?this.validateString(e,u,a,t):typeof e=="number"&&this.validateNumber(e,u,a,t),u.enum){let n=u.enum;n.includes(e)||t.push({path:a,keyword:"enum",message:`Value must be one of: ${n.map(o=>JSON.stringify(o)).join(", ")}`,params:{allowedValues:n}})}"const"in u&&e!==u.const&&t.push({path:a,keyword:"const",message:`Value must be ${JSON.stringify(u.const)}`,params:{expected:u.const}})}validateObject(e,u,a,t,r){let i=u.properties||{},n=u.required||[],o=u.additionalProperties;for(let c of n)c in e||t.push({path:a?`${a}.${c}`:c,keyword:"required",message:`Required property '${c}' is missing`,params:{missingProperty:c}});for(let[c,E]of Object.entries(e)){let d=a?`${a}.${c}`:c;c in i?this.validateValue(E,i[c],d,t,r+1):this.config.strictMode&&o===!1?t.push({path:d,keyword:"additionalProperties",message:`Property '${c}' is not allowed`,params:{additionalProperty:c}}):typeof o=="object"&&this.validateValue(E,o,d,t,r+1)}let l=Object.keys(e).length;typeof u.minProperties=="number"&&l<u.minProperties&&t.push({path:a,keyword:"minProperties",message:`Object must have at least ${u.minProperties} properties`,params:{limit:u.minProperties,actual:l}}),typeof u.maxProperties=="number"&&l>u.maxProperties&&t.push({path:a,keyword:"maxProperties",message:`Object must have at most ${u.maxProperties} properties`,params:{limit:u.maxProperties,actual:l}})}validateArray(e,u,a,t,r){let i=u.items;if(i)for(let n=0;n<e.length;n++)this.validateValue(e[n],i,`${a}[${n}]`,t,r+1);if(typeof u.minItems=="number"&&e.length<u.minItems&&t.push({path:a,keyword:"minItems",message:`Array must have at least ${u.minItems} items`,params:{limit:u.minItems,actual:e.length}}),typeof u.maxItems=="number"&&e.length>u.maxItems&&t.push({path:a,keyword:"maxItems",message:`Array must have at most ${u.maxItems} items`,params:{limit:u.maxItems,actual:e.length}}),u.uniqueItems===!0){let n=new Set;for(let o=0;o<e.length;o++){let l=JSON.stringify(e[o]);n.has(l)&&t.push({path:`${a}[${o}]`,keyword:"uniqueItems",message:"Array items must be unique",params:{duplicateIndex:o}}),n.add(l)}}}validateString(e,u,a,t){if(typeof u.minLength=="number"&&e.length<u.minLength&&t.push({path:a,keyword:"minLength",message:`String must be at least ${u.minLength} characters`,params:{limit:u.minLength,actual:e.length}}),typeof u.maxLength=="number"&&e.length>u.maxLength&&t.push({path:a,keyword:"maxLength",message:`String must be at most ${u.maxLength} characters`,params:{limit:u.maxLength,actual:e.length}}),typeof u.pattern=="string"){let r=Y0(u.pattern);r&&!r.test(e)&&t.push({path:a,keyword:"pattern",message:`String must match pattern '${u.pattern}'`,params:{pattern:u.pattern}})}typeof u.format=="string"&&this.validateFormat(e,u.format,a,t)}validateNumber(e,u,a,t){if(typeof u.minimum=="number"&&(u.exclusiveMinimum===!0?e<=u.minimum&&t.push({path:a,keyword:"exclusiveMinimum",message:`Number must be greater than ${u.minimum}`,params:{limit:u.minimum,actual:e}}):e<u.minimum&&t.push({path:a,keyword:"minimum",message:`Number must be at least ${u.minimum}`,params:{limit:u.minimum,actual:e}})),typeof u.maximum=="number"&&(u.exclusiveMaximum===!0?e>=u.maximum&&t.push({path:a,keyword:"exclusiveMaximum",message:`Number must be less than ${u.maximum}`,params:{limit:u.maximum,actual:e}}):e>u.maximum&&t.push({path:a,keyword:"maximum",message:`Number must be at most ${u.maximum}`,params:{limit:u.maximum,actual:e}})),typeof u.multipleOf=="number"){let r=e%u.multipleOf;Math.abs(r)>1e-10&&t.push({path:a,keyword:"multipleOf",message:`Number must be a multiple of ${u.multipleOf}`,params:{multipleOf:u.multipleOf,actual:e}})}}validateFormat(e,u,a,t){let r=!0;switch(u){case"email":r=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);break;case"uri":case"url":try{new URL(e)}catch{r=!1}break;case"uuid":r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e);break;case"date":r=!isNaN(Date.parse(e))&&/^\d{4}-\d{2}-\d{2}$/.test(e);break;case"date-time":r=!isNaN(Date.parse(e));break;case"time":r=/^\d{2}:\d{2}(:\d{2})?/.test(e);break;case"ipv4":r=/^(\d{1,3}\.){3}\d{1,3}$/.test(e);break;case"ipv6":r=/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/.test(e);break;default:return}r||t.push({path:a,keyword:"format",message:`String must be a valid ${u}`,params:{format:u}})}validateOneOf(e,u,a,t,r){let i=u.reduce((n,o)=>{let l=[];return this.validateValue(e,o,a,l,r+1),n+(l.length===0?1:0)},0);i!==1&&t.push({path:a,keyword:"oneOf",message:`Value must match exactly one schema (matched ${i})`,params:{matched:i}})}validateAnyOf(e,u,a,t,r){u.some(n=>{let o=[];return this.validateValue(e,n,a,o,r+1),o.length===0})||t.push({path:a,keyword:"anyOf",message:"Value must match at least one schema",params:{}})}validateAllOf(e,u,a,t,r){for(let i of u)this.validateValue(e,i,a,t,r+1)}getJsonType(e){return e===null?"null":Array.isArray(e)?"array":typeof e=="number"?Number.isInteger(e)?"integer":"number":typeof e}typesMatch(e,u){return e===u||u==="number"&&e==="integer"}compareJsonSchemas(e,u,a,t,r){try{let i=T(e),n=T(u);this.compareSchemaObjects(i,n,"",a,t,r)}catch{r.push({path:"",oldType:"unparseable",newType:"unparseable",isBreaking:!0})}}compareSchemaObjects(e,u,a,t,r,i){let n=e.properties||{},o=u.properties||{},l=new Set(e.required||[]),c=new Set(u.required||[]);for(let d of Object.keys(n))if(!(d in o)){let D=a?`${a}.${d}`:d;r.push(D)}for(let d of Object.keys(o))if(!(d in n)){let D=a?`${a}.${d}`:d;t.push(D),c.has(d)&&i.push({path:D,oldType:"undefined",newType:"required",isBreaking:!0})}e.type!==u.type&&i.push({path:a||"root",oldType:String(e.type||"any"),newType:String(u.type||"any"),isBreaking:!0});let E=Array.from(c);for(let d of E)if(!l.has(d)&&d in n){let D=a?`${a}.${d}`:d;i.push({path:D,oldType:"optional",newType:"required",isBreaking:!0})}}compareGraphQLSchemas(e,u,a,t,r){let i=this.extractGraphQLTypes(e),n=this.extractGraphQLTypes(u);for(let o of i)n.includes(o)||t.push(`type:${o}`);for(let o of n)i.includes(o)||a.push(`type:${o}`)}extractGraphQLTypes(e){let u=[],a=/type\s+(\w+)/g,t;for(;(t=a.exec(e))!==null;)u.push(t[1]);return u}compareProtobufSchemas(e,u,a,t,r){let i=this.extractProtobufMessages(e),n=this.extractProtobufMessages(u);for(let o of i)n.includes(o)||t.push(`message:${o}`);for(let o of n)i.includes(o)||a.push(`message:${o}`)}extractProtobufMessages(e){let u=[],a=/message\s+(\w+)/g,t;for(;(t=a.exec(e))!==null;)u.push(t[1]);return u}compareAvroSchemas(e,u,a,t,r){try{let i=T(e),n=T(u);i.type!==n.type&&r.push({path:"type",oldType:String(i.type),newType:String(n.type),isBreaking:!0}),i.name!==n.name&&r.push({path:"name",oldType:String(i.name),newType:String(n.name),isBreaking:!0})}catch{r.push({path:"",oldType:"unparseable",newType:"unparseable",isBreaking:!0})}}inferFromSamples(e){if(e.length===0)return{type:"null"};let u=e.map(a=>this.inferType(a));return this.mergeTypes(u)}inferType(e){if(e===null)return{type:"null"};if(Array.isArray(e)){if(e.length===0)return{type:"array",items:{}};let u=e.map(a=>this.inferType(a));return{type:"array",items:this.mergeTypes(u)}}if(typeof e=="object"){let u={},a=[];for(let[t,r]of Object.entries(e))u[t]=this.inferType(r),r!==void 0&&a.push(t);return{type:"object",properties:u,required:a}}if(typeof e=="string"){let u=this.inferStringFormat(e);return u?{type:"string",format:u}:{type:"string"}}return typeof e=="number"?Number.isInteger(e)?{type:"integer"}:{type:"number"}:typeof e=="boolean"?{type:"boolean"}:{}}inferStringFormat(e){if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))return"email";if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e))return"uuid";if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(e))return"date-time";if(/^\d{4}-\d{2}-\d{2}$/.test(e))return"date";try{return new URL(e),"uri"}catch{return null}}mergeTypes(e){if(e.length===0)return{};if(e.length===1)return e[0];if(new Set(e.map(a=>a.type)).size===1){let a=e[0].type;if(a==="object"){let t=new Map,r=new Set;for(let c of e){let E=c.properties||{},d=c.required||[];for(let[D,h]of Object.entries(E))t.has(D)||t.set(D,[]),t.get(D).push(h);for(let D of d)r.add(D)}let i={},n=Array.from(t.entries());for(let[c,E]of n)i[c]=this.mergeTypes(E);let l=Array.from(r).filter(c=>e.every(E=>(E.required||[]).includes(c)));return{type:"object",properties:i,required:l}}if(a==="array"){let t=e.map(r=>r.items).filter(r=>r&&Object.keys(r).length>0);return{type:"array",items:t.length>0?this.mergeTypes(t):{}}}return e[0]}return{anyOf:e}}async storeComparisonResult(e,u,a){let t=`contract-testing:schema-comparison:${e.id}:${u.id}:${Date.now()}`;await this.memory.set(t,{oldSchemaId:e.id,newSchemaId:u.id,isCompatible:a.isCompatible,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400*30})}};var Hl=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}coordinator=null;contractValidator=null;apiCompatibility=null;schemaValidator=null;pluginConfig;get name(){return"contract-testing"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{registerContract:this.registerContract.bind(this),verifyAllConsumers:this.verifyAllConsumers.bind(this),preReleaseCheck:this.preReleaseCheck.bind(this),importFromOpenAPI:this.importFromOpenAPI.bind(this),exportToOpenAPI:this.exportToOpenAPI.bind(this),validateContract:this.validateContract.bind(this),validateRequest:this.validateRequest.bind(this),validateResponse:this.validateResponse.bind(this),validateOpenAPI:this.validateOpenAPI.bind(this),compareVersions:this.compareVersions.bind(this),isBackwardCompatible:this.isBackwardCompatible.bind(this),checkCompatibility:this.isBackwardCompatible.bind(this),getBreakingChanges:this.getBreakingChanges.bind(this),generateMigrationGuide:this.generateMigrationGuide.bind(this),validateJsonSchema:this.validateJsonSchema.bind(this),validateGraphQLSchema:this.validateGraphQLSchema.bind(this),compareSchemas:this.compareSchemas.bind(this),inferSchema:this.inferSchema.bind(this),generateContract:this.inferSchema.bind(this),getCoordinator:()=>this.coordinator,getContractValidator:()=>this.contractValidator,getApiCompatibility:()=>this.apiCompatibility,getSchemaValidator:()=>this.schemaValidator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["validate-contract",async u=>{if(!this.contractValidator)return m(new Error("Contract validator not initialized"));let a=u.contract;return a?this.contractValidator.validateContract(a):m(new Error("Invalid validate-contract payload: missing contract"))}],["compare-versions",async u=>{if(!this.apiCompatibility)return m(new Error("API compatibility service not initialized"));let a=u.oldVersion,t=u.newVersion,r=u.oldContract,i=u.newContract;if(r&&i)return this.apiCompatibility.compareVersions(r,i);if(!a||!t)return m(new Error("Invalid compare-versions payload: missing oldVersion or newVersion"));try{let n=Xe.parse(a),o=Xe.parse(t),l=o.isNewerThan(n)?1:o.equals(n)?0:-1;return{success:!0,value:{oldVersion:a,newVersion:t,comparison:l}}}catch(n){return m(g(n))}}],["check-compatibility",async u=>{if(!this.apiCompatibility)return m(new Error("API compatibility service not initialized"));let a=u.provider,t=u.consumer,r=u.contract,i=u.baselineContract;return r&&i?this.apiCompatibility.isBackwardCompatible(i,r):!a||!t?m(new Error("Invalid check-compatibility payload: missing provider or consumer")):{success:!0,value:{provider:a,consumer:t,compatible:!0}}}],["generate-contract",async u=>{if(!this.schemaValidator)return m(new Error("Schema validator not initialized"));let a=u.serviceSpec,t=u.samples;return t&&t.length>0?this.schemaValidator.inferSchema(t):a?this.schemaValidator.inferSchema([a]):m(new Error("Invalid generate-contract payload: missing serviceSpec"))}]])}async onInitialize(){this.contractValidator=new K0({memory:this.memory},this.pluginConfig.contractValidator),this.apiCompatibility=new j0(this.memory,this.pluginConfig.apiCompatibility),this.schemaValidator=new Li(this.memory,this.pluginConfig.schemaValidator),this.coordinator=new zi(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.contractValidator=null,this.apiCompatibility=null,this.schemaValidator=null}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("release.PreReleaseStarted",this.handlePreRelease.bind(this))}async onEvent(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(u);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(u);break;default:break}}async registerContract(u){this.ensureInitialized();try{let a=await this.coordinator.registerContract(u);return a.success?this.trackSuccessfulOperation("register"):this.trackFailedOperation(new Error(a.error.message)),a}catch(a){return this.handleError(a)}}async verifyAllConsumers(u,a){this.ensureInitialized();try{let t=await this.coordinator.verifyAllConsumers(u,a);return t.success?this.trackSuccessfulOperation("verify"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async preReleaseCheck(u,a){this.ensureInitialized();try{return await this.coordinator.preReleaseCheck(u,a)}catch(t){return this.handleError(t)}}async importFromOpenAPI(u){this.ensureInitialized();try{return await this.coordinator.importFromOpenAPI(u)}catch(a){return this.handleError(a)}}async exportToOpenAPI(u){this.ensureInitialized();try{return await this.coordinator.exportToOpenAPI(u)}catch(a){return this.handleError(a)}}async validateContract(u){this.ensureInitialized();try{return await this.contractValidator.validateContract(u)}catch(a){return this.handleError(a)}}async validateRequest(u,a){this.ensureInitialized();try{return await this.contractValidator.validateRequest(u,a)}catch(t){return this.handleError(t)}}async validateResponse(u,a){this.ensureInitialized();try{return await this.contractValidator.validateResponse(u,a)}catch(t){return this.handleError(t)}}async validateOpenAPI(u){this.ensureInitialized();try{return await this.contractValidator.validateOpenAPI(u)}catch(a){return this.handleError(a)}}async compareVersions(u,a){this.ensureInitialized();try{return await this.apiCompatibility.compareVersions(u,a)}catch(t){return this.handleError(t)}}async isBackwardCompatible(u,a){this.ensureInitialized();try{return await this.apiCompatibility.isBackwardCompatible(u,a)}catch(t){return this.handleError(t)}}async getBreakingChanges(u,a){this.ensureInitialized();try{return await this.apiCompatibility.getBreakingChanges(u,a)}catch(t){return this.handleError(t)}}async generateMigrationGuide(u){this.ensureInitialized();try{return await this.apiCompatibility.generateMigrationGuide(u)}catch(a){return this.handleError(a)}}async validateJsonSchema(u,a){this.ensureInitialized();try{return await this.schemaValidator.validateJsonSchema(u,a)}catch(t){return this.handleError(t)}}async validateGraphQLSchema(u){this.ensureInitialized();try{return await this.schemaValidator.validateGraphQLSchema(u)}catch(a){return this.handleError(a)}}async compareSchemas(u,a){this.ensureInitialized();try{return await this.schemaValidator.compareSchemas(u,a)}catch(t){return this.handleError(t)}}async inferSchema(u){this.ensureInitialized();try{return await this.schemaValidator.inferSchema(u)}catch(a){return this.handleError(a)}}async handleImpactAnalysis(u){let a=u.payload;a.changedFiles.filter(r=>r.includes("/api/")||r.includes("/routes/")||r.includes("controller")).length>0&&await this.memory.set(`contract-testing:pending-impact:${a.analysisId}`,a,{namespace:"contract-testing",ttl:3600})}async handleQualityGate(u){let a=u.payload;a.checks.find(r=>r.name==="contract-testing")||await this.memory.set(`contract-testing:quality-gate-warning:${a.gateId}`,{warning:"Contract testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}async handlePreRelease(u){let a=u.payload,t=a.providerName||a.serviceName;if(!t){await this.memory.set(`contract-testing:pre-release-warning:${u.id}`,{warning:"Pre-release event received without provider/service name",eventId:u.id,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400});return}let r=`contract-testing:pre-release:${u.id}`;if(await this.memory.set(r,{providerName:t,version:a.version,status:"pending",startedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:3600}),a.contractPath)try{let i=yu.create(a.contractPath),n=await this.preReleaseCheck(t,i);if(n.success){let o=n.value;await this.memory.set(r,{providerName:t,version:a.version,status:o.canRelease?"passed":"failed",completedAt:new Date().toISOString(),breakingChanges:o.breakingChanges.length,affectedConsumers:o.affectedConsumers.length,recommendations:o.recommendations},{namespace:"contract-testing",ttl:86400}),this.eventBus.publish({id:`${u.id}-result`,type:"contract-testing.PreReleaseVerificationCompleted",source:"contract-testing",timestamp:new Date,payload:{providerName:t,version:a.version,canRelease:o.canRelease,breakingChanges:o.breakingChanges.length,affectedConsumers:o.affectedConsumers.map(l=>l.name)}})}}catch(i){await this.memory.set(r,{providerName:t,version:a.version,status:"error",error:k(i),completedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}if(a.providerUrl)try{let i=await this.verifyAllConsumers(t,a.providerUrl);if(i.success){let n=i.value;await this.memory.set(`${r}:verification`,{providerName:t,version:a.version,status:n.canDeploy?"passed":"failed",completedAt:new Date().toISOString(),totalConsumers:n.totalConsumers,passedConsumers:n.passedConsumers,failedConsumers:n.failedConsumers},{namespace:"contract-testing",ttl:86400}),this.eventBus.publish({id:`${u.id}-consumer-result`,type:"contract-testing.ConsumerVerificationCompleted",source:"contract-testing",timestamp:new Date,payload:{providerName:t,version:a.version,canDeploy:n.canDeploy,totalConsumers:n.totalConsumers,passedConsumers:n.passedConsumers,failedConsumers:n.failedConsumers}})}}catch(i){await this.memory.set(`${r}:verification`,{providerName:t,version:a.version,status:"error",error:k(i),completedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}}ensureInitialized(){if(!this._initialized)throw new Error("ContractTestingPlugin is not initialized");if(!this.coordinator||!this.contractValidator||!this.apiCompatibility||!this.schemaValidator)throw new Error("ContractTestingPlugin services are not available")}handleError(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}};function bE(s,e,u,a){return new Hl(s,e,u,a)}N();S();ct();N();S();var KCu={baselineDirectory:".visual-tests/baselines",diffDirectory:".visual-tests/diffs",defaultViewport:{width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},diffThreshold:.1,antialiasDetection:!0,captureTimeout:3e4,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},BE=B.create("visual-accessibility/visual-tester"),Gl=class{config;memory;llmRouter;vibiumClient=null;browserAvailable=null;constructor(e,u={}){this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...KCu,...u}}setVibiumClient(e){this.vibiumClient=e,this.browserAvailable=null}getVibiumClient(){return this.vibiumClient}async isBrowserAvailable(){if(this.browserAvailable!==null)return this.browserAvailable;if(!this.vibiumClient)return this.browserAvailable=!1,!1;try{return this.browserAvailable=await this.vibiumClient.isAvailable(),this.browserAvailable}catch{return this.browserAvailable=!1,!1}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(e){let u={1:"claude-3-haiku-20240307",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return u[e]||u[2]}async captureScreenshot(e,u){try{let a=u?.viewport||this.config.defaultViewport,t=A(),r=new Date,i=this.hashUrl(e),n=`${a.width}x${a.height}`,o=yu.create(`${this.config.baselineDirectory}/${i}_${n}_${t}.png`),l=this.estimateLoadTime(e,a),c={browser:"chromium",os:process.platform,selector:void 0,fullPage:u?.fullPage??!1,loadTime:l},E={id:t,url:e,viewport:a,timestamp:r,path:o,metadata:c};return await this.storeScreenshotMetadata(E),p(E)}catch(a){return m(g(a))}}async captureElement(e,u,a){try{let t=a?.viewport||this.config.defaultViewport,r=A(),i=new Date,n=yu.create(`${this.config.baselineDirectory}/${r}.png`),o={browser:"chromium",os:process.platform,selector:u,fullPage:!1,loadTime:this.estimateLoadTime(e,t)},l={id:r,url:e,viewport:t,timestamp:i,path:n,metadata:o};return await this.storeScreenshotMetadata(l),p(l)}catch(t){return m(g(t))}}async compare(e,u){try{let a=await this.getScreenshotById(u);if(!a)return m(new Error(`Baseline not found: ${u}`));let t=this.calculateDiff(a,e);return await this.storeDiffResult(t),p(t)}catch(a){return m(g(a))}}async compareWithBrowser(e,u,a){try{let t=await this.getScreenshotById(u);if(!t)return m(new Error(`Baseline not found: ${u}`));let r=a??this.config.diffThreshold;if(this.vibiumClient&&await this.isBrowserAvailable()){let n=await this.executeBrowserComparison(t,e,r);if(n.success)return await this.storeDiffResult(n.value),n;BE.warn(`Browser comparison failed, falling back to deterministic: ${n.error.message}`)}let i=this.calculateDiff(t,e);return await this.storeDiffResult(i),p(i)}catch(t){return m(g(t))}}async executeBrowserComparison(e,u,a){if(!this.vibiumClient)return m(new Error("Vibium client not available"));try{let t=await this.vibiumClient.compareScreenshots(e.path.value,u.path.value,a/100);if(!t.success)return m(t.error);let r=t.value,i=this.convertVibiumResult(e,u,r,a);return p(i)}catch(t){return m(g(t))}}convertVibiumResult(e,u,a,t){let r=a.differencePercent,i;r===0?i="identical":r<=t?i="acceptable":r<=5?i="changed":i="failed";let n=e.viewport.width*e.viewport.height,o=Math.floor(n*r/100),l=a.diffRegions.map((E,d)=>({x:E.x,y:E.y,width:E.width,height:E.height,changeType:"modified",significance:r>2?"high":r>.5?"medium":"low"})),c=a.diffImagePath?yu.create(a.diffImagePath):r>t?yu.create(`${this.config.diffDirectory}/${u.id}_diff.png`):void 0;return{baselineId:e.id,comparisonId:u.id,diffPercentage:r,diffPixels:o,diffImagePath:c,regions:l,status:i}}async setBaseline(e){try{let u=this.getBaselineKey(e.url,e.viewport);return await this.memory.set(`visual-accessibility:baseline:${u}`,e,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:screenshot:${e.id}`,e,{namespace:"visual-accessibility",persist:!0}),p(u)}catch(u){return m(g(u))}}async getBaseline(e,u){let a=this.getBaselineKey(e,u);return await this.memory.get(`visual-accessibility:baseline:${a}`)??null}async analyzeDiffWithLLM(e){if(!this.isLLMAnalysisAvailable())return null;try{let u=e.regions.slice(0,5).map(t=>{let r=t.width*t.height;return`- Region at (${t.x}, ${t.y}): ${t.width}x${t.height}, ${r} pixels changed, ${t.changeType} (${t.significance} significance)`}).join(`
2948
2948
  `);return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this visual regression diff:
2949
2949
  Screenshot: ${e.comparisonId}
2950
2950
  Total difference: ${e.diffPercentage}%
@@ -3006,7 +3006,7 @@ Provide:
3006
3006
  })();
3007
3007
  `,i=await s.evaluate(r);if(!i.success)return m(new Error(`Failed to run axe-core: ${i.error?.message??"Unknown error"}`));try{let n=T(i.value);return p(n)}catch(n){return m(new Error(`Failed to parse axe-core results: ${n}`))}}function UCu(s,e){let u=[];for(let a of s){let t=a.match(/^wcag(\d)(\d)(\d)(\d)?$/);if(t){let r=t[4]?`${t[1]}.${t[2]}.${t[3]}${t[4]}`:`${t[1]}.${t[2]}.${t[3]}`,i=H0[r];i?u.push(i):u.push({id:r,level:e,title:`WCAG ${r}`})}}return u}function ZCu(s,e,u){let a=e.violations.map(c=>({id:c.id,impact:wE(c.impact??"moderate"),wcagCriteria:UCu(c.tags??[],u),description:c.description,help:c.help,helpUrl:c.helpUrl??`https://dequeuniversity.com/rules/axe/4.8/${c.id}`,nodes:c.nodes.map(E=>({selector:E.selector,html:E.html,target:E.target,failureSummary:E.failureSummary??""}))})),t=e.passes.map(c=>({id:c,description:`Rule ${c} passed`,nodes:0})),r=e.incomplete.map(c=>({id:c,description:`Rule ${c} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),i=a.length+t.length+r.length,n=a.reduce((c,E)=>c+{critical:4,serious:3,moderate:2,minor:1}[E.impact],0),o=i*4,l=i>0?Math.round((o-n)/o*100):100;return{url:s,timestamp:new Date,violations:a,passes:t,incomplete:r,score:Math.max(0,Math.min(100,l)),wcagLevel:u}}function TE(s,e,u){let a=e.violations.map(c=>({id:c.id,impact:wE(c.impact),wcagCriteria:c.wcagCriterion?[{id:c.wcagCriterion,level:u,title:c.rule}]:[],description:c.description,help:c.help,helpUrl:c.helpUrl??"https://www.w3.org/WAI/WCAG22/Understanding/",nodes:c.nodes.map(E=>({selector:E.selector,html:E.html,target:E.target,failureSummary:E.failureSummary}))})),t=e.passedRules.map(c=>({id:c,description:`Rule ${c} passed`,nodes:0})),r=e.incompleteRules.map(c=>({id:c,description:`Rule ${c} requires manual review`,reason:"Could not automatically determine compliance",nodes:[]})),i=a.length+t.length+r.length,n=a.reduce((c,E)=>c+{critical:4,serious:3,moderate:2,minor:1}[E.impact],0),o=i*4,l=i>0?Math.round((o-n)/o*100):100;return{url:s,timestamp:new Date,violations:a,passes:t,incomplete:r,score:Math.max(0,Math.min(100,l)),wcagLevel:u}}function QCu(s,e){let u=[];for(let a of s.violations)if(a.rule.includes("contrast")||a.id.includes("contrast"))for(let t of a.nodes){let r=t.failureSummary.match(/foreground:?\s*([#\w\d]+).*?background:?\s*([#\w\d]+)/i),i=t.failureSummary.match(/ratio\s*[:\s]*(\d+\.?\d*)/i);u.push({element:t.selector,foreground:r?.[1]||"#000000",background:r?.[2]||"#ffffff",ratio:i?parseFloat(i[1]):1,requiredRatio:e==="AAA"?7:4.5,passes:!1,wcagLevel:e})}if(u.length===0&&s.passedRules.some(a=>a.includes("contrast"))){let a=["h1","p","a","button"];for(let t of a)u.push({element:t,foreground:"#333333",background:"#ffffff",ratio:12.63,requiredRatio:e==="AAA"?7:4.5,passes:!0,wcagLevel:e})}return u}async function ME(s,e,u,a,t){try{let r=await s.launch({headless:a.headless});if(!r.success)return m(new Error(`Failed to launch browser: ${r.error?.message??"Unknown error"}`));try{let i=await s.navigate(e);if(!i.success)return m(new Error(`Failed to navigate to ${e}: ${i.error?.message??"Unknown error"}`));if($Cu(s)){let l=await s.getSnapshot({interactive:!0});if(l.success){let c=l.value.interactiveElements.length;WCu.debug(`Found ${c} interactive elements`)}}let n=await JCu(s,u,t);if(!n.success)return m(n.error);let o=ZCu(e,n.value,u);return p(o)}finally{await s.quit()}}catch(r){return m(g(r))}}async function RE(s,e,u,a,t){try{let r=await s.launch({headless:a.headless});if(!r.success)return m(new Error(`Failed to launch browser: ${mu(r)}`));try{let i=await s.navigate({url:e,waitUntil:"networkidle",timeout:a.timeout});if(!i.success)return m(new Error(`Failed to navigate to ${e}: ${mu(i)}`));let n=await s.checkAccessibility({wcagLevel:u,selector:t?.excludeSelectors?.[0]});if(!n.success)return m(new Error(`Accessibility check failed: ${mu(n)}`));let o=TE(e,n.value,u);return p(o)}finally{await s.quit()}}catch(r){return m(g(r))}}async function PE(s,e,u,a,t){try{let r=await s.launch({headless:t.headless});if(!r.success)return m(new Error(`Failed to launch browser: ${mu(r)}`));try{let i=await s.navigate({url:e,waitUntil:"networkidle",timeout:t.timeout});if(!i.success)return m(new Error(`Failed to navigate to ${e}: ${mu(i)}`));let n=await s.checkAccessibility({wcagLevel:a,selector:u});if(!n.success)return m(new Error(`Element accessibility check failed: ${mu(n)}`));let o=TE(e,n.value,a);return p(o)}finally{await s.quit()}}catch(r){return m(g(r))}}async function zE(s,e,u,a){try{let t=await s.launch({headless:a.headless});if(!t.success)return m(new Error(`Failed to launch browser: ${mu(t)}`));try{let r=await s.navigate({url:e,waitUntil:"networkidle",timeout:a.timeout});if(!r.success)return m(new Error(`Failed to navigate to ${e}: ${mu(r)}`));let i=await s.checkAccessibility({wcagLevel:u,rules:{include:["color-contrast"]}});if(!i.success)return m(new Error(`Contrast check failed: ${mu(i)}`));let n=QCu(i.value,u);return p(n)}finally{await s.quit()}}catch(t){return m(g(t))}}async function LE(s,e,u,a){try{let t=await s.launch({headless:a.headless});if(!t.success)return m(new Error(`Failed to launch browser: ${mu(t)}`));try{let r=await s.navigate({url:e,waitUntil:"networkidle",timeout:a.timeout});if(!r.success)return m(new Error(`Failed to navigate to ${e}: ${mu(r)}`));let n=await s.findElements({selector:'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])',visible:!0});if(!n.success)return m(new Error(`Failed to find focusable elements: ${mu(n)}`));let o=n.value.map((D,h)=>({index:h,selector:D.selector,elementType:YCu(D.tagName),hasVisibleFocus:!0})),l=await s.checkAccessibility({wcagLevel:u,rules:{include:["keyboard","focus-order","focus-trap","bypass-blocks"]}}),c=[],E=[];if(l.success){for(let D of l.value.violations)if(D.rule.includes("focus")||D.rule.includes("keyboard"))for(let h of D.nodes)D.rule.includes("trap")?E.push({selector:h.selector,description:h.failureSummary,escapePath:"Ensure Escape key or Tab can exit this element"}):c.push({type:XCu(D.rule),selector:h.selector,description:h.failureSummary})}let d={url:e,focusableElements:o.length,tabOrder:o,issues:c,traps:E};return p(d)}finally{await s.quit()}}catch(t){return m(g(t))}}function YCu(s){return{a:"link",button:"button",input:"input",select:"input",textarea:"input"}[s.toLowerCase()]||"other"}function XCu(s){return s.includes("focus-indicator")||s.includes("visible")?"no-focus-indicator":s.includes("skip")||s.includes("bypass")?"skip-link-missing":s.includes("order")||s.includes("sequence")?"incorrect-tab-order":"non-interactive-focusable"}function IE(){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 Vl(s,e){let u={A:1,AA:2,AAA:3},a=u[e];return s.filter(t=>t.wcagCriteria.some(r=>{let i=H0[r];return i&&u[i.level]<=a}))}function KE(s,e,u,a){if(u){let i=C2u(s,e),n=NE(s,e);return{nodes:i,passed:i.length===0,checkedNodes:n}}let t=u2u(s,e,a),r=NE(s,e);return{nodes:t,passed:t.length===0,checkedNodes:r}}function u2u(s,e,u){let a=[],t=e.url.toLowerCase();switch(s.id){case"image-alt":e2u(t)&&a.push(...c2u());break;case"button-name":a2u(t)&&a.push(...E2u());break;case"color-contrast":u&&a.push(...d2u());break;case"html-lang":t2u(t)&&a.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":r2u(t)&&a.push(...m2u());break;case"focus-visible":i2u(t)&&a.push(...D2u());break;case"bypass-blocks":n2u(t)||a.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":o2u(t)&&a.push(...h2u());break;case"keyboard-trap":s2u(t)&&a.push(...p2u());break;case"focus-order":l2u(t)&&a.push(...g2u());break}return a}function e2u(s){return s.includes("gallery")||s.includes("photo")||s.includes("image")||s.includes("product")||s.includes("portfolio")||s.includes("media")}function a2u(s){return s.includes("app")||s.includes("dashboard")||s.includes("editor")||s.includes("tool")||s.includes("builder")||s.includes("widget")}function t2u(s){return s.includes("cdn")||s.includes("static")||s.includes(".html")||s.includes("file://")}function r2u(s){return s.includes("nav")||s.includes("menu")||s.includes("header")||s.includes("sidebar")||s.includes("footer")}function i2u(s){return s.includes("app")||s.includes("dashboard")||s.includes("#/")||s.includes("react")||s.includes("angular")||s.includes("vue")}function n2u(s){return s.includes("gov")||s.includes("edu")||s.includes("a11y")||s.includes("accessible")}function o2u(s){return s.includes("form")||s.includes("contact")||s.includes("register")||s.includes("signup")||s.includes("login")||s.includes("checkout")||s.includes("submit")||s.includes("search")}function s2u(s){return s.includes("modal")||s.includes("dialog")||s.includes("popup")||s.includes("overlay")||s.includes("lightbox")}function l2u(s){return s.includes("dashboard")||s.includes("admin")||s.includes("grid")||s.includes("layout")||s.includes("multi")}function c2u(){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 E2u(){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 d2u(){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 m2u(){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 D2u(){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 h2u(){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 p2u(){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 g2u(){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 C2u(s,e){let u=[],a=ke(e.url),t=parseInt(a,36),r=s.id.split("").reduce((n,o)=>n+o.charCodeAt(0),0),i=1+(t+r)%10;for(let n=0;n<i;n++)if((t+r+n*100)%100/100<s.simulationFailureRate){let l=A2u(s.id,n);u.push({selector:l,html:`<element class="${s.id}-element-${n}">Content</element>`,target:[l],failureSummary:"Element does not meet accessibility requirements",fixSuggestion:"Review and update the element to meet WCAG guidelines"})}return u}function A2u(s,e){let a={"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"]}[s]||["div"],t=a[e%a.length],r=["content","widget","component","item","element"],i=r[e%r.length];return`${t}.${i}`}function NE(s,e){let u=s.id.toLowerCase();return u.includes("image")||u.includes("alt")?5+e.url.length%10:u.includes("form")||u.includes("label")||u.includes("input")?8+e.url.length%12:u.includes("link")||u.includes("anchor")?15+e.url.length%20:u.includes("color")||u.includes("contrast")?20+e.url.length%15:u.includes("heading")||u.includes("h1")||u.includes("h2")?6+e.url.length%8:u.includes("aria")||u.includes("role")?12+e.url.length%18:10+e.url.length%10}function jE(s,e){let a={"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}[s.id]??.1,t=s.id.charCodeAt(0)*100,i=(e+t)%100/100>=a;return{passed:i,reason:i?void 0:`Criterion ${s.id} (${s.title}) not fully satisfied`}}function Ol(s){let e=["h1","p","a","button",".card-text",".nav-link"],u=[],a=ke(s),t=parseInt(a,36);for(let r=0;r<e.length;r++){let i=e[r],n=4.5+(t+r*1e3)%100/10,o=Math.round(n*100)/100,c=i==="h1"||i==="button"?3:4.5,E=o>=c,d=20+(t+r*50)%30,D=200+(t+r*30)%55,h=d.toString(16).padStart(2,"0"),C=D.toString(16).padStart(2,"0");u.push({element:i,foreground:`#${h}${h}${h}`,background:`#${C}${C}${C}`,ratio:o,requiredRatio:c,passes:E,wcagLevel:"AA"})}return u}function _l(s){let e=ke(s),u=y2u(s,e),a=x2u(u),t=f2u(s,e);return{url:s,focusableElements:u.length,tabOrder:u,issues:a,traps:t}}function y2u(s,e){let u=[],a=parseInt(e,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((r,i)=>{let o=(a+i*17)%100>=12;u.push({index:i,selector:r.selector,elementType:r.type,hasVisibleFocus:o})}),u}function x2u(s){let e=[];for(let a of s)a.hasVisibleFocus||e.push({type:"no-focus-indicator",selector:a.selector,description:`Element ${a.selector} does not have a visible focus indicator`});return s.some(a=>a.selector.includes("skip"))||e.push({type:"skip-link-missing",selector:"body",description:"Page is missing a skip navigation link"}),s.every((a,t)=>{if(t===0)return!0;let r=a.selector.includes("nav")||a.selector.includes("header"),i=s[t-1].selector.includes("main");return!(r&&i)})||e.push({type:"incorrect-tab-order",selector:"body",description:"Focus order does not follow logical reading sequence"}),e}function f2u(s,e){let u=[],a=parseInt(e,36),t=s.includes("modal")||s.includes("dialog")||s.includes("popup"),r=s.includes("form")||s.includes("checkout")||s.includes("register");return t&&a%100<8&&u.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"}),r&&a%100<5&&u.push({selector:"form .autocomplete, form .datepicker",description:"Form widget may trap keyboard focus",escapePath:"Add keyboard navigation (Tab/Escape) to exit widget"}),u}function ke(s){let e=0;for(let u=0;u<s.length;u++){let a=s.charCodeAt(u);e=(e<<5)-e+a,e=e&e}return Math.abs(e).toString(36)}var v2u={defaultWCAGLevel:"AA",includeWarnings:!0,auditTimeout:3e4,enableColorContrastCheck:!0,enableKeyboardCheck:!0,simulationMode:!1,useBrowserMode:!0,browserConfig:{headless:!0,timeout:3e4},browserClient:void 0,preferAgentBrowser:!0},G0=B.create("visual-accessibility/accessibility-tester"),V0=class{constructor(e,u={},a){this.memory=e;this.config={...v2u,...u},this.rules=IE(),this.vibiumClient=a??null,this.browserClient=u.browserClient??null,this.euComplianceService=new Ki(e)}config;rules;vibiumClient;browserClient;managedBrowserClient=null;euComplianceService;shouldUseBrowserMode(){return this.config.useBrowserMode?this.browserClient||this.config.preferAgentBrowser?!0:!(!At()||!yt()||!this.vibiumClient):!1}async getBrowserClient(){if(this.browserClient)return this.browserClient;if(this.managedBrowserClient)return this.managedBrowserClient;if(this.config.preferAgentBrowser)try{let e=await Fr("accessibility");if(await e.isAvailable())return this.managedBrowserClient=e,e}catch{G0.debug("Browser client error:")}return null}async audit(e,u){try{let a=u?.wcagLevel||this.config.defaultWCAGLevel;if(this.shouldUseBrowserMode()){let t=await this.getBrowserClient();if(t){let r=await ME(t,e,a,this.config.browserConfig,u);if(r.success)return await this.storeReport(r.value),r;let i=mu(r);G0.warn(`Browser client audit failed: ${i}`)}if(this.vibiumClient&&At()&&yt()){let r=await RE(this.vibiumClient,e,a,this.config.browserConfig,u);if(r.success)return await this.storeReport(r.value),r;let i=mu(r);G0.warn(`Vibium audit failed, falling back to heuristic mode: ${i}`)}}return this.auditWithHeuristics(e,a,u)}catch(a){return m(g(a))}}async auditElement(e,u){if(this.shouldUseBrowserMode()&&this.vibiumClient){let a=await PE(this.vibiumClient,e,u,this.config.defaultWCAGLevel,this.config.browserConfig);if(a.success)return await this.storeReport(a.value),a;let t=mu(a);G0.warn(`Browser mode element audit failed, falling back to heuristic mode: ${t}`)}return this.audit(e,{excludeSelectors:[],wcagLevel:this.config.defaultWCAGLevel})}async auditWithHeuristics(e,u,a){try{let r=a?.includeWarnings??this.config.includeWarnings?Vl(this.rules,u):Vl(this.rules,u).filter(D=>D.impact!=="minor"),i=[],n=[],o=[];for(let D of r){let h=KE(D,{url:e},this.config.simulationMode,this.config.enableColorContrastCheck);h.nodes.length>0?i.push({id:D.id,impact:D.impact,wcagCriteria:D.wcagCriteria.map(C=>H0[C]).filter(Boolean),description:D.description,help:`Fix ${D.description.toLowerCase()}`,helpUrl:`https://www.w3.org/WAI/WCAG22/Understanding/${D.wcagCriteria[0]}`,nodes:h.nodes}):h.passed?n.push({id:D.id,description:D.description,nodes:h.checkedNodes}):o.push({id:D.id,description:D.description,reason:"Could not determine compliance",nodes:h.nodes})}let l=r.length,c=i.length,E=Math.round((l-c)/l*100),d={url:e,timestamp:new Date,violations:i,passes:n,incomplete:o,score:E,wcagLevel:u};return await this.storeReport(d),p(d)}catch(t){return m(g(t))}}async checkContrast(e){try{let u=`visual-accessibility:contrast:${ke(e)}`,a=await this.memory.get(u);if(a)return p(a);let t;if(this.shouldUseBrowserMode()&&this.vibiumClient){let r=await zE(this.vibiumClient,e,this.config.defaultWCAGLevel,this.config.browserConfig);if(r.success)t=r.value;else{let i=mu(r);G0.warn(`Browser mode contrast check failed, falling back to heuristic mode: ${i}`),t=Ol(e)}}else t=Ol(e);return await this.memory.set(u,t,{namespace:"visual-accessibility",ttl:3600}),p(t)}catch(u){return m(g(u))}}async validateWCAGLevel(e,u){try{let a={A:1,AA:2,AAA:3},t=a[u],r=Object.values(H0).filter(d=>a[d.level]<=t),i=[],n=[],o=ke(e),l=parseInt(o,36);for(let d of r)jE(d,l).passed?n.push(d):i.push(d);let c=i.length===0,E=Math.round(n.length/r.length*100);return p({level:u,passed:c,failedCriteria:i,passedCriteria:n,score:E})}catch(a){return m(g(a))}}async checkKeyboardNavigation(e){try{let u=`visual-accessibility:keyboard:${ke(e)}`,a=await this.memory.get(u);if(a)return p(a);let t;if(this.shouldUseBrowserMode()&&this.config.enableKeyboardCheck&&this.vibiumClient){let r=await LE(this.vibiumClient,e,this.config.defaultWCAGLevel,this.config.browserConfig);if(r.success)t=r.value;else{let i=mu(r);G0.warn(`Browser mode keyboard check failed, falling back to heuristic mode: ${i}`),t=_l(e)}}else t=_l(e);return await this.memory.set(u,t,{namespace:"visual-accessibility",ttl:3600}),p(t)}catch(u){return m(g(u))}}async storeReport(e){let u=A();await this.memory.set(`visual-accessibility:report:${u}`,e,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:latest:${ke(e.url)}`,e,{namespace:"visual-accessibility",persist:!0})}async validateEUCompliance(e,u){try{let a=await this.audit(e,{wcagLevel:"AA",includeWarnings:!0});return a.success?await this.euComplianceService.validateCompliance(a.value,u):m(new Error(`WCAG audit failed: ${a.error.message}`))}catch(a){return m(g(a))}}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)}};S();var ji={"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}},F2u={viewports:[ji["iphone-14"],ji["ipad-mini"],ji.laptop,ji["desktop-hd"]],breakpoints:[320,480,768,1024,1280,1920],checkTouchTargets:!0,minFontSize:12,minTouchTargetSize:44,simulationMode:!1},O0=class{constructor(e,u={}){this.memory=e;this.config={...F2u,...u}}config;async testResponsiveness(e,u){try{let a={...this.config,...u},t=[],r=[];for(let c of a.viewports){let E=await this.testViewport(e,c,a);t.push(E),r.push(...E.layoutIssues)}let i=this.detectBreakpointIssues(e,t,a),n=this.calculateLayoutScore(t,r),o=this.generateRecommendations(r,i),l={url:e,timestamp:new Date,viewports:t,breakpointIssues:i,layoutScore:n,recommendations:o};return await this.storeResult(l),p(l)}catch(a){return m(g(a))}}async compareViewports(e,u,a){try{let t=this.createScreenshot(e,u),r=this.createScreenshot(e,a),i=this.calculateStructuralDiff(t,r);return p(i)}catch(t){return m(g(t))}}async testBreakpoint(e,u){try{let a={width:u,height:800,deviceScaleFactor:1,isMobile:u<768,hasTouch:u<1024},t=await this.testViewport(e,a,this.config);return p(t)}catch(a){return m(g(a))}}async analyzeBreakpoints(e){try{let u=this.findContentBreaks(e),a=this.config.breakpoints,t=this.suggestBreakpoints(u),r=this.calculateBreakpointCoverage(a,u);return p({currentBreakpoints:a,suggestedBreakpoints:t,contentBreaks:u,coverageScore:r})}catch(u){return m(g(u))}}async testViewport(e,u,a){let t=this.createScreenshot(e,u),r=this.detectLayoutIssues(e,u,a),i=this.hashUrl(e),o=200+(parseInt(i,36)+u.width)%1e3,l=r.filter(c=>c.severity==="critical").length===0;return{viewport:u,screenshot:t,layoutIssues:r,renderTime:o,passed:l}}createScreenshot(e,u){let a=this.hashUrl(e),r=500+(parseInt(a,36)+u.width+u.height)%2e3;return{id:A(),url:e,viewport:u,timestamp:new Date,path:yu.create(`.visual-tests/responsive/${u.width}x${u.height}.png`),metadata:{browser:"chromium",os:process.platform,fullPage:!1,loadTime:r}}}detectLayoutIssues(e,u,a){return a.simulationMode?this.detectLayoutIssuesSimulation(e,u,a):this.detectLayoutIssuesHeuristic(e,u,a)}detectLayoutIssuesHeuristic(e,u,a){let t=[],r=e.toLowerCase(),i=this.hasResponsivePatterns(r);u.width<768&&(this.hasWideContentPatterns(r)&&t.push({type:"horizontal-overflow",severity:"critical",element:".wide-content, table, pre",description:"Wide content elements may cause horizontal overflow on mobile",viewport:u}),i||t.push({type:"horizontal-overflow",severity:"warning",element:".container",description:"Page may lack responsive CSS breakpoints for mobile",viewport:u})),u.width<=320&&t.push({type:"text-overflow",severity:"warning",element:"body",description:"Verify viewport meta tag is set correctly for very small screens",viewport:u}),a.checkTouchTargets&&u.hasTouch&&(this.hasInteractiveElements(r)&&t.push({type:"touch-target-size",severity:"warning",element:"button, a, input",description:`Touch targets should be at least ${a.minTouchTargetSize}px for accessibility`,viewport:u}),u.isMobile&&this.hasNavigationElements(r)&&t.push({type:"touch-target-size",severity:"info",element:"nav a",description:"Navigation links may be too small for touch on mobile devices",viewport:u})),u.isMobile&&a.minFontSize>0&&this.hasDataDensePatterns(r)&&t.push({type:"font-size-too-small",severity:"warning",element:".data, .table, .form-label",description:`Font size may be below ${a.minFontSize}px on mobile`,viewport:u}),this.hasImagePatterns(r)&&(u.deviceScaleFactor>1&&t.push({type:"image-not-responsive",severity:"info",element:"img",description:"Verify images use srcset for high-DPI displays",viewport:u}),u.width<480&&t.push({type:"image-not-responsive",severity:"info",element:"img",description:"Verify images are resized for mobile to reduce bandwidth",viewport:u}));let n=this.findNearestBreakpoint(u.width,a.breakpoints);return n.gap>200&&t.push({type:"hidden-content",severity:"info",element:"body",description:`Viewport ${u.width}px is ${n.gap}px from nearest breakpoint (${n.value}px)`,viewport:u}),this.hasOverlapRiskPatterns(r)&&u.width<1024&&t.push({type:"overlapping-elements",severity:"warning",element:".positioned, .absolute, .fixed",description:"Positioned elements may overlap on smaller screens",viewport:u}),t}hasResponsivePatterns(e){return e.includes("mobile")||e.includes("responsive")||e.includes("bootstrap")||e.includes("tailwind")||e.includes("material")||e.includes("foundation")}hasWideContentPatterns(e){return e.includes("table")||e.includes("data")||e.includes("report")||e.includes("code")||e.includes("pre")||e.includes("spreadsheet")}hasInteractiveElements(e){return e.includes("form")||e.includes("button")||e.includes("input")||e.includes("select")||e.includes("click")||e.includes("action")}hasNavigationElements(e){return e.includes("nav")||e.includes("menu")||e.includes("header")||e.includes("sidebar")||e.includes("footer")||e.includes("breadcrumb")}hasDataDensePatterns(e){return e.includes("dashboard")||e.includes("analytics")||e.includes("report")||e.includes("table")||e.includes("stats")||e.includes("metrics")}hasImagePatterns(e){return e.includes("gallery")||e.includes("photo")||e.includes("image")||e.includes("media")||e.includes("portfolio")||e.includes("hero")}hasOverlapRiskPatterns(e){return e.includes("modal")||e.includes("overlay")||e.includes("tooltip")||e.includes("dropdown")||e.includes("popup")||e.includes("float")}findNearestBreakpoint(e,u){let a=u[0]||0,t=Math.abs(e-a);for(let r of u){let i=Math.abs(e-r);i<t&&(t=i,a=r)}return{value:a,gap:t}}detectLayoutIssuesSimulation(e,u,a){let t=[],r=this.hashUrl(e),i=parseInt(r,36),n=(i+u.width)%100/100;u.width<768&&n<.2&&t.push({type:"horizontal-overflow",severity:"critical",element:".container",description:"Content overflows horizontally causing horizontal scroll",viewport:u});let o=(i+u.width+100)%100/100;u.width<480&&o<.15&&t.push({type:"text-overflow",severity:"warning",element:".long-text",description:"Text content is truncated or overflows container",viewport:u});let l=(i+u.width+200)%100/100;a.checkTouchTargets&&u.isMobile&&l<.25&&t.push({type:"touch-target-size",severity:"warning",element:".small-button",description:`Touch target is smaller than ${a.minTouchTargetSize}px minimum`,viewport:u});let c=(i+u.width+300)%100/100;return u.isMobile&&c<.1&&t.push({type:"font-size-too-small",severity:"warning",element:".fine-print",description:`Font size is below ${a.minFontSize}px minimum for readability`,viewport:u}),(i+u.width+400)%100/100<.15&&t.push({type:"image-not-responsive",severity:"info",element:"img.hero-image",description:"Image does not scale properly for viewport width",viewport:u}),t}detectBreakpointIssues(e,u,a){if(!a.simulationMode)return[];let t=[],r=this.hashUrl(e),i=parseInt(r,36),n=[...u].sort((o,l)=>o.viewport.width-l.viewport.width);for(let o=0;o<n.length-1;o++){let l=n[o],c=n[o+1],E=a.breakpoints.find(d=>d>l.viewport.width&&d<c.viewport.width);E&&(i+E+o*100)%100/100<.2&&t.push({breakpoint:E,description:"Layout shifts abruptly at this breakpoint",affectedElements:[".navigation",".sidebar"],suggestion:"Consider adding intermediate styles or adjusting breakpoint"})}return t}calculateLayoutScore(e,u){let t=u.filter(o=>o.severity==="critical").length*15,r=u.filter(o=>o.severity==="warning").length*5,i=u.filter(o=>o.severity==="info").length*1,n=e.every(o=>o.passed)?5:0;return Math.max(0,100-t-r-i+n)}generateRecommendations(e,u){let a=[],t=new Map;for(let r of e){let i=t.get(r.type)||[];t.set(r.type,[...i,r])}return t.has("horizontal-overflow")&&a.push("Use CSS overflow-x: hidden or adjust element widths to prevent horizontal scrolling"),t.has("touch-target-size")&&a.push("Increase touch target sizes to at least 44x44 pixels for better mobile usability"),t.has("font-size-too-small")&&a.push("Use relative font units (rem/em) and ensure minimum 16px base font size on mobile"),t.has("image-not-responsive")&&a.push("Use srcset and sizes attributes for responsive images, or CSS max-width: 100%"),u.length>0&&a.push("Review CSS media queries to ensure smooth transitions between breakpoints"),a}calculateStructuralDiff(e,u){let a=Math.abs(e.viewport.width-u.viewport.width),t=Math.abs(e.viewport.height-u.viewport.height),r=Math.min(50,(a+t)/20);return{baselineId:e.id,comparisonId:u.id,diffPercentage:r,diffPixels:Math.floor(r*1e3),regions:[],status:r<10?"acceptable":"changed"}}findContentBreaks(e){let u=[],a=this.hashUrl(e),t=parseInt(a.substring(0,6),36),r=[375,540,768,992,1200,1400],i=e.includes("shop")||e.includes("product")||e.includes("cart"),n=e.includes("dashboard")||e.includes("admin")||e.includes("panel"),o=e.includes("blog")||e.includes("article")||e.includes("news");for(let l=0;l<r.length;l++){let c=r[l],E=(t+l*100+c)%100,d,D,h;if(i?(d=40,D=[".product-grid",".cart-items",".checkout-form",".filters"],h="Product grid layout adjusts for viewport"):n?(d=50,D=[".sidebar",".dashboard-cards",".data-table",".nav-menu"],h="Dashboard layout reorganizes for smaller screens"):o?(d=60,D=[".article-content",".sidebar-widgets",".comments"],h="Content width and sidebar visibility changes"):(d=55,D=[".container",".grid",".navigation",".footer"],h="Content layout changes significantly"),E<d){let C=Math.min(D.length,1+Math.floor((t+c)%D.length)),y=D.slice(0,C);u.push({width:c,reason:h,affectedElements:y})}}return u}hashUrl(e){let u=0;for(let a=0;a<e.length;a++){let t=e.charCodeAt(a);u=(u<<5)-u+t,u=u&u}return Math.abs(u).toString(36)}suggestBreakpoints(e){let u=new Set;for(let t of e){let r=Math.round(t.width/100)*100;u.add(r)}let a=[576,768,992,1200,1400];for(let t of a)Array.from(u).some(r=>Math.abs(r-t)<50)||u.add(t);return Array.from(u).sort((t,r)=>t-r)}calculateBreakpointCoverage(e,u){if(u.length===0)return 100;let a=0;for(let t of u)e.some(r=>Math.abs(r-t.width)<50)&&a++;return Math.round(a/u.length*100)}async storeResult(e){let u=A();await this.memory.set(`visual-accessibility:responsive:${u}`,e,{namespace:"visual-accessibility",persist:!0})}};cu();var b2u={stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4,nSteps:5,entropyCoeff:.01,valueLossCoeff:.5},Hi=class extends Eu{actor;critic;a2cConfig;actions=[];constructor(e={}){super("a2c","actor-critic"),this.a2cConfig={...b2u,...e},this.initializeActions(),this.actor=new $({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.critic=new $({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate})}async predict(e){this.initialized||await this.initialize();let u=this.prepareState(e),a=this.actor.forward(u),t=Cu.forward(a),r=this.sampleAction(t),i=this.actions[r],n=this.critic.forward(u)[0],o=Math.max(.3,Math.min(1,t[r]+.4));return{action:i,confidence:o,value:n,reasoning:`A2C (${this.a2cConfig.numWorkers} workers): ${i.type}`}}async trainCore(e){let u=this.distributeToWorkers(e),a=0,t=0;for(let[r,i]of Object.entries(u)){if(i.length===0)continue;let n=this.calculateReturns(i),o=this.calculateAdvantages(i,n);for(let l=0;l<i.length;l++){let c=i[l],E=this.prepareState(c.state),d=this.actionToIndex(c.action),D=o[l],h=this.actor.forward(E),C=Cu.forward(h),x=-Math.log(C[d]+1e-10)*D,b=this.calculateEntropy(C),R=this.a2cConfig.entropyCoeff*b,w=new Float32Array(C.length);for(let eu=0;eu<w.length;eu++)eu===d?w[eu]=-D*(1-C[eu]):w[eu]=D*C[eu];this.actor.backward(w);for(let eu of this.actor.layers)eu.update(this.config.learningRate*.1);let P=this.critic.forward(E)[0],V=n[l],X=(P-V)**2,Bu=new Float32Array([V]);this.critic.train(E,Bu,new xu),a+=Math.abs(x-R),t+=X}}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((r,i)=>r+i,0)/this.rewardHistory.length,loss:(a+t)/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 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(e){let u={};for(let a=0;a<this.a2cConfig.numWorkers;a++)u[a]=[];return e.forEach((a,t)=>{let r=t%this.a2cConfig.numWorkers;u[r].push(a)}),u}calculateReturns(e){let u=[],a=0;for(let t=e.length-1;t>=0;t--)a=e[t].reward+this.config.discountFactor*a,u.unshift(a);return u}calculateAdvantages(e,u){return e.map((a,t)=>{let r=this.prepareState(a.state),i=this.critic.forward(r)[0];return u[t]-i})}prepareState(e){let u=e.features.slice(0,this.a2cConfig.stateSize);for(;u.length<this.a2cConfig.stateSize;)u.push(0);let a=Math.max(...u.map(Math.abs));if(a>0)for(let t=0;t<u.length;t++)u[t]/=a;return new Float32Array(u)}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 $({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.critic=new $({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate})}actionToIndex(e){let u=`${e.type}:${JSON.stringify(e.value)}`;for(let a=0;a<this.actions.length;a++)if(`${this.actions[a].type}:${JSON.stringify(this.actions[a].value)}`===u)return a;return 0}sampleAction(e){if(K()<this.config.explorationRate)return Du(0,this.actions.length);let u=K(),a=0;for(let t=0;t<e.length;t++)if(a+=e[t],u<=a)return t;return this.argmax(e)}argmax(e){let u=0,a=e[0];for(let t=1;t<e.length;t++)e[t]>a&&(a=e[t],u=t);return u}calculateEntropy(e){let u=0;for(let a=0;a<e.length;a++)e[a]>0&&(u-=e[a]*Math.log(e[a]));return u}async exportCustomData(){return{actor:this.actor.getParameters(),critic:this.critic.getParameters(),a2cConfig:this.a2cConfig}}async importCustomData(e){e.actor&&this.actor.setParameters(e.actor),e.critic&&this.critic.setParameters(e.critic),e.a2cConfig&&(this.a2cConfig={...this.a2cConfig,...e.a2cConfig}),this.initialized=!0}async resetAlgorithm(){this.actor=new $({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.actorHiddenLayers,this.a2cConfig.actionSize],activations:Array(this.a2cConfig.actorHiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate}),this.critic=new $({layerSizes:[this.a2cConfig.stateSize,...this.a2cConfig.criticHiddenLayers,1],activations:Array(this.a2cConfig.criticHiddenLayers.length).fill(new _).concat([new W]),learningRate:this.config.learningRate})}};var B2u={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},Iu=B.create("visual-accessibility"),Gi=class extends Y{constructor(u,a,t,r={},i={},n={},o={}){let l={...B2u,...r};super(u,"visual-accessibility",l,{verifyFindingTypes:["accessibility-violation","visual-regression","wcag-non-compliance"]});this.memory=a;this.agentCoordinator=t;this.visualTester=Ni(a,i),this.accessibilityTester=new V0(a,n),this.responsiveTester=new O0(a,o)}visualTester;accessibilityTester;responsiveTester;a2cAlgorithm;flashAttention;async onInitialize(){if(this.config.enableA2C)try{this.a2cAlgorithm=new Hi({stateSize:10,actionSize:5,actorHiddenLayers:[64,64],criticHiddenLayers:[64,64],numWorkers:4}),Iu.info("A2C algorithm created successfully")}catch(u){throw Iu.error("Failed to create A2C:",u instanceof Error?u:void 0),new Error(`A2C creation failed: ${k(u)}`)}if(this.config.enableFlashAttention)try{this.flashAttention=await Ku("test-similarity"),Iu.info("QEFlashAttention initialized successfully")}catch(u){throw Iu.error("Failed to initialize Flash Attention:",u instanceof Error?u:void 0),new Error(`Flash Attention initialization failed: ${k(u)}`)}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(u,a){let t=A();try{if(this.startWorkflow(t,"visual"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Iu.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Operation paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn visual testing agents"));let r=await this.spawnVisualTestingAgent(t);if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);this.addAgentToWorkflow(t,r.value);let i=[],n=0,o=0,l=0,c=[];for(let y of u)for(let x of a)c.push({url:y,viewport:x});if(this.config.enableA2C&&c.length>1){let y={urgency:5,availableResources:80,historicalFailureRate:.1},x=await this.prioritizeVisualTests(c.map(b=>({...b,priority:5})),y);x.success&&(c=x.value.orderedTests.map(b=>({url:b.url,viewport:b.viewport})),Iu.info(`[visual-accessibility] Using ${x.value.strategy} strategy for visual test order (confidence: ${x.value.confidence.toFixed(2)})`))}let E=c.length,d=0;for(let{url:y,viewport:x}of c){let b=await this.visualTester.captureScreenshot(y,{viewport:x});if(!b.success){o++,i.push({url:y,viewport:x,status:"failed",screenshot:{id:"",url:y,viewport:x,timestamp:new Date,path:yu.create("error-placeholder.png"),metadata:{browser:"",os:"",fullPage:!1,loadTime:0}}});continue}let R=b.value,w=await this.visualTester.getBaseline(y,x);if(!w)await this.visualTester.setBaseline(R),l++,i.push({url:y,viewport:x,status:"new",screenshot:R});else{let P=await this.visualTester.compare(R,w.id);if(P.success){let V=P.value,X=V.status==="identical"||V.status==="acceptable"?"passed":"failed";X==="passed"?n++:o++,i.push({url:y,viewport:x,status:X,diff:V,screenshot:R}),X==="failed"&&this.config.publishEvents&&await this.publishVisualRegressionEvent(y,x,V)}else o++,i.push({url:y,viewport:x,status:"failed",screenshot:R})}d++,this.updateWorkflowProgress(t,d/E*100)}let D=this.workflows.get(t)?.startedAt.getTime()??Date.now(),h=Date.now()-D,C={totalTests:i.length,passed:n,failed:o,newBaselines:l,results:i,duration:h};return this.completeWorkflow(t),await this.agentCoordinator.stop(r.value),p(C)}catch(r){let i=g(r);return this.failWorkflow(t,i.message),{success:!1,error:i}}}async runAccessibilityAudit(u,a){let t=A();try{if(this.startWorkflow(t,"accessibility"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Iu.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Operation paused: topology is in critical state"));let r=await this.spawnAccessibilityTestingAgent(t,a);if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);this.addAgentToWorkflow(t,r.value);let i=[],n=0,o=0,l=0;for(let D=0;D<u.length;D++){let h=u[D],C=await this.accessibilityTester.audit(h,{wcagLevel:a});if(C.success){let y=C.value;i.push(y),n+=y.violations.length,o+=y.violations.filter(x=>x.impact==="critical").length,y.violations.length===0&&l++,this.config.publishEvents&&await this.publishAccessibilityAuditEvent(y)}this.updateWorkflowProgress(t,(D+1)/u.length*100)}let c=i.length>0?Math.round(i.reduce((D,h)=>D+h.score,0)/i.length):0,E=this.identifyTopIssues(i),d={totalUrls:u.length,passingUrls:l,totalViolations:n,criticalViolations:o,averageScore:c,reports:i,topIssues:E};return this.completeWorkflow(t),await this.agentCoordinator.stop(r.value),p(d)}catch(r){let i=g(r);return this.failWorkflow(t,i.message),{success:!1,error:i}}}async approveVisualChanges(u,a){try{for(let t of u){let r=await this.memory.get(`visual-accessibility:diff:${t}`);if(!r)continue;let i=await this.memory.get(`visual-accessibility:screenshot:${r.comparisonId}`);i&&(await this.visualTester.setBaseline(i),this.config.publishEvents&&await this.publishBaselineUpdatedEvent(i,a))}return p(void 0)}catch(t){return m(g(t))}}async generateRemediationPlan(u){try{let a=[];for(let n of u){let o=this.createRemediation(n);a.push(o)}let t={trivial:0,minor:1,moderate:2,major:3};a.sort((n,o)=>t[n.effort]-t[o.effort]);let r=this.calculateTotalEffort(a),i={violations:a,totalEffort:r,prioritizedOrder:a.map(n=>n.violationId)};return p(i)}catch(a){return m(g(a))}}async getVisualTestingStatus(){try{let u=await this.memory.search("visual-accessibility:baseline:*",1e3),a=u.length,t=await this.memory.search("visual-accessibility:diff:*",1e3),r=0;for(let D of t){let h=await this.memory.get(D);h&&(h.status==="changed"||h.status==="failed")&&r++}let n=Array.from(this.workflows.values()).filter(D=>D.type==="visual"&&D.status==="completed").sort((D,h)=>(h.completedAt?.getTime()??0)-(D.completedAt?.getTime()??0))[0]?.completedAt??new Date,o=Array.from(this.workflows.values()).filter(D=>D.type==="visual").length,l=Array.from(this.workflows.values()).filter(D=>D.type==="visual"&&D.status==="failed").length,c=o>0?l/o:0,E=await this.calculateViewportCoverage(u);return p({baselineCount:a,pendingReviews:r,lastTestRun:n,failureRate:c,coverageByViewport:E})}catch(u){return m(g(u))}}async runVisualRegression(u){let a=A();try{if(this.startWorkflow(a,"visual"),!this.agentCoordinator.canSpawn())return this.failWorkflow(a,"Agent limit reached"),m(new Error("Agent limit reached, cannot spawn visual testing agents"));let t=await this.spawnVisualTestingAgent(a);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=[],i={width:1280,height:720,deviceScaleFactor:1,isMobile:!1,hasTouch:!1},n=u.viewports??[i];for(let o of u.pages)for(let l of n){let c=await this.visualTester.captureScreenshot(`${u.baselineUrl}${o}`,{viewport:l}),E=await this.visualTester.captureScreenshot(`${u.compareUrl}${o}`,{viewport:l});if(c.success&&E.success){let d=await this.visualTester.compare(E.value,c.value.id);d.success?r.push({page:o,diffPercentage:d.value.diffPercentage,passed:d.value.status==="identical"||d.value.status==="acceptable"}):r.push({page:o,diffPercentage:100,passed:!1})}else r.push({page:o,diffPercentage:100,passed:!1})}return this.completeWorkflow(a),await this.agentCoordinator.stop(t.value),p({differences:r})}catch(t){let r=g(t);return this.failWorkflow(a,r.message),{success:!1,error:r}}}async runAccessibilityAuditSingle(u){let a=await this.runAccessibilityAudit([u.url],u.wcagLevel);if(!a.success)return m(a.error);let t=a.value.reports[0];return t?p({violations:t.violations,wcagLevel:t.wcagLevel,score:t.score}):p({violations:[],wcagLevel:u.wcagLevel,score:100})}async compareScreenshots(u){try{let a=await this.memory.get(`visual-accessibility:screenshot:${u.baseline}`),t=await this.memory.get(`visual-accessibility:screenshot:${u.current}`);if(a&&t){let r=await this.visualTester.compare(t,a.id);if(r.success){let i=u.threshold??.1;return p({diffPercentage:r.value.diffPercentage,passed:r.value.diffPercentage<=i*100,diffImagePath:r.value.diffImagePath?.value})}}return p({diffPercentage:0,passed:!0})}catch(a){return m(g(a))}}async analyzeColorContrast(u){try{let a=u.wcagLevel??"AA",t=await this.accessibilityTester.audit(u.url,{wcagLevel:a});if(!t.success)return m(t.error);let i=t.value.violations.filter(n=>n.id.includes("color-contrast")||n.id.includes("contrast")).flatMap(n=>n.nodes.map(o=>({element:o.target.join(" "),foreground:"#000000",background:"#ffffff",ratio:1,required:a==="AAA"?7:4.5})));return p({issues:i})}catch(a){return m(g(a))}}async testResponsiveDesign(u){try{let a=[];for(let t of u.viewports){let r={width:t.width,height:t.height,deviceScaleFactor:1,isMobile:t.width<768,hasTouch:t.width<1024},i=await this.visualTester.captureScreenshot(u.url,{viewport:r}),n=t.name??`${t.width}x${t.height}`,o=[];i.success||o.push(`Failed to capture screenshot: ${i.error.message}`),a.push({viewport:n,passed:o.length===0,issues:o})}return p({viewportResults:a})}catch(a){return m(g(a))}}async spawnVisualTestingAgent(u){let a={name:`visual-tester-${u.slice(0,8)}`,domain:"visual-accessibility",type:"tester",capabilities:["visual-testing","screenshot-capture","image-diff"],config:{workflowId:u}};return this.agentCoordinator.spawn(a)}async spawnAccessibilityTestingAgent(u,a){let t={name:`a11y-tester-${u.slice(0,8)}`,domain:"visual-accessibility",type:"analyzer",capabilities:["accessibility-audit","wcag-validation",a],config:{workflowId:u,wcagLevel:a}};return this.agentCoordinator.spawn(t)}async calculateViewportCoverage(u){let a=new Map([["mobile",0],["tablet",0],["desktop",0]]),t=new Set;for(let n of u){let o=n.match(/baseline:([^_]+)_(\d+)x(\d+)_/);if(o){let[,l,c]=o,E=parseInt(c,10);t.add(l);let d=this.categorizeViewport(E);a.set(d,(a.get(d)||0)+1)}}let r=t.size||1,i=new Map;for(let[n,o]of a){let l=Math.min(100,Math.round(o/r*100));i.set(n,l)}return u.length===0?new Map([["mobile",0],["tablet",0],["desktop",0]]):i}categorizeViewport(u){return u<=480?"mobile":u<=1024?"tablet":"desktop"}async publishVisualRegressionEvent(u,a,t){let r={id:A(),type:"visual-accessibility.VisualRegressionDetected",timestamp:new Date,source:"visual-accessibility",payload:{url:u,viewport:a,diffPercentage:t.diffPercentage,diffImagePath:t.diffImagePath?.value}};await this.eventBus.publish(r)}async publishAccessibilityAuditEvent(u){let a={id:A(),type:"visual-accessibility.AccessibilityAuditCompleted",timestamp:new Date,source:"visual-accessibility",payload:{url:u.url,violations:u.violations.length,score:u.score,wcagLevel:u.wcagLevel}};await this.eventBus.publish(a)}async publishBaselineUpdatedEvent(u,a){let t={id:A(),type:"visual-accessibility.BaselineUpdated",timestamp:new Date,source:"visual-accessibility",payload:{screenshotId:u.id,url:u.url,viewport:u.viewport,reason:a}};await this.eventBus.publish(t)}identifyTopIssues(u){let a=new Map;for(let t of u)for(let r of t.violations){let i=a.get(r.id);i?(i.occurrences++,i.affectedUrls.includes(t.url)||i.affectedUrls.push(t.url)):a.set(r.id,{ruleId:r.id,description:r.description,occurrences:1,impact:r.impact,affectedUrls:[t.url]})}return Array.from(a.values()).sort((t,r)=>r.occurrences-t.occurrences).slice(0,10)}createRemediation(u){let a=this.estimateEffort(u);return{violationId:u.id,description:u.description,fix:u.help,codeExample:this.generateCodeExample(u),effort:a,wcagReference:u.wcagCriteria[0]?.id??""}}estimateEffort(u){let a=u.nodes.length;return u.impact==="minor"&&a<=3?"trivial":u.impact==="minor"||a<=5?"minor":u.impact==="serious"&&a<=10?"moderate":"major"}generateCodeExample(u){return u.id.includes("alt")?'<img src="..." alt="Descriptive text for the image">':u.id.includes("label")?`<label for="input-id">Label text</label>
3008
3008
  <input id="input-id" type="text">`:u.id.includes("button")?'<button aria-label="Descriptive action">Icon</button>':"<!-- See WCAG guidelines for specific implementation -->"}calculateTotalEffort(u){let a={trivial:1,minor:2,moderate:4,major:8},t=u.reduce((r,i)=>r+a[i.effort],0);return t<=5?"trivial":t<=15?"minor":t<=40?"moderate":"major"}async prioritizeVisualTests(u,a){if(!this.a2cAlgorithm||!this.config.enableA2C)return p({orderedTests:u.map(t=>({...t,priority:t.priority??5,reason:"default"})),strategy:"default",confidence:1});if(u.length===0)return p({orderedTests:[],strategy:"empty",confidence:1});try{let t={id:`visual-priority-${Date.now()}`,features:[a.urgency/10,a.availableResources/100,a.historicalFailureRate,u.length/100,u.filter(c=>c.viewport.width<=480).length/Math.max(1,u.length),u.filter(c=>c.viewport.width>1024).length/Math.max(1,u.length),u.filter(c=>(c.priority??5)>7).length/Math.max(1,u.length),u.filter(c=>c.url.includes("dashboard")).length/Math.max(1,u.length),u.filter(c=>c.url.includes("checkout")).length/Math.max(1,u.length),u.filter(c=>c.url.includes("login")).length/Math.max(1,u.length)]},r=await this.a2cAlgorithm.predict(t),i=u.map(c=>({...c,priority:c.priority??5,reason:"default"})),n="default";switch(r.action.type){case"coordinate":if(r.action.value==="parallel")i.sort((D,h)=>D.viewport.width-h.viewport.width),i=i.map(D=>({...D,priority:10-Math.floor(D.viewport.width/200),reason:"parallel-viewport-order"})),n="parallel-viewport-order";else if(r.action.value==="sequential"){let D=["checkout","payment","login"];i.sort((h,C)=>{let y=D.some(b=>h.url.includes(b))?1:0;return(D.some(b=>C.url.includes(b))?1:0)-y}),i=i.map(h=>({...h,priority:D.some(C=>h.url.includes(C))?9:5,reason:"sequential-critical-url"})),n="sequential-critical-url"}break;case"allocate":let c=typeof r.action.value=="object"?r.action.value.agents??2:2,E=Math.ceil(i.length/c);i=i.map((D,h)=>({...D,priority:10-Math.floor(h/E),reason:`allocate-agent-${Math.floor(h/E)}`})),n="allocate-by-agent";break;case"rebalance":let d=new Map;for(let D of i)d.set(D.viewport.width,(d.get(D.viewport.width)||0)+1);i.sort((D,h)=>(d.get(D.viewport.width)||0)-(d.get(h.viewport.width)||0)),i=i.map(D=>({...D,priority:10-(d.get(D.viewport.width)||0),reason:"rebalance-viewport-coverage"})),n="rebalance-viewport-coverage";break;default:break}let o=await this.calculatePrioritizationReward(i,a),l=r.action;return await this.a2cAlgorithm.train({state:t,action:l,reward:o,nextState:t,done:!0}),Iu.info(`[visual-accessibility] A2C prioritized ${u.length} visual tests using ${n} strategy (confidence: ${r.confidence.toFixed(2)})`),p({orderedTests:i,strategy:n,confidence:r.confidence})}catch(t){return Iu.error("A2C prioritization failed:",t instanceof Error?t:void 0),p({orderedTests:u.map(r=>({...r,priority:r.priority??5,reason:"fallback"})),strategy:"fallback",confidence:.5})}}async calculatePrioritizationReward(u,a){let t=.5,r=u.slice(0,Math.ceil(u.length/4)),i=r.filter(o=>["checkout","payment","login","dashboard"].some(l=>o.url.includes(l))).length;t+=Math.min(.3,i/r.length);let n=new Set(u.map(o=>`${o.viewport.width}x${o.viewport.height}`));return t+=Math.min(.2,n.size/10),a.availableResources<30&&u.length>50&&(t-=.1),Math.max(0,Math.min(1,t))}async findSimilarImages(u,a,t=5){if(!this.flashAttention||!this.config.enableFlashAttention)return this.cosineSimilarityFallback(u,a,t);try{return(await this.flashAttention.computeTestSimilarity(u,a,t)).map(i=>({index:i.index,similarity:i.similarity,imagePath:`image-${i.index}.png`}))}catch(r){return Iu.error("Flash Attention similarity search failed:",r instanceof Error?r:void 0),this.cosineSimilarityFallback(u,a,t)}}cosineSimilarityFallback(u,a,t){let r=[];for(let i=0;i<a.length;i++){let o=(ce(u,a[i])+1)/2;r.push({index:i,similarity:o,imagePath:`image-${i}.png`})}return r.sort((i,n)=>n.similarity-i.similarity),r.slice(0,t)}async storeVisualPattern(u,a,t,r){if(!(!this.flashAttention||!this.config.enableFlashAttention))try{let i=this.createVisualEmbedding(u,a,t,r);await this.memory.set(`visual-accessibility:embedding:${u}:${a.width}x${a.height}`,{embedding:i,url:u,viewport:a,diffScore:t,passed:r,timestamp:new Date},{namespace:"visual-accessibility",persist:!0}),Iu.info(`Stored visual pattern for ${u} at ${a.width}x${a.height}`)}catch(i){Iu.error("Failed to store visual pattern:",i instanceof Error?i:void 0)}}createVisualEmbedding(u,a,t,r){let i=[],n=this.hashString(u);for(let c=0;c<100;c++)i.push((n>>c%32&1)===1?1:0);i.push(a.width/2e3),i.push(a.height/2e3),i.push(a.deviceScaleFactor/3),i.push(a.isMobile?1:0),i.push(a.hasTouch?1:0),i.push(a.width<=480?1:0),i.push(a.width<=1024&&a.width>480?1:0),i.push(a.width>1024?1:0);let o=a.height>a.width;i.push(o?1:0),i.push(o?0:1),i.push(t/100),i.push(r?1:0),i.push(t>10?1:0),i.push(t>50?1:0);let l=this.extractPathFeatures(u);return i.push(...l.slice(0,270)),new Float32Array(i.slice(0,384))}hashString(u){let a=0;for(let t=0;t<u.length;t++)a=(a<<5)-a+u.charCodeAt(t),a=a|0;return Math.abs(a)}extractPathFeatures(u){let a=[],t=new URL(u).pathname,r=["dashboard","checkout","login","profile","settings","api","admin","search"];for(let n of r)a.push(t.includes(n)?1:0);let i=t.split("/").filter(Boolean).length;for(a.push(i/10),a.push(u.includes("?")?1:0),a.push(u.startsWith("https://")?1:0);a.length<270;)a.push(0);return a}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.FileChanged",this.handleFileChanged.bind(this)),this.eventBus.subscribe("ci-cd.DeploymentCompleted",this.handleDeploymentCompleted.bind(this))}async handleFileChanged(u){}async handleDeploymentCompleted(u){}async loadWorkflowState(){let u=await this.memory.get("visual-accessibility:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("visual-accessibility:coordinator:workflows",u,{namespace:"visual-accessibility",persist:!0})}requiresConsensus(u){return this.consensusMixin.requiresConsensus(u)}async verifyFinding(u){return this.consensusMixin.verifyFinding(u)}async verifyAccessibilityViolation(u,a){let t=O({id:A(),type:"accessibility-violation",confidence:a,description:`Accessibility violation: ${u.description} (${u.impact} impact)`,payload:u,detectedBy:"visual-accessibility-coordinator",severity:u.impact==="critical"?"critical":u.impact==="serious"?"high":u.impact==="moderate"?"medium":"low"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return!!(r.success&&r.value.verdict==="verified")}return!0}async verifyVisualRegression(u,a){let t=O({id:A(),type:"visual-regression",confidence:a,description:`Visual regression detected at ${u.url} (${u.viewport.width}x${u.viewport.height}): ${u.diffPercentage.toFixed(2)}% difference`,payload:u,detectedBy:"visual-accessibility-coordinator",severity:u.diffPercentage>20?"critical":u.diffPercentage>10?"high":u.diffPercentage>5?"medium":"low"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return!!(r.success&&r.value.verdict==="verified")}return!0}onTopologyHealthChange(u){return this.minCutMixin.onTopologyHealthChange(u)}};S();var Wl=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.urls,t=u.viewports;return!a||a.length===0?m(new Error("Invalid run-visual-tests payload: missing urls")):this.coordinator.runVisualTests(a,t||[{width:1920,height:1080,deviceScaleFactor:1,isMobile:!1,hasTouch:!1}])}],["run-accessibility-audit",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.urls,t=u.level||"AA";return!a||a.length===0?m(new Error("Invalid run-accessibility-audit payload: missing urls")):this.coordinator.runAccessibilityAudit(a,t)}],["capture-screenshot",async u=>{if(!this.visualTester)return m(new Error("Visual tester not initialized"));let a=u.url;return a?this.visualTester.captureScreenshot(a,u.options):m(new Error("Invalid capture-screenshot payload: missing url"))}],["test-responsiveness",async u=>{if(!this.responsiveTester)return m(new Error("Responsive tester not initialized"));let a=u.url;return a?this.responsiveTester.testResponsiveness(a,u.options):m(new Error("Invalid test-responsiveness payload: missing url"))}],["validate-wcag",async u=>{if(!this.accessibilityTester)return m(new Error("Accessibility tester not initialized"));let a=u.url;if(!a)return m(new Error("Invalid validate-wcag payload: missing url"));let t=u.level||"AA";return this.accessibilityTester.validateWCAGLevel(a,t)}]])}async onInitialize(){this.visualTester=Ni(this.memory,this.pluginConfig.visualTester),this.accessibilityTester=new V0(this.memory,this.pluginConfig.accessibilityTester),this.responsiveTester=new O0(this.memory,this.pluginConfig.responsiveTester),this.coordinator=new Gi(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"ci-cd.DeploymentCompleted":await this.handleDeploymentCompleted(u);break;case"code-intelligence.FileChanged":await this.handleFileChanged(u);break;case"quality-assessment.QualityGateTriggered":await this.handleQualityGateTriggered(u);break;default:break}}async runVisualTests(u,a){this.ensureInitialized();try{let t=await this.coordinator.runVisualTests(u,a);return t.success?this.trackSuccessfulTest("visual",t.value.totalTests):this.trackFailedTest(t.error),t}catch(t){return this.handleError(t)}}async runAccessibilityAudit(u,a){this.ensureInitialized();try{let t=await this.coordinator.runAccessibilityAudit(u,a);return t.success?this.trackSuccessfulTest("accessibility",t.value.totalUrls):this.trackFailedTest(t.error),t}catch(t){return this.handleError(t)}}async approveVisualChanges(u,a){this.ensureInitialized();try{return await this.coordinator.approveVisualChanges(u,a)}catch(t){return this.handleError(t)}}async generateRemediationPlan(u){this.ensureInitialized();try{return await this.coordinator.generateRemediationPlan(u)}catch(a){return this.handleError(a)}}async getVisualTestingStatus(){this.ensureInitialized();try{return await this.coordinator.getVisualTestingStatus()}catch(u){return this.handleError(u)}}async captureScreenshot(u,a){this.ensureInitialized();try{return await this.visualTester.captureScreenshot(u,a)}catch(t){return this.handleError(t)}}async captureElement(u,a,t){this.ensureInitialized();try{return await this.visualTester.captureElement(u,a,t)}catch(r){return this.handleError(r)}}async auditAccessibility(u,a){this.ensureInitialized();try{return await this.accessibilityTester.audit(u,a)}catch(t){return this.handleError(t)}}async checkContrast(u){this.ensureInitialized();try{return await this.accessibilityTester.checkContrast(u)}catch(a){return this.handleError(a)}}async validateWCAGLevel(u,a){this.ensureInitialized();try{return await this.accessibilityTester.validateWCAGLevel(u,a)}catch(t){return this.handleError(t)}}async checkKeyboardNavigation(u){this.ensureInitialized();try{return await this.accessibilityTester.checkKeyboardNavigation(u)}catch(a){return this.handleError(a)}}async testResponsiveness(u,a){this.ensureInitialized();try{return await this.responsiveTester.testResponsiveness(u,a)}catch(t){return this.handleError(t)}}async analyzeBreakpoints(u){this.ensureInitialized();try{return await this.responsiveTester.analyzeBreakpoints(u)}catch(a){return this.handleError(a)}}async handleDeploymentCompleted(u){let a=u.payload;await this.memory.set(`visual-accessibility:deployment:${Date.now()}`,a,{namespace:"visual-accessibility",ttl:3600})}async handleFileChanged(u){let a=u.payload;(a.file.endsWith(".css")||a.file.endsWith(".scss"))&&await this.memory.set(`visual-accessibility:style-change:${Date.now()}`,a,{namespace:"visual-accessibility",ttl:3600})}async handleQualityGateTriggered(u){let a=u.payload;a.checks.includes("accessibility")&&await this.memory.set(`visual-accessibility:quality-gate:${a.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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulTest(u,a){let t=this.getHealth();this.updateHealth({agents:{...t.agents,total:t.agents.total+1,idle:t.agents.idle+1},lastActivity:new Date})}trackFailedTest(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}registerWorkflowActions(u){if(!this._initialized)throw new Error("VisualAccessibilityPlugin must be initialized before registering workflow actions");u.registerAction("visual-accessibility","runVisualTest",async(a,t)=>{try{this.ensureInitialized();let r=this.extractUrls(a);if(r.length===0)return m(new Error('No URLs provided for visual test. Provide "url" or "urls" parameter.'));let i=this.extractViewports(a),n=await this.coordinator.runVisualTests(r,i);return n.success?p({passed:n.value.passed,failed:n.value.failed,totalTests:n.value.totalTests,newBaselines:n.value.newBaselines,duration:n.value.duration,results:n.value.results.map(o=>({url:o.url,viewport:`${o.viewport.width}x${o.viewport.height}`,status:o.status,diffPercentage:o.diff?.diffPercentage}))}):m(n.error)}catch(r){return m(g(r))}}),u.registerAction("visual-accessibility","runAccessibilityTest",async(a,t)=>{try{this.ensureInitialized();let r=this.extractUrls(a);if(r.length===0)return m(new Error('No URLs provided for accessibility test. Provide "url" or "urls" parameter.'));let i=this.extractWcagLevel(a),n=await this.coordinator.runAccessibilityAudit(r,i);return n.success?p({totalUrls:n.value.totalUrls,passingUrls:n.value.passingUrls,totalViolations:n.value.totalViolations,criticalViolations:n.value.criticalViolations,averageScore:n.value.averageScore,topIssues:n.value.topIssues.map(o=>({ruleId:o.ruleId,description:o.description,occurrences:o.occurrences,impact:o.impact}))}):m(n.error)}catch(r){return m(g(r))}})}extractUrls(u){return typeof u.url=="string"?[u.url]:Array.isArray(u.urls)?u.urls.filter(a=>typeof a=="string"):typeof u.target=="string"?[u.target]:[]}extractViewports(u){let a=[{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(u.viewports))return u.viewports.filter(t=>typeof t=="object"&&t!==null).map(t=>({width:typeof t.width=="number"?t.width:1920,height:typeof t.height=="number"?t.height:1080,deviceScaleFactor:typeof t.deviceScaleFactor=="number"?t.deviceScaleFactor:1,isMobile:typeof t.isMobile=="boolean"?t.isMobile:!1,hasTouch:typeof t.hasTouch=="boolean"?t.hasTouch:!1}));if(typeof u.viewport=="object"&&u.viewport!==null){let t=u.viewport;return[{width:typeof t.width=="number"?t.width:1920,height:typeof t.height=="number"?t.height:1080,deviceScaleFactor:typeof t.deviceScaleFactor=="number"?t.deviceScaleFactor:1,isMobile:typeof t.isMobile=="boolean"?t.isMobile:!1,hasTouch:typeof t.hasTouch=="boolean"?t.hasTouch:!1}]}return a}extractWcagLevel(u){let t=(u.level??u.wcagLevel??"AA").toUpperCase();return t==="A"||t==="AA"||t==="AAA"?t:"AA"}};function HE(s,e,u,a){return new Wl(s,e,u,a)}N();S();N();import*as VE from"net";import{execFile as GE}from"child_process";S();J();cu();var k2u={defaultTimeout:6e4,maxConcurrentFaults:3,enableDryRun:!0,safetyCheckInterval:5e3,autoRollbackOnFailure:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},G=B.create("chaos-resilience/chaos-engineer"),_0=class s{config;activeExperiments=new Map;activeFaults=new Map;httpClient;metricsCollector;stressWorkers=new Map;memory;llmRouter;constructor(e,u={}){this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...k2u,...u},this.httpClient=new Uu,this.metricsCollector=Us()}async createExperiment(e){try{let u=this.validateExperiment(e);if(!u.success)return m(u.error);let a=await this.analyzeExperimentWithLLM(e);return a&&G.info(`LLM Analysis:
3009
- ${a}`),await this.memory.set(`chaos:experiments:${e.id}`,e,{namespace:"chaos-resilience",persist:!0}),p(e.id)}catch(u){return m(g(u))}}async runExperiment(e){try{let u=await this.memory.get(`chaos:experiments:${e}`);if(!u)return m(new Error(`Experiment not found: ${e}`));if(this.activeExperiments.has(e))return m(new Error(`Experiment ${e} is already running`));let a=this.createExecution(u);this.activeExperiments.set(e,a);try{let t=await this.verifySteadyState(u.steadyState);if(!t.success||!t.value)return a.result.steadyStateVerified=!1,a.result.status="failed",a.result.incidents.push({type:"error",severity:"high",message:"Initial steady state verification failed",timestamp:new Date,resolved:!1}),p(this.finalizeExecution(a));a.result.steadyStateVerified=!0;for(let n of u.faults){let o=await this.injectFault(n);o.success?a.result.faultResults.push(o.value):a.result.faultResults.push({faultId:n.id,injected:!1,duration:0,affectedTargets:0,errors:[o.error.message]})}await this.collectMetricsDuringExperiment(a,u);let r=await this.verifySteadyState(u.steadyState),i=r.success?r.value:!1;a.result.hypothesisValidated=this.validateHypothesis(u.hypothesis,a.result.metrics),a.result.status=this.determineExperimentStatus(a,i);for(let n of u.faults)await this.removeFault(n.id);return p(this.finalizeExecution(a))}catch(t){return a.result.status="failed",a.result.incidents.push({type:"error",severity:"critical",message:k(t),timestamp:new Date,resolved:!1}),this.config.autoRollbackOnFailure&&(await this.rollbackExperiment(u),a.result.status="rolled-back"),p(this.finalizeExecution(a))}finally{this.activeExperiments.delete(e)}}catch(u){return m(g(u))}}async abortExperiment(e,u){try{let a=this.activeExperiments.get(e);if(!a)return m(new Error(`No active experiment found: ${e}`));a.result.status="aborted",a.result.incidents.push({type:"alert",severity:"medium",message:`Experiment aborted: ${u}`,timestamp:new Date,resolved:!0});let t=await this.memory.get(`chaos:experiments:${e}`);if(t)for(let r of t.faults)await this.removeFault(r.id);return p(void 0)}catch(a){return m(g(a))}}async verifySteadyState(e){try{let u=[];for(let t of e.probes){let r=await this.executeProbe(t);u.push(r)}let a=u.every(t=>t);return p(a)}catch(u){return m(g(u))}}async injectFault(e){try{if(this.activeFaults.size>=this.config.maxConcurrentFaults)return m(new Error(`Maximum concurrent faults (${this.config.maxConcurrentFaults}) reached`));let u=this.validateFault(e);if(!u.success)return m(u.error);let a=Date.now();if(e.probability!==void 0&&K()>e.probability)return p({faultId:e.id,injected:!1,duration:0,affectedTargets:0,errors:["Skipped due to probability check"]});let t=await this.performFaultInjection(e);return t.success?(this.activeFaults.set(e.id,e),e.duration>0&&setTimeout(()=>{this.removeFault(e.id)},e.duration),p({faultId:e.id,injected:!0,duration:Date.now()-a,affectedTargets:t.value,errors:[]})):p({faultId:e.id,injected:!1,duration:Date.now()-a,affectedTargets:0,errors:[t.error.message]})}catch(u){return m(g(u))}}async removeFault(e){try{let u=this.activeFaults.get(e);return u?(await this.performFaultRemoval(u),this.activeFaults.delete(e),p(void 0)):p(void 0)}catch(u){return m(g(u))}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(e){let u={1:"claude-3-haiku-20240307",2:"claude-sonnet-4-20250514",3:"claude-sonnet-4-20250514",4:"claude-opus-4-20250514"};return u[e]||u[2]}async analyzeExperimentWithLLM(e){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:
3009
+ ${a}`),await this.memory.set(`chaos:experiments:${e.id}`,e,{namespace:"chaos-resilience",persist:!0}),p(e.id)}catch(u){return m(g(u))}}async runExperiment(e){try{let u=await this.memory.get(`chaos:experiments:${e}`);if(!u)return m(new Error(`Experiment not found: ${e}`));if(this.activeExperiments.has(e))return m(new Error(`Experiment ${e} is already running`));let a=this.createExecution(u);this.activeExperiments.set(e,a);try{let t=await this.verifySteadyState(u.steadyState);if(!t.success||!t.value)return a.result.steadyStateVerified=!1,a.result.status="failed",a.result.incidents.push({type:"error",severity:"high",message:"Initial steady state verification failed",timestamp:new Date,resolved:!1}),p(this.finalizeExecution(a));a.result.steadyStateVerified=!0;for(let n of u.faults){let o=await this.injectFault(n);o.success?a.result.faultResults.push(o.value):a.result.faultResults.push({faultId:n.id,injected:!1,duration:0,affectedTargets:0,errors:[o.error.message]})}await this.collectMetricsDuringExperiment(a,u);let r=await this.verifySteadyState(u.steadyState),i=r.success?r.value:!1;a.result.hypothesisValidated=this.validateHypothesis(u.hypothesis,a.result.metrics),a.result.status=this.determineExperimentStatus(a,i);for(let n of u.faults)await this.removeFault(n.id);return p(this.finalizeExecution(a))}catch(t){return a.result.status="failed",a.result.incidents.push({type:"error",severity:"critical",message:k(t),timestamp:new Date,resolved:!1}),this.config.autoRollbackOnFailure&&(await this.rollbackExperiment(u),a.result.status="rolled-back"),p(this.finalizeExecution(a))}finally{this.activeExperiments.delete(e)}}catch(u){return m(g(u))}}async abortExperiment(e,u){try{let a=this.activeExperiments.get(e);if(!a)return m(new Error(`No active experiment found: ${e}`));a.result.status="aborted",a.result.incidents.push({type:"alert",severity:"medium",message:`Experiment aborted: ${u}`,timestamp:new Date,resolved:!0});let t=await this.memory.get(`chaos:experiments:${e}`);if(t)for(let r of t.faults)await this.removeFault(r.id);return p(void 0)}catch(a){return m(g(a))}}async verifySteadyState(e){try{let u=[];for(let t of e.probes){let r=await this.executeProbe(t);u.push(r)}let a=u.every(t=>t);return p(a)}catch(u){return m(g(u))}}async injectFault(e){try{if(this.activeFaults.size>=this.config.maxConcurrentFaults)return m(new Error(`Maximum concurrent faults (${this.config.maxConcurrentFaults}) reached`));let u=this.validateFault(e);if(!u.success)return m(u.error);let a=Date.now();if(e.probability!==void 0&&K()>e.probability)return p({faultId:e.id,injected:!1,duration:0,affectedTargets:0,errors:["Skipped due to probability check"]});let t=await this.performFaultInjection(e);return t.success?(this.activeFaults.set(e.id,e),e.duration>0&&setTimeout(()=>{this.removeFault(e.id)},e.duration),p({faultId:e.id,injected:!0,duration:Date.now()-a,affectedTargets:t.value,errors:[]})):p({faultId:e.id,injected:!1,duration:Date.now()-a,affectedTargets:0,errors:[t.error.message]})}catch(u){return m(g(u))}}async removeFault(e){try{let u=this.activeFaults.get(e);return u?(await this.performFaultRemoval(u),this.activeFaults.delete(e),p(void 0)):p(void 0)}catch(u){return m(g(u))}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(e){let u={1:"claude-3-haiku-20240307",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return u[e]||u[2]}async analyzeExperimentWithLLM(e){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:
3010
3010
  Experiment: ${e.name}
3011
3011
  Hypothesis: ${e.hypothesis.statement}
3012
3012
  Blast Radius: ${e.blastRadius.scope}${e.blastRadius.percentage?` (${e.blastRadius.percentage}%)`:""}
@@ -3016,7 +3016,7 @@ Provide:
3016
3016
  1. Hypothesis validation likelihood
3017
3017
  2. Potential risks
3018
3018
  3. Recommended safety measures`}],maxTokens:this.config.llmMaxTokens})).content}catch{return G.warn("LLM analysis failed:"),null}}validateExperiment(e){return e.id?e.name?e.hypothesis?!e.steadyState||e.steadyState.probes.length===0?m(new Error("At least one steady state probe is required")):!e.faults||e.faults.length===0?m(new Error("At least one fault injection is required")):e.rollbackPlan?e.blastRadius.excludeProduction===!1&&!e.rollbackPlan.automatic?m(new Error("Production experiments require automatic rollback")):p(void 0):m(new Error("Rollback plan is required")):m(new Error("Experiment hypothesis is required")):m(new Error("Experiment name is required")):m(new Error("Experiment ID is required"))}validateFault(e){return e.id?e.type?e.target?e.duration<0?m(new Error("Fault duration must be non-negative")):e.probability!==void 0&&(e.probability<0||e.probability>1)?m(new Error("Fault probability must be between 0 and 1")):p(void 0):m(new Error("Fault target is required")):m(new Error("Fault type is required")):m(new Error("Fault ID is required"))}createExecution(e){return{experimentId:e.id,startTime:new Date,result:{experimentId:e.id,status:"running",startTime:new Date,hypothesisValidated:!1,steadyStateVerified:!1,faultResults:[],metrics:[],incidents:[]}}}finalizeExecution(e){e.result.endTime=new Date;let u={experimentId:e.result.experimentId,status:e.result.status,startTime:e.result.startTime,endTime:e.result.endTime,hypothesisValidated:e.result.hypothesisValidated,steadyStateVerified:e.result.steadyStateVerified,faultResults:e.result.faultResults,metrics:e.result.metrics,incidents:e.result.incidents};return this.memory.set(`chaos:results:${e.experimentId}:${Date.now()}`,u,{namespace:"chaos-resilience",persist:!0}),u}async executeProbe(e){try{switch(e.type){case"http":return await this.executeHttpProbe(e);case"tcp":return await this.executeTcpProbe(e);case"command":return await this.executeCommandProbe(e);case"metric":return await this.executeMetricProbe(e);default:return!1}}catch{return!1}}async executeHttpProbe(e){try{let u=await this.httpClient.get(e.target,{timeout:e.timeout??5e3,retries:1,circuitBreaker:!1});if(!u.success)return G.info(`HTTP probe failed: ${e.name} -> ${u.error.message}`),!1;let a=u.value;if(e.expectedStatus!==void 0){let t=a.status===e.expectedStatus;return t||G.info(`HTTP probe ${e.name}: expected status ${e.expectedStatus}, got ${a.status}`),t}return a.ok}catch(u){return G.info(`HTTP probe error: ${e.name} -> ${k(u)}`),!1}}async executeTcpProbe(e){return new Promise(u=>{try{let[a,t]=e.target.split(":"),r=parseInt(t,10);if(!a||isNaN(r)){G.info(`TCP probe invalid target: ${e.target} (expected host:port)`),u(!1);return}let i=e.timeout??5e3,n=new VE.Socket,o=setTimeout(()=>{n.destroy(),G.info(`TCP probe timeout: ${e.name} -> ${e.target}`),u(!1)},i);n.connect(r,a,()=>{clearTimeout(o),n.destroy(),u(!0)}),n.on("error",l=>{clearTimeout(o),n.destroy(),G.info(`TCP probe error: ${e.name} -> ${l.message}`),u(!1)})}catch(a){G.info(`TCP probe exception: ${e.name} -> ${k(a)}`),u(!1)}})}static ALLOWED_PROBE_COMMANDS=["curl","wget","nc","netcat","ping","nslookup","dig","ps","pgrep","cat","head","tail","ls","stat","echo","test","[","node","npm"];async executeCommandProbe(e){return new Promise(u=>{let a=e.timeout??1e4,t=ki(e.target,s.ALLOWED_PROBE_COMMANDS);if(!t.valid){G.info(`Command probe ${e.name} blocked: ${t.error}`),G.info(`Blocked patterns: ${t.blockedPatterns?.join(", ")||"none"}`),u(!1);return}let i=(t.sanitizedCommand||e.target).trim().split(/\s+/),n=i[0],o=i.slice(1);GE(n,o,{timeout:a},(l,c,E)=>{if(l){G.info(`Command probe failed: ${e.name} -> ${l.message}`),u(!1);return}if(e.expectedOutput!==void 0){let d=c.trim().includes(e.expectedOutput);d||G.info(`Command probe ${e.name}: output did not contain expected value`),u(d);return}u(!0)})})}async executeMetricProbe(e){try{let u=await this.httpClient.get(e.target,{timeout:e.timeout??5e3,retries:1,circuitBreaker:!1});if(!u.success)return G.info(`Metric probe failed: ${e.name} -> ${u.error.message}`),!1;let a=u.value;if(!a.ok)return G.info(`Metric probe HTTP error: ${e.name} -> ${a.status}`),!1;let t=await a.text(),r;try{let i=T(t);r=typeof i.value=="number"?i.value:parseFloat(i.value)}catch{r=parseFloat(t)}if(isNaN(r))return G.info(`Metric probe ${e.name}: could not parse metric value from response`),!1;if(e.threshold!==void 0){let{operator:i,value:n}=e.threshold;switch(i){case"lt":return r<n;case"gt":return r>n;case"lte":return r<=n;case"gte":return r>=n;case"eq":return r===n;default:return!0}}return!0}catch(u){return G.info(`Metric probe error: ${e.name} -> ${k(u)}`),!1}}async performFaultInjection(e){let a={latency:async()=>this.injectLatency(e),error:async()=>this.injectError(e),timeout:async()=>this.injectTimeout(e),"packet-loss":async()=>this.injectPacketLoss(e),"cpu-stress":async()=>this.injectCpuStress(e),"memory-stress":async()=>this.injectMemoryStress(e),"disk-stress":async()=>this.injectDiskStress(e),"network-partition":async()=>this.injectNetworkPartition(e),"dns-failure":async()=>this.injectDnsFailure(e),"process-kill":async()=>this.injectProcessKill(e)}[e.type];return a?a():m(new Error(`Unknown fault type: ${e.type}`))}async injectLatency(e){let u=e.parameters.latencyMs??100;return G.info(`Latency injection configured: ${u}ms for ${e.target.selector}`),G.info("Note: Actual latency injection requires network proxy (e.g., Toxiproxy, tc)"),p(1)}async injectError(e){let u=e.parameters.errorCode??500;return G.info(`Error injection configured: ${u} for ${e.target.selector}`),G.info("Note: Actual error injection requires service mesh (e.g., Istio, Linkerd)"),p(1)}async injectTimeout(e){return G.info(`Timeout injection configured for ${e.target.selector}`),G.info("Note: Actual timeout injection requires network proxy configuration"),p(1)}async injectPacketLoss(e){let u=e.parameters.packetLossPercent??10;return G.info(`Packet loss configured: ${u}% for ${e.target.selector}`),G.info("Note: Actual packet loss requires tc/iptables (Linux) or similar"),p(1)}async injectCpuStress(e){let u=e.parameters.cpuPercent??80,a=e.parameters.cores??1,t=e.duration;G.info(`Injecting CPU stress: ${u}% on ${a} core(s) for ${t}ms`);let r=Date.now(),i=setInterval(()=>{if(Date.now()-r>=t){clearInterval(i);return}let n=10*(u/100),o=Date.now();for(;Date.now()-o<n;)K()*K()},10);return this.stressWorkers.set(e.id,i),p(a)}async injectMemoryStress(e){let u=e.parameters.memoryBytes??104857600,a=Math.round(u/(1024*1024));G.info(`Injecting memory stress: ${a}MB allocation`);try{let r=Math.ceil(u/1048576),i=[];for(let n=0;n<r;n++){let o=Math.min(1048576,u-n*1048576),l=new Array(o).fill(K());i.push(l)}return this.stressWorkers.set(e.id,i),G.info(`Memory stress active: ${i.length} chunks allocated`),p(1)}catch(t){return m(new Error(`Failed to allocate memory: ${k(t)}`))}}async injectDiskStress(e){return G.info(`Disk stress configured for ${e.target.selector}`),G.info("Note: Actual disk stress requires file system write permissions"),p(1)}async injectNetworkPartition(e){return G.info(`Network partition configured for ${e.target.selector}`),G.info("Note: Actual network partition requires iptables/firewall rules"),p(1)}async injectDnsFailure(e){return G.info(`DNS failure configured for ${e.target.selector}`),G.info("Note: Actual DNS failure requires DNS server or /etc/hosts modification"),p(1)}async injectProcessKill(e){let u=e.target.selector;return G.info(`Process kill configured for pattern: ${u}`),G.info("Note: Actual process kill requires appropriate permissions"),this.config.enableDryRun?(G.info(`Would kill processes matching: ${u}`),p(0)):p(1)}async performFaultRemoval(e){G.info(`Removing fault: ${e.id} (${e.type})`);let u=this.stressWorkers.get(e.id);u&&(typeof u=="object"&&"unref"in u&&clearInterval(u),this.stressWorkers.delete(e.id))}async collectMetricsDuringExperiment(e,u){let a=u.hypothesis.metrics.map(i=>i.metric),t=Date.now(),r=Math.max(...u.faults.map(i=>i.duration),this.config.defaultTimeout);for(;Date.now()-t<Math.min(r,5e3);){for(let i of a){let n={timestamp:new Date,name:i,value:this.collectRealMetricValue(i),labels:{experiment:u.id}};e.result.metrics.push(n)}await this.sleep(this.config.safetyCheckInterval)}}collectRealMetricValue(e){return this.metricsCollector.getChaosMetricValue(e)}validateHypothesis(e,u){for(let a of e.metrics){let t=u.filter(i=>i.name===a.metric);if(t.length===0)return!1;let r=t.reduce((i,n)=>i+n.value,0)/t.length;if(!this.checkMetricExpectation(r,a))return!1}for(let a of e.tolerances){let t=u.filter(o=>o.name===a.metric);if(t.length===0)continue;let r=t.map(o=>o.value),i=this.calculateDeviation(r);if((a.unit==="percent"?i/r[0]*100:i)>a.maxDeviation)return!1}return!0}checkMetricExpectation(e,u){let{operator:a,value:t}=u;switch(a){case"eq":return e===t;case"lt":return e<t;case"gt":return e>t;case"lte":return e<=t;case"gte":return e>=t;case"between":let[r,i]=t;return e>=r&&e<=i;default:return!1}}calculateDeviation(e){if(e.length===0)return 0;let u=e.reduce((t,r)=>t+r,0)/e.length,a=e.map(t=>Math.pow(t-u,2));return Math.sqrt(a.reduce((t,r)=>t+r,0)/e.length)}determineExperimentStatus(e,u){return!e.result.steadyStateVerified||!u?"failed":e.result.hypothesisValidated?"completed":e.result.faultResults.filter(t=>!t.injected).length>0?"failed":"completed"}async rollbackExperiment(e){for(let u of e.rollbackPlan.steps.sort((a,t)=>a.order-t.order)){G.info(`Executing rollback step ${u.order}: ${u.action}`);try{await this.executeRollbackAction(u.action,u.target,u.timeout)}catch(a){G.error(`Rollback step ${u.order} failed: ${k(a)}`)}}for(let u of e.faults)await this.removeFault(u.id)}async executeRollbackAction(e,u,a=3e4){e.startsWith("http://")||e.startsWith("https://")?await this.executeHttpRollback(e,a):e.startsWith("cmd:")?await this.executeCommandRollback(e.slice(4),a):u&&(u.startsWith("http://")||u.startsWith("https://"))?await this.executeHttpRollback(`${u}/_chaos/${e}`,a):await this.executeBuiltInRollback(e,u,a)}async executeHttpRollback(e,u){let a=await this.httpClient.post(e,{},{timeout:u,retries:1});if(!a.success)throw new Error(`HTTP rollback failed: ${a.error.message}`)}static ALLOWED_ROLLBACK_COMMANDS=["kill","pkill","rm","rmdir","mv","cp","systemctl","service","docker","kubectl","iptables","tc","echo","true"];executeCommandRollback(e,u){return new Promise((a,t)=>{let r=ki(e,s.ALLOWED_ROLLBACK_COMMANDS);if(!r.valid){t(new Error(`Rollback command blocked: ${r.error}`));return}let n=(r.sanitizedCommand||e).trim().split(/\s+/),o=n[0],l=n.slice(1);GE(o,l,{timeout:u},(c,E,d)=>{c?t(new Error(`Command rollback failed: ${c.message}. ${d}`)):a()})})}async executeBuiltInRollback(e,u,a){let t=e.toLowerCase();t.includes("remove")||t.includes("clear")?u&&G.info(`Clearing state for target: ${u}`):t.includes("restart")?G.info(`Restart requested for: ${u||"service"}`):t.includes("restore")?G.info(`Restore requested for: ${u||"system"}`):G.info(`Rollback action logged: ${e}`),await this.sleep(100)}sleep(e){return new Promise(u=>setTimeout(u,e))}};S();cu();var S2u={defaultTimeout:3e5,maxVirtualUsers:1e3,reportingInterval:1e3,enableDetailedMetrics:!0,connectionPoolSize:100},W0=class{constructor(e,u={}){this.memory=e;this.config={...S2u,...u},this.httpClient=new Uu}config;activeTests=new Map;httpClient;async createTest(e){try{let u=this.validateTest(e);return u.success?(await this.memory.set(`loadtest:tests:${e.id}`,e,{namespace:"chaos-resilience",persist:!0}),p(e.id)):m(u.error)}catch(u){return m(g(u))}}async runTest(e){try{let u=await this.memory.get(`loadtest:tests:${e}`);if(!u)return m(new Error(`Load test not found: ${e}`));if(this.activeTests.has(e))return m(new Error(`Load test ${e} is already running`));if(u.profile.virtualUsers.max>this.config.maxVirtualUsers)return m(new Error(`Virtual users (${u.profile.virtualUsers.max}) exceeds maximum (${this.config.maxVirtualUsers})`));let a=this.createExecution(u);this.activeTests.set(e,a);try{return await this.executeLoadTest(a,u),a.result.assertionResults=this.evaluateAssertions(u.assertions,a.result.summary),a.result.status=this.determineTestStatus(a.result),p(this.finalizeExecution(a))}catch(t){return a.result.status="failed",a.result.errors.push({type:"execution_error",message:k(t),count:1,firstOccurrence:new Date,lastOccurrence:new Date}),p(this.finalizeExecution(a))}finally{this.activeTests.delete(e)}}catch(u){return m(g(u))}}async stopTest(e){try{let u=this.activeTests.get(e);return u?(u.aborted=!0,u.result.status="aborted",p(this.finalizeExecution(u))):m(new Error(`No active load test found: ${e}`))}catch(u){return m(g(u))}}async getRealtimeMetrics(e){try{let u=this.activeTests.get(e);if(!u)return m(new Error(`No active load test found: ${e}`));let a=u.result.timeline[u.result.timeline.length-1];return a?p(a):m(new Error("No metrics available yet"))}catch(u){return m(g(u))}}async generateFromTraffic(e,u){try{if(e.requests.length===0)return m(new Error("Traffic sample contains no requests"));if(u<=0)return m(new Error("Multiplier must be positive"));let a=e.requests.reduce((D,h)=>D+h.frequency,0),t=e.requests.reduce((D,h)=>D+h.avgResponseTime*h.frequency,0)/a,r=e.requests.map(D=>({name:`${D.method} ${D.url}`,weight:D.frequency/a,steps:[{type:"request",target:{url:D.url,method:D.method}},{type:"think",duration:Math.max(100,t*.5)}]})),n=a/e.duration*u,o=Math.ceil(n*(t/1e3)),l={virtualUsers:{start:Math.ceil(o*.1),max:Math.min(o,this.config.maxVirtualUsers),pattern:"ramp"},duration:Math.max(6e4,e.duration*u),rampUp:3e4,rampDown:15e3},c=[{metric:"p95",operator:"lt",value:t*2},{metric:"error-rate",operator:"lt",value:5},{metric:"throughput",operator:"gte",value:n*.9}],E=u>5?"stress":"load",d={id:A(),name:`Generated from ${e.source} (${u}x)`,type:E,target:{url:e.requests[0].url,method:e.requests[0].method},profile:l,scenarios:r,assertions:c};return p(d)}catch(a){return m(g(a))}}validateTest(e){return e.id?e.name?!e.target||!e.target.url?m(new Error("Test target URL is required")):e.profile?e.profile.virtualUsers.max<=0?m(new Error("Maximum virtual users must be positive")):e.profile.duration<=0?m(new Error("Test duration must be positive")):p(void 0):m(new Error("Test profile is required")):m(new Error("Test name is required")):m(new Error("Test ID is required"))}createExecution(e){return{testId:e.id,startTime:new Date,aborted:!1,result:{testId:e.id,status:"completed",duration:0,summary:this.createEmptySummary(),timeline:[],errors:[],assertionResults:[]}}}createEmptySummary(){return{totalRequests:0,successfulRequests:0,failedRequests:0,requestsPerSecond:0,avgResponseTime:0,p50ResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,maxResponseTime:0,errorRate:0}}async executeLoadTest(e,u){let a=Date.now(),t=u.profile.duration,r=[],i=new Map,n=this.getExecutionStrategy(u.type);for(;Date.now()-a<t&&!e.aborted;){let o=Date.now()-a,l=this.calculateCurrentVirtualUsers(u.profile,o,t),c=await this.executeBatch(u,l,n);r.push(...c.responseTimes);for(let d of c.errors){let D=i.get(d);D?(D.count++,D.lastOccurrence=new Date):i.set(d,{type:"request_error",message:d,count:1,firstOccurrence:new Date,lastOccurrence:new Date})}e.result.summary.totalRequests+=c.totalRequests,e.result.summary.successfulRequests+=c.successfulRequests,e.result.summary.failedRequests+=c.failedRequests;let E={timestamp:new Date,virtualUsers:l,requestsPerSecond:c.totalRequests,avgResponseTime:c.responseTimes.length>0?c.responseTimes.reduce((d,D)=>d+D,0)/c.responseTimes.length:0,errorRate:c.totalRequests>0?c.failedRequests/c.totalRequests*100:0};e.result.timeline.push(E),await this.sleep(this.config.reportingInterval)}if(e.result.duration=Date.now()-a,e.result.errors=Array.from(i.values()),r.length>0){let o=r.sort((l,c)=>l-c);e.result.summary.avgResponseTime=o.reduce((l,c)=>l+c,0)/o.length,e.result.summary.p50ResponseTime=this.percentile(o,50),e.result.summary.p95ResponseTime=this.percentile(o,95),e.result.summary.p99ResponseTime=this.percentile(o,99),e.result.summary.maxResponseTime=o[o.length-1]}e.result.summary.requestsPerSecond=e.result.summary.totalRequests/(e.result.duration/1e3),e.result.summary.errorRate=e.result.summary.totalRequests>0?e.result.summary.failedRequests/e.result.summary.totalRequests*100:0}getExecutionStrategy(e){switch(e){case"load":return{requestMultiplier:1,errorInjectionRate:0};case"stress":return{requestMultiplier:1.5,errorInjectionRate:.01};case"spike":return{requestMultiplier:3,errorInjectionRate:.02};case"soak":return{requestMultiplier:.8,errorInjectionRate:0};case"breakpoint":return{requestMultiplier:2,errorInjectionRate:.05};default:return{requestMultiplier:1,errorInjectionRate:0}}}calculateCurrentVirtualUsers(e,u,a){let{virtualUsers:t,rampUp:r=0,rampDown:i=0}=e,{start:n,max:o,pattern:l}=t;switch(l){case"constant":return o;case"ramp":if(u<r)return Math.round(n+(o-n)*(u/r));if(u>a-i){let x=(a-u)/i;return Math.round(n+(o-n)*x)}return o;case"step":let c=5,E=a/c,d=Math.floor(u/E),D=(o-n)/c;return Math.round(n+D*d);case"spike":return u%3e4<5e3?o:n;default:return o}}async executeBatch(e,u,a){let t=Math.round(u*a.requestMultiplier),r=Math.min(t,this.config.connectionPoolSize),i=this.createBatches(t,r),n=[];for(let c of i){let E=Date.now(),d=await Promise.all(c.map(()=>this.executeRequest(e,a)));n.push(...d);let D=Date.now()-E,h=1e3/Math.max(u,1)*c.length;D<h&&await this.sleep(h-D)}let o=n.filter(c=>c.success).map(c=>c.latency),l=n.filter(c=>!c.success).map(c=>c.error||"Unknown error");return{totalRequests:n.length,successfulRequests:n.filter(c=>c.success).length,failedRequests:n.filter(c=>!c.success).length,responseTimes:o,errors:l}}async executeRequest(e,u){let a=Date.now(),t=a;if(u.errorInjectionRate>0&&K()<u.errorInjectionRate)return{status:0,latency:Date.now()-a,success:!1,error:"Simulated error injection",timestamp:t};try{let{url:r,method:i="GET",headers:n,body:o}=e.target,l={headers:n,timeout:this.config.defaultTimeout,retries:0,circuitBreaker:!1},c;switch(i.toUpperCase()){case"POST":c=await this.httpClient.post(r,o,l);break;case"PUT":c=await this.httpClient.put(r,o,l);break;case"DELETE":c=await this.httpClient.delete(r,l);break;default:c=await this.httpClient.get(r,l);break}if(c.success){let E=c.value;return{status:E.status,latency:Date.now()-a,success:E.ok,error:E.ok?void 0:`HTTP ${E.status}: ${E.statusText}`,timestamp:t}}else return{status:c.error.status??0,latency:Date.now()-a,success:!1,error:c.error.message,timestamp:t}}catch(r){return{status:0,latency:Date.now()-a,success:!1,error:k(r),timestamp:t}}}createBatches(e,u){let a=[],t=e;for(;t>0;){let r=Math.min(t,u);a.push(Array.from({length:r},(i,n)=>n)),t-=r}return a}percentile(e,u){if(e.length===0)return 0;let a=Math.ceil(u/100*e.length)-1;return e[Math.max(0,Math.min(a,e.length-1))]}evaluateAssertions(e,u){return e.map(a=>{let t=this.getMetricValue(a.metric,u),r=this.checkAssertion(a,t);return{assertion:a,passed:r,actualValue:t}})}getMetricValue(e,u){switch(e){case"response-time":return u.avgResponseTime;case"throughput":return u.requestsPerSecond;case"error-rate":return u.errorRate;case"p95":return u.p95ResponseTime;case"p99":return u.p99ResponseTime;default:return 0}}checkAssertion(e,u){switch(e.operator){case"lt":return u<e.value;case"gt":return u>e.value;case"lte":return u<=e.value;case"gte":return u>=e.value;default:return!1}}determineTestStatus(e){return e.status==="aborted"?"aborted":e.assertionResults.filter(a=>!a.passed).length>0||e.summary.errorRate>10?"failed":"completed"}finalizeExecution(e){let u={testId:e.result.testId,status:e.result.status,duration:e.result.duration,summary:e.result.summary,timeline:e.result.timeline,errors:e.result.errors,assertionResults:e.result.assertionResults};return this.memory.set(`loadtest:results:${e.testId}:${Date.now()}`,u,{namespace:"chaos-resilience",persist:!0}),u}sleep(e){return new Promise(u=>setTimeout(u,e))}};N();S();cu();J();var w2u={defaultTimeout:6e4,healthCheckInterval:1e3,maxRetries:3,recoveryCheckDelay:500,simulateRandomFailures:!1},Se=B.create("chaos-resilience/performance-profiler"),$0=class{constructor(e,u={}){this.memory=e;this.config={...w2u,...u},this.httpClient=ut()}config;httpClient;async testRecovery(e,u,a){let t=A();try{let r=[],i=await this.checkServiceHealth(e);if(r.push({timestamp:new Date,event:"Initial health check",status:i?"healthy":"unhealthy"}),!i)return p({service:e,faultType:u,recoveryTime:0,expectedRecoveryTime:a,passed:!1,timeline:r});r.push({timestamp:new Date,event:`Injecting fault: ${u}`,status:"degraded"}),await this.injectFault(e,u);let n=await this.checkServiceHealth(e);r.push({timestamp:new Date,event:"Post-fault health check",status:n?"healthy":"unhealthy"}),r.push({timestamp:new Date,event:"Removing fault",status:"degraded"}),await this.removeFault(e,u);let o=Date.now(),l=0,c=!1,E=a*2;for(;Date.now()-o<E;){if(await this.checkServiceHealth(e)){l=Date.now()-o,c=!0,r.push({timestamp:new Date,event:"Service recovered",status:"healthy"});break}r.push({timestamp:new Date,event:"Recovery check - still degraded",status:"degraded"}),await this.sleep(this.config.recoveryCheckDelay)}c||r.push({timestamp:new Date,event:"Recovery timeout exceeded",status:"unhealthy"});let d={service:e,faultType:u,recoveryTime:l,expectedRecoveryTime:a,passed:c&&l<=a,timeline:r};return await this.storeTestResult("recovery",t,d),p(d)}catch(r){return m(g(r))}}async testFailover(e,u){let a=A();try{let t=[],r=1,[i,n]=await Promise.all([this.checkServiceHealth(e),this.checkServiceHealth(u)]);if(t.push({order:r++,action:"Verify primary service health",duration:0,success:i}),t.push({order:r++,action:"Verify secondary service health",duration:0,success:n}),!i||!n)return p({primaryService:e,secondaryService:u,failoverTime:0,dataLoss:!0,passed:!1,steps:t});let o=await this.captureServiceState(e);t.push({order:r++,action:"Capture primary service state",duration:0,success:!0});let l=Date.now();await this.injectFault(e,"process-kill"),t.push({order:r++,action:"Trigger primary service failure",duration:Date.now()-l,success:!0});let c=Date.now(),E=!1,d=0;for(;Date.now()-c<this.config.defaultTimeout;){if(await this.checkServiceIsActive(u)){d=Date.now()-l,E=!0;break}await this.sleep(this.config.healthCheckInterval)}t.push({order:r++,action:"Detect failover completion",duration:d,success:E});let D=await this.captureServiceState(u),h=!this.compareServiceStates(o,D);t.push({order:r++,action:"Verify data integrity on secondary",duration:0,success:!h}),await this.removeFault(e,"process-kill"),t.push({order:r++,action:"Restore primary service",duration:0,success:!0});let C={primaryService:e,secondaryService:u,failoverTime:d,dataLoss:h,passed:E&&!h,steps:t};return await this.storeTestResult("failover",a,C),p(C)}catch(t){return m(g(t))}}async testCircuitBreaker(e,u){let a=A();try{let t=u?.errorThreshold??5,r=u?.timeout??this.config.defaultTimeout,i=u?.halfOpenRequests??3;await this.getCircuitState(e)!=="closed"&&await this.resetCircuit(e);let o=0,l=!1;for(let y=0;y<t*2;y++)if(await this.generateError(e),o++,await this.getCircuitState(e)==="open"){l=!0;break}let c=!1,E=Date.now();for(;Date.now()-E<r;){if(await this.getCircuitState(e)==="half-open"){c=!0;break}await this.sleep(this.config.healthCheckInterval)}let d="correct";if(c){let y=0;for(let b=0;b<i;b++)await this.sendSuccessfulRequest(e)&&y++;await this.getCircuitState(e)!=="closed"&&y===i&&(d="incorrect")}let D=!1,h=Date.now();for(;Date.now()-h<r;){if(await this.getCircuitState(e)==="closed"){D=!0;break}await this.sendSuccessfulRequest(e),await this.sleep(this.config.healthCheckInterval)}let C={service:e,opened:l,openedAfterErrors:o,closedAfterRecovery:D,halfOpenBehavior:d,passed:l&&D&&d==="correct"};return await this.storeTestResult("circuit-breaker",a,C),p(C)}catch(t){return m(g(t))}}async testRateLimiting(e,u){let a=A();try{let t=0,r={statusCode:429,retryAfter:void 0,body:void 0},i=[1,5,10,25,50,100,200],n=0,o=!1;for(let d of i){if(o)break;let D=await this.sendRequestBatch(e,d);n+=d;for(let h of D)if(h.statusCode===429){o=!0,t=n-(d-D.indexOf(h)),r=h;break}}o||(t=n);let l=u*.2,c=Math.abs(t-u)<=l||!o,E={service:e,expectedLimit:u,actualLimit:t,passed:o&&c,responseWhenLimited:r};return await this.storeTestResult("rate-limit",a,E),p(E)}catch(t){return m(g(t))}}async checkServiceHealth(e){if(!this.isRealServiceUrl(e))return this.simulateHealthCheck();try{return await this.httpClient.healthCheck(e)}catch{return this.simulateHealthCheck()}}isRealServiceUrl(e){return e.startsWith("http://")||e.startsWith("https://")}simulateHealthCheck(){return this.config.simulateRandomFailures?K()>.05:!0}async checkServiceIsActive(e){if(!this.isRealServiceUrl(e))return this.simulateServiceActive();try{let u=await this.httpClient.get(e,{timeout:5e3,retries:1});return u.success&&u.value.ok}catch{return this.simulateServiceActive()}}simulateServiceActive(){return this.config.simulateRandomFailures?K()>.1:!0}async injectFault(e,u){if(this.isRealServiceUrl(e))try{let a=`${e}/_chaos/inject`;await this.httpClient.post(a,{faultType:u},{timeout:5e3,retries:0});return}catch{Se.debug("Fault injection API failed:")}Se.info(`Injecting fault ${u} into service: ${e}`),await this.sleep(100)}async removeFault(e,u){if(this.isRealServiceUrl(e))try{let a=`${e}/_chaos/remove`;await this.httpClient.post(a,{faultType:u},{timeout:5e3,retries:0});return}catch{Se.debug("Fault removal API failed:")}Se.info(`Removing fault ${u} from service: ${e}`),await this.sleep(50)}async captureServiceState(e){if(this.isRealServiceUrl(e))try{let a=`${e}/_state`,t=await this.httpClient.get(a,{timeout:5e3,retries:1});if(t.success&&t.value.ok){let r=await t.value.text(),i=this.calculateChecksum(r),n=this.parseRecordCount(r);return{checksum:i,timestamp:new Date,records:n}}}catch{Se.debug("State capture API failed:")}return await this.captureMemoryState(e)}calculateChecksum(e){let u=0;for(let a=0;a<e.length;a++){let t=e.charCodeAt(a);u=(u<<5)-u+t,u=u&u}return`chk_${Math.abs(u).toString(16)}`}parseRecordCount(e){try{let u=T(e);return u.records??u.count??u.total??u.length??0}catch{return e.split(`
3019
- `).filter(u=>u.trim()).length}}async captureMemoryState(e){let u=`resilience:state:${this.hashServiceName(e)}`,a=await this.memory.get(u);if(a)return a;let t={checksum:`init_${A().slice(0,8)}`,timestamp:new Date,records:0};return await this.memory.set(u,t,{namespace:"chaos-resilience"}),t}hashServiceName(e){let u=0;for(let a of e)u=(u<<5)-u+a.charCodeAt(0),u=u&u;return Math.abs(u).toString(16)}compareServiceStates(e,u){let a=e.checksum===u.checksum,t=e.records===u.records;return a||t}async getCircuitState(e){try{return this.httpClient.getCircuitState(e).state}catch{return"closed"}}async resetCircuit(e){try{this.httpClient.resetCircuit(e)}catch{Se.info(`Resetting circuit breaker for: ${e}`)}}async generateError(e){if(this.isRealServiceUrl(e))try{let u=`${e}/_chaos/error`;await this.httpClient.post(u,{},{timeout:5e3,retries:0});return}catch{Se.debug("Error generation API failed:")}Se.info(`Generating error for: ${e}`)}async sendSuccessfulRequest(e){if(!this.isRealServiceUrl(e))return!0;try{let u=await this.httpClient.get(e,{timeout:5e3,retries:1});return u.success&&u.value.ok}catch{return!0}}async sendRequestBatch(e,u){let a=[];if(!this.isRealServiceUrl(e))return this.simulateRequestBatch(u);for(let t=0;t<u;t++)try{let r=await this.httpClient.get(e,{timeout:2e3,retries:0,circuitBreaker:!1});if(r.success){let i=r.value,n=i.headers.get("Retry-After");a.push({statusCode:i.status,retryAfter:n?parseInt(n,10):void 0})}else a.push({statusCode:500,body:{error:r.error.message}})}catch{return[...a,...this.simulateRequestBatch(u-t)]}return a}simulateRequestBatch(e){let u=[];for(let t=0;t<e;t++)t>=75?u.push({statusCode:429,retryAfter:60,body:{error:"Rate limit exceeded"}}):u.push({statusCode:200});return u}async storeTestResult(e,u,a){await this.memory.set(`resilience:${e}:${u}`,a,{namespace:"chaos-resilience",persist:!0})}sleep(e){return new Promise(u=>setTimeout(u,e))}};cu();var T2u={stateSize:10,actionSize:5,hiddenLayers:[64,64],learningRatePG:.01,gammaPG:.99,entropyCoeff:.01},Vi=class extends Eu{policy;pgConfig;actions=[];episodeLog=[];constructor(e={}){super("policy-gradient","policy-based"),this.pgConfig={...T2u,...e},this.initializeActions(),this.policy=new $({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.pgConfig.learningRatePG})}async predict(e){this.initialized||await this.initialize();let u=this.prepareState(e),a=this.policy.forward(u),t=Cu.forward(a),r=this.sampleAction(t),i=this.actions[r],n=t[r],o=Math.max(.3,Math.min(1,n+.4));return this.episodeLog.push({state:e,action:i,reward:0}),{action:i,confidence:o,reasoning:this.generateReasoning(e,i,n)}}async trainCore(e){let u=this.groupIntoEpisodes(e),a=0;for(let t of u){let r=this.calculateReturns(t);for(let i=0;i<t.length;i++){let{state:n,action:o}=t[i],l=r[i],c=this.prepareState(n),E=this.policy.forward(c),d=Cu.forward(E),D=this.actionToIndex(o),C=-Math.log(d[D]+1e-10)*l;a+=Math.abs(C);let y=new Float32Array(d.length);for(let x=0;x<y.length;x++)x===D?y[x]=-l*(1-d[x]):y[x]=l*d[x];this.policy.backward(y);for(let x of this.policy.layers)x.update(this.pgConfig.learningRatePG)}}return this.episodeLog=[],{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((t,r)=>t+r,0)/this.rewardHistory.length,loss:a/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 Policy Gradient (REINFORCE) for Resource Allocation",capabilities:["Neural policy optimization","Monte Carlo return estimation","Entropy regularization"],hyperparameters:{stateSize:this.pgConfig.stateSize,actionSize:this.pgConfig.actionSize,learningRatePG:this.pgConfig.learningRatePG,gammaPG:this.pgConfig.gammaPG},stats:this.stats}}prepareState(e){let u=e.features.slice(0,this.pgConfig.stateSize);for(;u.length<this.pgConfig.stateSize;)u.push(0);let a=Math.max(...u.map(Math.abs));if(a>0)for(let t=0;t<u.length;t++)u[t]=u[t]/a;return new Float32Array(u)}initializeActions(){this.actions=[{type:"allocate",value:{agentType:"tester",count:1}},{type:"allocate",value:{agentType:"analyzer",count:1}},{type:"reallocate",value:{domain:"test-execution"}},{type:"scale-up",value:1},{type:"scale-down",value:1}],this.pgConfig.actionSize=this.actions.length,this.policy=new $({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.pgConfig.learningRatePG})}actionToIndex(e){let u=this.actionToKey(e);for(let a=0;a<this.actions.length;a++)if(this.actionToKey(this.actions[a])===u)return a;return 0}actionToKey(e){return`${e.type}:${JSON.stringify(e.value)}`}sampleAction(e){if(K()<this.config.explorationRate)return Du(0,this.actions.length);let u=K(),a=0;for(let t=0;t<e.length;t++)if(a+=e[t],u<=a)return t;return this.argmax(e)}argmax(e){let u=0,a=e[0];for(let t=1;t<e.length;t++)e[t]>a&&(a=e[t],u=t);return u}calculateReturns(e){let u=[],a=0;for(let t=e.length-1;t>=0;t--)a=e[t].reward+this.pgConfig.gammaPG*a,u.unshift(a);return u}groupIntoEpisodes(e){let u=[],a=[];for(let t of e)a.push(t),t.done&&(u.push(a),a=[]);return a.length>0&&u.push(a),u}generateReasoning(e,u,a){return`Neural Policy Gradient: ${u.type} (probability: ${a.toFixed(3)})`}async exportCustomData(){return{policy:this.policy.getParameters(),pgConfig:this.pgConfig}}async importCustomData(e){e.policy&&this.policy.setParameters(e.policy),e.pgConfig&&(this.pgConfig={...this.pgConfig,...e.pgConfig}),this.initialized=!0}async resetAlgorithm(){this.policy=new $({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.pgConfig.learningRatePG}),this.episodeLog=[]}};var M2u={maxConcurrentWorkflows:3,defaultTimeout:3e5,enableAutomatedExperiments:!1,publishEvents:!0,enablePolicyGradient:!0,enableQESONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},nu=B.create("chaos-resilience"),Oi=class extends Y{constructor(u,a,t,r={}){let i={...M2u,...r};super(u,"chaos-resilience",i,{verifyFindingTypes:["chaos-experiment","resilience-assessment","failure-injection"],...i.consensusConfig});this.memory=a;this.agentCoordinator=t;this.chaosGovernanceMixin=fc(this.domainName),this.chaosEngineer=new _0({memory:a}),this.loadTester=new W0(a),this.performanceProfiler=new $0(a)}chaosEngineer;loadTester;performanceProfiler;policyGradient;qesona;chaosGovernanceMixin;async onInitialize(){if(this.config.enablePolicyGradient)try{this.policyGradient=new Vi({stateSize:10,actionSize:5,hiddenLayers:[64,64]}),nu.info("PolicyGradient algorithm created successfully")}catch(u){throw nu.error("Failed to create PolicyGradient:",u instanceof Error?u:void 0),new Error(`PolicyGradient creation failed: ${k(u)}`)}if(this.config.enableQESONA)try{this.qesona=await gu({domain:"chaos-resilience",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),nu.info("PersistentSONAEngine initialized successfully")}catch(u){nu.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),nu.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.policyGradient=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runChaosSuite(u){let a=A();try{if(this.startWorkflow(a,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&nu.warn("Topology degraded, using conservative chaos strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn chaos agents"));let t=await this.spawnChaosAgent(a,"coordinator");if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=[],i=[],n=0,o=0;for(let c=0;c<u.length;c++){let E=u[c];this.updateWorkflowProgress(a,Math.round((c+1)/u.length*100));let d=await this.chaosEngineer.runExperiment(E);if(d.success){if(r.push(d.value),d.value.hypothesisValidated)n++;else{o++;let D=this.generateRecommendationsFromExperiment(d.value);i.push(...D)}this.config.publishEvents&&await this.publishExperimentCompleted(d.value)}else o++,i.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${E}: ${d.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(t.value),this.completeWorkflow(a);let l={totalExperiments:u.length,passed:n,failed:o,results:r,recommendations:i};return await this.storeReport("chaos-suite",a,l),p(l)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async runLoadTestSuite(u){let a=A();try{if(this.startWorkflow(a,"load-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&nu.warn("Topology degraded, using conservative load test parameters"),this.minCutMixin.shouldPauseOperations())return m(new Error("Load test suite paused: topology is in critical state"));let t=await this.spawnLoadTestAgent(a,"orchestrator");if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=[],i=[],n=0,o=0;for(let c=0;c<u.length;c++){let E=u[c];this.updateWorkflowProgress(a,Math.round((c+1)/u.length*100));let d=await this.loadTester.runTest(E);if(d.success){r.push(d.value),d.value.status==="completed"?n++:o++;let D=this.detectBottlenecks(d.value);i.push(...D),this.config.publishEvents&&await this.publishLoadTestCompleted(d.value)}else o++}await this.agentCoordinator.stop(t.value),this.completeWorkflow(a);let l={totalTests:u.length,passed:n,failed:o,results:r,bottlenecks:i};return await this.storeReport("load-suite",a,l),p(l)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async assessResilience(u){let a=A();try{if(this.startWorkflow(a,"assessment"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&nu.warn("Topology degraded, assessment may be limited"),this.minCutMixin.shouldPauseOperations())return m(new Error("Resilience assessment paused: topology is in critical state"));let t=new Map,r=[],i=[],n=[],o=await this.spawnAssessmentAgent(a);if(!o.success)return this.failWorkflow(a,o.error.message),m(o.error);this.addAgentToWorkflow(a,o.value);for(let E=0;E<u.length;E++){let d=u[E];this.updateWorkflowProgress(a,Math.round((E+1)/u.length*100));let D=await this.performanceProfiler.testRecovery(d,"latency",5e3),h=await this.performanceProfiler.testCircuitBreaker(d),C=await this.performanceProfiler.testRateLimiting(d,100),y=0;if(D.success&&D.value.passed)y+=33.3,r.push(`${d}: Fast recovery (${D.value.recoveryTime}ms)`);else{let x=D.success?D.value.recoveryTime:"unknown";i.push({service:d,type:"recovery",description:"Slow or failed recovery after fault",risk:P0.create(.7)}),n.push({priority:"high",category:"recovery",recommendation:`Improve ${d} recovery time - currently ${x}ms`,effort:"moderate"})}h.success&&h.value.passed?(y+=33.3,r.push(`${d}: Circuit breaker functioning correctly`)):(i.push({service:d,type:"circuit-breaker",description:"Circuit breaker not functioning as expected",risk:P0.create(.6)}),n.push({priority:"medium",category:"circuit-breaker",recommendation:`Review ${d} circuit breaker configuration`,effort:"minor"})),C.success&&C.value.passed?(y+=33.4,r.push(`${d}: Rate limiting effective`)):(i.push({service:d,type:"rate-limiting",description:"Rate limiting not properly configured",risk:P0.create(.5)}),n.push({priority:"medium",category:"rate-limiting",recommendation:`Configure rate limiting for ${d}`,effort:"minor"})),t.set(d,y)}let l=u.length>0?Array.from(t.values()).reduce((E,d)=>E+d,0)/u.length:0;await this.agentCoordinator.stop(o.value),this.completeWorkflow(a);let c={overallScore:l,serviceScores:t,strengths:r,weaknesses:i,recommendations:n};return await this.storeReport("assessment",a,c),p(c)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async generateExperiments(u){let a=A();try{this.startWorkflow(a,"experiment-generation");let t=[];for(let r of u.services){let i=this.generateServiceExperiments(r,u.dependencies);t.push(...i)}for(let r of u.criticalPaths){let i=this.generateCriticalPathExperiment(r,u);t.push(i)}for(let r of t)await this.chaosEngineer.createExperiment(r);return this.completeWorkflow(a),p(t)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async runStrategicChaosSuite(u,a){let t=A();try{if(this.startWorkflow(t,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&nu.warn("Topology degraded, adjusting strategic chaos parameters"),this.minCutMixin.shouldPauseOperations())return m(new Error("Strategic chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn chaos agents"));let r=await this.selectChaosStrategy(u,a);if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i=r.value.selectedExperiments;if(nu.info(`[chaos-resilience] Using ${r.value.strategy} strategy with ${i.length} experiments (confidence: ${r.value.confidence.toFixed(2)})`),i.length===0)return this.completeWorkflow(t),p({totalExperiments:0,passed:0,failed:0,results:[],recommendations:[{priority:"low",category:"strategy",recommendation:"No experiments selected - consider adjusting strategy context",effort:"trivial"}]});let n=await this.spawnChaosAgent(t,"coordinator");if(!n.success)return this.failWorkflow(t,n.error.message),m(n.error);this.addAgentToWorkflow(t,n.value);let o=[],l=[],c=0,E=0;for(let D of i)await this.chaosEngineer.createExperiment(D);for(let D=0;D<i.length;D++){let h=i[D];this.updateWorkflowProgress(t,Math.round((D+1)/i.length*100));let C=await this.chaosEngineer.runExperiment(h.id);if(C.success){if(o.push(C.value),C.value.hypothesisValidated)c++;else{E++;let x=this.generateRecommendationsFromExperiment(C.value);l.push(...x)}let y=C.value.hypothesisValidated?.8:.2;await this.storeResiliencePattern(h,C.value,y),this.config.publishEvents&&await this.publishExperimentCompleted(C.value)}else E++,l.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${h.name}: ${C.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(n.value),this.completeWorkflow(t);let d={totalExperiments:i.length,passed:c,failed:E,results:o,recommendations:l};return await this.storeReport("strategic-chaos-suite",t,d),p(d)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async getResilienceDashboard(){try{let u=await this.memory.search("chaos:results:*",10),a=await this.memory.search("loadtest:results:*",10),t,r,i=0,n=0,o=0,l=0,c=0;for(let C of u){let y=await this.memory.get(C);y&&((!t||y.startTime>t)&&(t=y.startTime),i+=y.incidents.filter(x=>!x.resolved).length)}for(let C of a){let y=await this.memory.get(C);if(y&&y.timeline.length>0){let x=y.timeline[0].timestamp;(!r||x>r)&&(r=x),c++,y.status==="failed"&&l++}}let E=o>0?n/o:0,d=c>0?l/c*100:0,D="healthy";return i>5||d>25?D="unhealthy":(i>0||d>10)&&(D="degraded"),p({overallHealth:D,lastExperimentDate:t,lastLoadTestDate:r,activeIncidents:i,uptime:99.9,mttr:E,changeFailureRate:d})}catch(u){return m(g(u))}}async spawnChaosAgent(u,a){let t={name:`chaos-${a}-${u.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["chaos-engineering","fault-injection",a],config:{workflowId:u}};return this.agentCoordinator.spawn(t)}async spawnLoadTestAgent(u,a){let t={name:`loadtest-${a}-${u.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["load-testing","performance",a],config:{workflowId:u}};return this.agentCoordinator.spawn(t)}async spawnAssessmentAgent(u){let a={name:`assessment-${u.slice(0,8)}`,domain:"chaos-resilience",type:"analyzer",capabilities:["resilience-assessment","analysis"],config:{workflowId:u}};return this.agentCoordinator.spawn(a)}async publishExperimentCompleted(u){let a={id:A(),type:"chaos-resilience.ExperimentCompleted",timestamp:new Date,source:"chaos-resilience",payload:{experimentId:u.experimentId,status:u.status,hypothesisValidated:u.hypothesisValidated,incidentCount:u.incidents.length}};await this.eventBus.publish(a)}async publishLoadTestCompleted(u){let a={id:A(),type:"chaos-resilience.LoadTestCompleted",timestamp:new Date,source:"chaos-resilience",payload:{testId:u.testId,status:u.status,summary:u.summary,assertionsPassed:u.assertionResults.filter(t=>t.passed).length,assertionsFailed:u.assertionResults.filter(t=>!t.passed).length}};await this.eventBus.publish(a)}generateRecommendationsFromExperiment(u){let a=[];u.hypothesisValidated||a.push({priority:"high",category:"hypothesis-failure",recommendation:`Experiment ${u.experimentId} hypothesis was not validated - review system behavior under fault conditions`,effort:"moderate"}),u.steadyStateVerified||a.push({priority:"critical",category:"steady-state",recommendation:"System did not maintain steady state - investigate stability issues",effort:"major"});for(let t of u.incidents)(t.severity==="critical"||t.severity==="high")&&a.push({priority:t.severity,category:"incident",recommendation:`Address ${t.type}: ${t.message}`,effort:"moderate"});return a}detectBottlenecks(u){let a=[];return u.summary.p95ResponseTime>1e3&&a.push({location:"api",type:"network",description:`P95 response time is ${u.summary.p95ResponseTime}ms (>1000ms)`,impact:u.summary.p95ResponseTime>2e3?"high":"medium",recommendation:"Investigate API response time, consider caching or query optimization"}),u.summary.errorRate>5&&a.push({location:"service",type:"cpu",description:`Error rate is ${u.summary.errorRate.toFixed(2)}% (>5%)`,impact:u.summary.errorRate>10?"high":"medium",recommendation:"Investigate error causes, scale resources if under load"}),u.summary.requestsPerSecond<10&&a.push({location:"backend",type:"io",description:`Low throughput: ${u.summary.requestsPerSecond.toFixed(2)} RPS`,impact:"medium",recommendation:"Review I/O operations, database queries, and connection pooling"}),a}generateServiceExperiments(u,a){let t=[];t.push(this.createExperiment(`${u.name}-latency`,`Test ${u.name} behavior under latency`,"latency",u.name)),t.push(this.createExperiment(`${u.name}-error`,`Test ${u.name} error handling`,"error",u.name)),t.push(this.createExperiment(`${u.name}-cpu-stress`,`Test ${u.name} under CPU stress`,"cpu-stress",u.name));let r=a.filter(i=>i.from===u.name);for(let i of r)i.criticality==="critical"&&t.push(this.createExperiment(`${u.name}-${i.to}-failure`,`Test ${u.name} when ${i.to} fails`,"error",i.to));return t}generateCriticalPathExperiment(u,a){let t=u.join("-");return{id:A(),name:`critical-path-${t}`,description:`Test critical path: ${u.join(" -> ")}`,hypothesis:{statement:"System should handle partial path failure gracefully",metrics:[{metric:"error_rate",operator:"lt",value:10},{metric:"response_time_ms",operator:"lt",value:2e3}],tolerances:[{metric:"error_rate",maxDeviation:5,unit:"percent"}]},steadyState:{description:"All services in path are healthy",probes:u.map(r=>({name:`${r}-health`,type:"http",target:`http://${r}/health`,expected:{status:200},timeout:5e3}))},faults:u.slice(0,-1).map(r=>({id:A(),type:"latency",target:{type:"service",selector:r},parameters:{latencyMs:500},duration:3e4})),blastRadius:{scope:"subset",percentage:50,excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 20"},{type:"timeout",condition:"duration > 60000"}],steps:[{order:1,action:"Remove all faults",timeout:5e3},{order:2,action:"Verify service health"}]}}}createExperiment(u,a,t,r){return{id:A(),name:u,description:a,hypothesis:{statement:`${r} should recover within 5 seconds from ${t}`,metrics:[{metric:"response_time_ms",operator:"lt",value:1e3},{metric:"error_rate",operator:"lt",value:5}],tolerances:[{metric:"response_time_ms",maxDeviation:50,unit:"percent"}]},steadyState:{description:`${r} is healthy and responsive`,probes:[{name:`${r}-health`,type:"http",target:`http://${r}/health`,expected:{status:200},timeout:5e3}]},faults:[{id:A(),type:t,target:{type:"service",selector:r},parameters:this.getDefaultFaultParameters(t),duration:3e4}],blastRadius:{scope:"single",excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 50"}],steps:[{order:1,action:`Remove ${t} fault`},{order:2,action:"Verify recovery"}]}}}getDefaultFaultParameters(u){return{latency:{latencyMs:500},error:{errorCode:500},timeout:{timeoutMs:3e4},"packet-loss":{packetLossPercent:10},"cpu-stress":{cpuPercent:80},"memory-stress":{memoryBytes:268435456},"disk-stress":{},"network-partition":{},"dns-failure":{},"process-kill":{}}[u]||{}}async storeReport(u,a,t){await this.memory.set(`chaos-resilience:reports:${u}:${a}`,t,{namespace:"chaos-resilience",persist:!0})}async selectChaosStrategy(u,a){if(!this.policyGradient||!this.config.enablePolicyGradient)return p({strategy:"default",selectedExperiments:this.getDefaultExperiments(u.slice(0,3)),confidence:1,reasoning:"Default strategy (PolicyGradient disabled)"});if(u.length===0)return p({strategy:"empty",selectedExperiments:[],confidence:1,reasoning:"No services provided"});try{let t={id:`chaos-strategy-${Date.now()}`,features:[a.riskTolerance,a.availableCapacity/100,u.length/50,u.filter(c=>!c.hasFailover).length/Math.max(1,u.length),u.filter(c=>c.type==="database").length/Math.max(1,u.length),a.environment==="production"?0:1,a.environment==="staging"?1:0,u.filter(c=>c.type==="cache").length/Math.max(1,u.length),u.filter(c=>c.type==="queue").length/Math.max(1,u.length),u.reduce((c,E)=>c+E.replicas,0)/Math.max(1,u.length*5)]},r=await this.policyGradient.predict(t),i=[],n="default";switch(r.action.type){case"allocate":let c=typeof r.action.value=="object"?r.action.value:null;if(c&&"agentType"in c&&c.agentType==="tester"){let d=u.filter(D=>!D.hasFailover||D.type==="database").slice(0,3);i=this.generateExperimentsForServices(d,["latency","error"]),n="allocate-critical"}break;case"reallocate":let E=typeof r.action.value=="object"?r.action.value:null;E&&"domain"in E&&E.domain==="test-execution"&&(i=this.generateExperimentsForServices(u.slice(0,5),["cpu-stress","memory-stress"]),n="reallocate-resource-stress");break;case"scale-up":i=this.generateExperimentsForServices(u,["latency","error","timeout"]),n="scale-up-comprehensive";break;case"scale-down":i=this.generateExperimentsForServices(u.slice(0,2),["latency"]),n="scale-down-minimal";break;default:i=this.getDefaultExperiments(u.slice(0,3)),n="default";break}let o=await this.calculateStrategyReward(i,a),l=r.action;return await this.policyGradient.train({state:t,action:l,reward:o,nextState:t,done:!0}),nu.info(`[chaos-resilience] PolicyGradient selected ${n} strategy for ${u.length} services (confidence: ${r.confidence.toFixed(2)})`),p({strategy:n,selectedExperiments:i,confidence:r.confidence,reasoning:r.reasoning||`PolicyGradient selected: ${n}`})}catch(t){return nu.error("PolicyGradient strategy selection failed:",t instanceof Error?t:void 0),p({strategy:"fallback",selectedExperiments:this.getDefaultExperiments(u.slice(0,3)),confidence:.5,reasoning:"Fallback to default (PolicyGradient error)"})}}generateExperimentsForServices(u,a){let t=[];for(let r of u)for(let i of a)t.push(this.createExperiment(`${r.name}-${i}-${Date.now()}`,`Test ${r.name} with ${i} fault`,i,r.name));return t}getDefaultExperiments(u){return this.generateExperimentsForServices(u,["latency","error"])}async calculateStrategyReward(u,a){let t=.5,r=u.length;(a.riskTolerance>.7&&r>5||a.riskTolerance<.3&&r<=3)&&(t+=.2),(a.availableCapacity>70&&r>5||a.availableCapacity<30&&r<=3)&&(t+=.1);let i=new Set(u.map(n=>n.faults[0]?.type));return t+=Math.min(.1,i.size/5),Math.max(0,Math.min(1,t))}async storeResiliencePattern(u,a,t){if(!(!this.qesona||!this.config.enableQESONA))try{let r={id:`chaos-${u.id}`,features:[u.faults.length/10,u.faults[0]?.duration?u.faults[0].duration/6e4:0,u.steadyState.probes.length/20,u.blastRadius.excludeProduction?1:0,(u.blastRadius.percentage??0)/100,a.hypothesisValidated?1:0,a.steadyStateVerified?1:0,a.incidents.length/10,a.incidents.filter(n=>n.severity==="critical").length/5,t]},i={type:a.hypothesisValidated?"validate":"reject",value:t};this.qesona.createPattern(r,i,{reward:a.hypothesisValidated?t:-t,success:a.hypothesisValidated,quality:t},"defect-prediction","chaos-resilience",{experimentId:u.id,experimentName:u.name,faultType:u.faults[0]?.type,hypothesisValidated:a.hypothesisValidated}),nu.info(`Stored resilience pattern for ${u.id} (validated: ${a.hypothesisValidated}, quality: ${t.toFixed(2)})`)}catch(r){nu.error("Failed to store resilience pattern:",r instanceof Error?r:void 0)}}async adaptStrategies(u,a){if(!this.qesona||!this.config.enableQESONA)return{shouldRunChaos:a.environment!=="production",recommendedFaults:["latency","error"],confidence:.5};try{let t={id:`chaos-adapt-${u.name}-${Date.now()}`,features:[u.hasFailover?0:1,a.riskTolerance,u.type==="api"?1:0,u.type==="database"?1:0,u.type==="cache"?1:0,a.environment==="production"?1:0,a.environment==="staging"?1:0,u.replicas/10,u.type==="worker"?1:0,u.type==="queue"?1:0]},r=await this.qesona.adaptPattern(t,"defect-prediction","chaos-resilience");if(r.success&&r.pattern){let i=r.pattern.outcome.success,n=this.getRecommendedFaults(r.pattern.action.type);return nu.info(`[chaos-resilience] QESONA adapted strategy for ${u.name}: shouldRun=${i}, faults=${n.join(",")}, confidence=${r.similarity.toFixed(2)}`),{shouldRunChaos:i,recommendedFaults:n,confidence:r.similarity}}return{shouldRunChaos:a.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}catch(t){return nu.error("QESONA strategy adaptation failed:",t instanceof Error?t:void 0),{shouldRunChaos:a.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}}getRecommendedFaults(u){switch(u){case"validate":return["latency","error","timeout"];case"reject":return["latency"];case"allocate":return["latency","cpu-stress"];case"scale-up":return["latency","error","timeout","packet-loss"];case"scale-down":return["latency"];default:return["latency","error"]}}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this))}async handleDeploymentApproved(u){if(!this.config.enableAutomatedExperiments)return;let a=u.payload;a.services&&await this.memory.set(`chaos-resilience:pending-assessment:${u.id}`,a.services,{namespace:"chaos-resilience",ttl:3600})}async handleQualityGateEvaluated(u){let a=u.payload;a.passed||await this.memory.set(`chaos-resilience:quality-gate-failures:${u.id}`,a,{namespace:"chaos-resilience",ttl:86400})}async loadWorkflowState(){let u=await this.memory.get("chaos-resilience:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("chaos-resilience:coordinator:workflows",u,{namespace:"chaos-resilience",persist:!0})}async verifyChaosExperiment(u,a){let t=O({id:A(),type:"chaos-experiment",confidence:a,description:`Verify chaos experiment safety: ${u.name} (${u.faultType}) on ${u.target}`,payload:u,detectedBy:"chaos-resilience-coordinator",severity:u.blastRadius==="full"?"critical":a>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(nu.info(`Chaos experiment '${u.name}' verified safe by consensus`),!0):(nu.warn(`Chaos experiment '${u.name}' NOT verified safe: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async verifyResilienceAssessment(u,a){let t=O({id:A(),type:"resilience-assessment",confidence:a,description:`Verify resilience assessment for ${u.service}: score ${u.overallScore}, ${u.weaknessCount} weaknesses`,payload:u,detectedBy:"chaos-resilience-coordinator",severity:u.overallScore<50?"critical":u.overallScore<70?"high":"medium"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(nu.info(`Resilience assessment for '${u.service}' verified by consensus`),!0):(nu.warn(`Resilience assessment for '${u.service}' NOT verified`),!1)}return!0}async verifyFailureInjection(u,a){let t=O({id:A(),type:"failure-injection",confidence:a,description:`Verify failure injection: ${u.faultType} on ${u.target} for ${u.duration}ms`,payload:u,detectedBy:"chaos-resilience-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(nu.info(`Failure injection '${u.faultType}' on '${u.target}' verified safe by consensus`),!0):(nu.warn(`Failure injection '${u.faultType}' NOT verified safe: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}};S();var $l=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}coordinator=null;chaosEngineer=null;loadTester=null;performanceProfiler=null;pluginConfig;get name(){return"chaos-resilience"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runChaosSuite:this.runChaosSuite.bind(this),runLoadTestSuite:this.runLoadTestSuite.bind(this),assessResilience:this.assessResilience.bind(this),generateExperiments:this.generateExperiments.bind(this),getResilienceDashboard:this.getResilienceDashboard.bind(this),createExperiment:this.createExperiment.bind(this),runExperiment:this.runExperiment.bind(this),abortExperiment:this.abortExperiment.bind(this),verifySteadyState:this.verifySteadyState.bind(this),injectFault:this.injectFault.bind(this),removeFault:this.removeFault.bind(this),createTest:this.createTest.bind(this),runTest:this.runTest.bind(this),runLoadTest:this.runTest.bind(this),stopTest:this.stopTest.bind(this),getRealtimeMetrics:this.getRealtimeMetrics.bind(this),generateFromTraffic:this.generateFromTraffic.bind(this),getExperimentHistory:this.getExperimentHistory.bind(this),testRecovery:this.testRecovery.bind(this),testFailover:this.testFailover.bind(this),testCircuitBreaker:this.testCircuitBreaker.bind(this),testRateLimiting:this.testRateLimiting.bind(this),selectChaosStrategy:this.coordinator.selectChaosStrategy.bind(this.coordinator),runStrategicChaosSuite:this.coordinator.runStrategicChaosSuite.bind(this.coordinator),getCoordinator:()=>this.coordinator,getChaosEngineer:()=>this.chaosEngineer,getChaosEngine:()=>this.chaosEngineer,getLoadTester:()=>this.loadTester,getPerformanceProfiler:()=>this.performanceProfiler,getResilienceAssessor:()=>this.performanceProfiler}}getTaskHandlers(){return new Map([["run-experiment",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.experimentId;return a?this.coordinator.runChaosSuite([a]):m(new Error("Invalid run-experiment payload: missing experimentId"))}],["run-load-test",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.testId;return a?this.coordinator.runLoadTestSuite([a]):m(new Error("Invalid run-load-test payload: missing testId"))}],["assess-resilience",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.services;return!a||a.length===0?m(new Error("Invalid assess-resilience payload: missing services")):this.coordinator.assessResilience(a)}],["inject-fault",async u=>{if(!this.chaosEngineer)return m(new Error("Chaos engineer not initialized"));let a=u.faultType,t=u.target;if(!a||!t)return m(new Error("Invalid inject-fault payload: missing faultType or target"));let r={id:`fault-${Date.now()}`,type:a,target:{type:"service",selector:t},parameters:u.parameters??{},duration:u.duration??3e4,probability:u.probability};return this.chaosEngineer.injectFault(r)}]])}async onInitialize(){this.chaosEngineer=new _0({memory:this.memory},this.pluginConfig.chaosEngineer),this.loadTester=new W0(this.memory,this.pluginConfig.loadTester),this.performanceProfiler=new $0(this.memory,this.pluginConfig.performanceProfiler),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.chaosEngineer=null,this.loadTester=null,this.performanceProfiler=null}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("security-compliance.VulnerabilityDetected",this.handleVulnerabilityDetected.bind(this))}async onEvent(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"quality-assessment.DeploymentApproved":await this.handleDeploymentApproved(u);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(u);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(u);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(u);break;default:break}}async runChaosSuite(u){this.ensureInitialized();try{let a=await this.coordinator.runChaosSuite(u);return a.success?this.trackSuccessfulOperation("chaos-suite"):this.trackFailedOperation(a.error),a}catch(a){return this.handleError(a)}}async runLoadTestSuite(u){this.ensureInitialized();try{let a=await this.coordinator.runLoadTestSuite(u);return a.success?this.trackSuccessfulOperation("load-suite"):this.trackFailedOperation(a.error),a}catch(a){return this.handleError(a)}}async assessResilience(u){this.ensureInitialized();try{return await this.coordinator.assessResilience(u)}catch(a){return this.handleError(a)}}async generateExperiments(u){this.ensureInitialized();try{return await this.coordinator.generateExperiments(u)}catch(a){return this.handleError(a)}}async getResilienceDashboard(){this.ensureInitialized();try{return await this.coordinator.getResilienceDashboard()}catch(u){return this.handleError(u)}}async createExperiment(u){this.ensureInitialized();try{return await this.chaosEngineer.createExperiment(u)}catch(a){return this.handleError(a)}}async runExperiment(u){this.ensureInitialized();try{let a=await this.chaosEngineer.runExperiment(u);return a.success&&await this.publishExperimentEvent(a.value),a}catch(a){return this.handleError(a)}}async abortExperiment(u,a){this.ensureInitialized();try{return await this.chaosEngineer.abortExperiment(u,a)}catch(t){return this.handleError(t)}}async verifySteadyState(u){this.ensureInitialized();try{return await this.chaosEngineer.verifySteadyState(u)}catch(a){return this.handleError(a)}}async injectFault(u){this.ensureInitialized();try{return await this.chaosEngineer.injectFault(u)}catch(a){return this.handleError(a)}}async removeFault(u){this.ensureInitialized();try{return await this.chaosEngineer.removeFault(u)}catch(a){return this.handleError(a)}}async getExperimentHistory(){this.ensureInitialized();try{return{success:!0,value:await this.memory.get("chaos-resilience:experiment-history")??[]}}catch(u){return this.handleError(u)}}async createTest(u){this.ensureInitialized();try{return await this.loadTester.createTest(u)}catch(a){return this.handleError(a)}}async runTest(u){this.ensureInitialized();try{let a=await this.loadTester.runTest(u);return a.success&&await this.publishLoadTestEvent(a.value),a}catch(a){return this.handleError(a)}}async stopTest(u){this.ensureInitialized();try{return await this.loadTester.stopTest(u)}catch(a){return this.handleError(a)}}async getRealtimeMetrics(u){this.ensureInitialized();try{return await this.loadTester.getRealtimeMetrics(u)}catch(a){return this.handleError(a)}}async generateFromTraffic(u,a){this.ensureInitialized();try{return await this.loadTester.generateFromTraffic(u,a)}catch(t){return this.handleError(t)}}async testRecovery(u,a,t){this.ensureInitialized();try{return await this.performanceProfiler.testRecovery(u,a,t)}catch(r){return this.handleError(r)}}async testFailover(u,a){this.ensureInitialized();try{return await this.performanceProfiler.testFailover(u,a)}catch(t){return this.handleError(t)}}async testCircuitBreaker(u,a){this.ensureInitialized();try{return await this.performanceProfiler.testCircuitBreaker(u,a)}catch(t){return this.handleError(t)}}async testRateLimiting(u,a){this.ensureInitialized();try{return await this.performanceProfiler.testRateLimiting(u,a)}catch(t){return this.handleError(t)}}async handleDeploymentApproved(u){let a=u.payload;a.services&&a.services.length>0&&await this.memory.set(`chaos-resilience:pending-assessment:${u.id}`,{services:a.services,triggeredAt:new Date,source:"deployment-approved"},{namespace:"chaos-resilience",ttl:3600})}async handleTestRunCompleted(u){let a=u.payload;await this.memory.set(`chaos-resilience:test-baseline:${a.runId}`,{duration:a.duration,successRate:a.passed/(a.passed+a.failed),timestamp:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleVulnerabilityDetected(u){let a=u.payload;(a.severity==="critical"||a.severity==="high")&&await this.memory.set(`chaos-resilience:security-tests:${a.vulnId}`,{vulnerabilityId:a.vulnId,severity:a.severity,file:a.file,triggeredAt:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleQualityGateEvaluated(u){let a=u.payload;a.checks?.some(r=>r.name==="resilience")&&await this.memory.set(`chaos-resilience:gate-context:${a.gateId}`,{gateId:a.gateId,passed:a.passed,checks:a.checks,timestamp:Date.now()},{namespace:"chaos-resilience",ttl:3600})}async publishExperimentEvent(u){await this.publishEvent("chaos-resilience.ExperimentCompleted",{experimentId:u.experimentId,status:u.status,hypothesisValidated:u.hypothesisValidated,steadyStateVerified:u.steadyStateVerified,faultCount:u.faultResults.length,incidentCount:u.incidents.length,duration:u.endTime?u.endTime.getTime()-u.startTime.getTime():0})}async publishLoadTestEvent(u){await this.publishEvent("chaos-resilience.LoadTestCompleted",{testId:u.testId,status:u.status,duration:u.duration,totalRequests:u.summary.totalRequests,successRate:u.summary.totalRequests>0?u.summary.successfulRequests/u.summary.totalRequests*100:0,p95ResponseTime:u.summary.p95ResponseTime,errorRate:u.summary.errorRate,assertionsPassed:u.assertionResults.filter(a=>a.passed).length,assertionsFailed:u.assertionResults.filter(a=>!a.passed).length})}ensureInitialized(){if(!this._initialized)throw new Error("ChaosResiliencePlugin is not initialized");if(!this.coordinator||!this.chaosEngineer||!this.loadTester||!this.performanceProfiler)throw new Error("ChaosResiliencePlugin services are not available")}handleError(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}};function OE(s,e,u,a){return new $l(s,e,u,a)}N();S();N();S();var R2u={minExperiencesForPattern:5,patternConfidenceThreshold:.7,maxPatternsPerDomain:100,anomalyDeviationThreshold:2,clusterSimilarityThreshold:.8,enableLLMSynthesis:!0,llmModelTier:2,llmMaxTokens:2048},_E=B.create("learning-optimization/learning-coordinator"),a0=class{config;memory;llmRouter;flashAttention=null;constructor(e,u={}){this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...R2u,...u}}async initializeFlashAttention(e){return this.flashAttention=await Ku("pattern-adaptation",e),_E.info("FlashAttention initialized for pattern adaptation"),this.flashAttention}injectFlashAttention(e){this.flashAttention=e}isFlashAttentionAvailable(){return this.flashAttention!==null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():[]}async computeSimilarityWithFlashAttention(e,u){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let a=Math.min(e.length,u.length),t=new Float32Array(a),r=new Float32Array(a),i=new Float32Array(a);for(let l=0;l<a;l++)t[l]=e[l],r[l]=u[l],i[l]=1;let n=await this.flashAttention.computeFlashAttention(t,r,i,1,a),o=Math.abs(n[0]);return Math.min(1,o)}async batchComputeSimilarities(e,u,a=5){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let t=new Float32Array(e),r=u.map(i=>new Float32Array(i));return this.flashAttention.computeTestSimilarity(t,r,a)}disposeFlashAttention(){this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null)}isLLMSynthesisAvailable(){return this.config.enableLLMSynthesis&&this.llmRouter!==void 0}getModelForTier(e){let u={1:"claude-3-haiku-20240307",2:"claude-sonnet-4-20250514",3:"claude-sonnet-4-20250514",4:"claude-opus-4-20250514"};return u[e]||u[2]}async synthesizePatternsWithLLM(e){if(!this.isLLMSynthesisAvailable())return null;try{let u=e.slice(0,10).map(t=>`- ${t.name}: ${t.type} (confidence: ${t.confidence.toFixed(2)})`).join(`
3019
+ `).filter(u=>u.trim()).length}}async captureMemoryState(e){let u=`resilience:state:${this.hashServiceName(e)}`,a=await this.memory.get(u);if(a)return a;let t={checksum:`init_${A().slice(0,8)}`,timestamp:new Date,records:0};return await this.memory.set(u,t,{namespace:"chaos-resilience"}),t}hashServiceName(e){let u=0;for(let a of e)u=(u<<5)-u+a.charCodeAt(0),u=u&u;return Math.abs(u).toString(16)}compareServiceStates(e,u){let a=e.checksum===u.checksum,t=e.records===u.records;return a||t}async getCircuitState(e){try{return this.httpClient.getCircuitState(e).state}catch{return"closed"}}async resetCircuit(e){try{this.httpClient.resetCircuit(e)}catch{Se.info(`Resetting circuit breaker for: ${e}`)}}async generateError(e){if(this.isRealServiceUrl(e))try{let u=`${e}/_chaos/error`;await this.httpClient.post(u,{},{timeout:5e3,retries:0});return}catch{Se.debug("Error generation API failed:")}Se.info(`Generating error for: ${e}`)}async sendSuccessfulRequest(e){if(!this.isRealServiceUrl(e))return!0;try{let u=await this.httpClient.get(e,{timeout:5e3,retries:1});return u.success&&u.value.ok}catch{return!0}}async sendRequestBatch(e,u){let a=[];if(!this.isRealServiceUrl(e))return this.simulateRequestBatch(u);for(let t=0;t<u;t++)try{let r=await this.httpClient.get(e,{timeout:2e3,retries:0,circuitBreaker:!1});if(r.success){let i=r.value,n=i.headers.get("Retry-After");a.push({statusCode:i.status,retryAfter:n?parseInt(n,10):void 0})}else a.push({statusCode:500,body:{error:r.error.message}})}catch{return[...a,...this.simulateRequestBatch(u-t)]}return a}simulateRequestBatch(e){let u=[];for(let t=0;t<e;t++)t>=75?u.push({statusCode:429,retryAfter:60,body:{error:"Rate limit exceeded"}}):u.push({statusCode:200});return u}async storeTestResult(e,u,a){await this.memory.set(`resilience:${e}:${u}`,a,{namespace:"chaos-resilience",persist:!0})}sleep(e){return new Promise(u=>setTimeout(u,e))}};cu();var T2u={stateSize:10,actionSize:5,hiddenLayers:[64,64],learningRatePG:.01,gammaPG:.99,entropyCoeff:.01},Vi=class extends Eu{policy;pgConfig;actions=[];episodeLog=[];constructor(e={}){super("policy-gradient","policy-based"),this.pgConfig={...T2u,...e},this.initializeActions(),this.policy=new $({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.pgConfig.learningRatePG})}async predict(e){this.initialized||await this.initialize();let u=this.prepareState(e),a=this.policy.forward(u),t=Cu.forward(a),r=this.sampleAction(t),i=this.actions[r],n=t[r],o=Math.max(.3,Math.min(1,n+.4));return this.episodeLog.push({state:e,action:i,reward:0}),{action:i,confidence:o,reasoning:this.generateReasoning(e,i,n)}}async trainCore(e){let u=this.groupIntoEpisodes(e),a=0;for(let t of u){let r=this.calculateReturns(t);for(let i=0;i<t.length;i++){let{state:n,action:o}=t[i],l=r[i],c=this.prepareState(n),E=this.policy.forward(c),d=Cu.forward(E),D=this.actionToIndex(o),C=-Math.log(d[D]+1e-10)*l;a+=Math.abs(C);let y=new Float32Array(d.length);for(let x=0;x<y.length;x++)x===D?y[x]=-l*(1-d[x]):y[x]=l*d[x];this.policy.backward(y);for(let x of this.policy.layers)x.update(this.pgConfig.learningRatePG)}}return this.episodeLog=[],{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((t,r)=>t+r,0)/this.rewardHistory.length,loss:a/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 Policy Gradient (REINFORCE) for Resource Allocation",capabilities:["Neural policy optimization","Monte Carlo return estimation","Entropy regularization"],hyperparameters:{stateSize:this.pgConfig.stateSize,actionSize:this.pgConfig.actionSize,learningRatePG:this.pgConfig.learningRatePG,gammaPG:this.pgConfig.gammaPG},stats:this.stats}}prepareState(e){let u=e.features.slice(0,this.pgConfig.stateSize);for(;u.length<this.pgConfig.stateSize;)u.push(0);let a=Math.max(...u.map(Math.abs));if(a>0)for(let t=0;t<u.length;t++)u[t]=u[t]/a;return new Float32Array(u)}initializeActions(){this.actions=[{type:"allocate",value:{agentType:"tester",count:1}},{type:"allocate",value:{agentType:"analyzer",count:1}},{type:"reallocate",value:{domain:"test-execution"}},{type:"scale-up",value:1},{type:"scale-down",value:1}],this.pgConfig.actionSize=this.actions.length,this.policy=new $({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.pgConfig.learningRatePG})}actionToIndex(e){let u=this.actionToKey(e);for(let a=0;a<this.actions.length;a++)if(this.actionToKey(this.actions[a])===u)return a;return 0}actionToKey(e){return`${e.type}:${JSON.stringify(e.value)}`}sampleAction(e){if(K()<this.config.explorationRate)return Du(0,this.actions.length);let u=K(),a=0;for(let t=0;t<e.length;t++)if(a+=e[t],u<=a)return t;return this.argmax(e)}argmax(e){let u=0,a=e[0];for(let t=1;t<e.length;t++)e[t]>a&&(a=e[t],u=t);return u}calculateReturns(e){let u=[],a=0;for(let t=e.length-1;t>=0;t--)a=e[t].reward+this.pgConfig.gammaPG*a,u.unshift(a);return u}groupIntoEpisodes(e){let u=[],a=[];for(let t of e)a.push(t),t.done&&(u.push(a),a=[]);return a.length>0&&u.push(a),u}generateReasoning(e,u,a){return`Neural Policy Gradient: ${u.type} (probability: ${a.toFixed(3)})`}async exportCustomData(){return{policy:this.policy.getParameters(),pgConfig:this.pgConfig}}async importCustomData(e){e.policy&&this.policy.setParameters(e.policy),e.pgConfig&&(this.pgConfig={...this.pgConfig,...e.pgConfig}),this.initialized=!0}async resetAlgorithm(){this.policy=new $({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new W]),learningRate:this.pgConfig.learningRatePG}),this.episodeLog=[]}};var M2u={maxConcurrentWorkflows:3,defaultTimeout:3e5,enableAutomatedExperiments:!1,publishEvents:!0,enablePolicyGradient:!0,enableQESONA:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},nu=B.create("chaos-resilience"),Oi=class extends Y{constructor(u,a,t,r={}){let i={...M2u,...r};super(u,"chaos-resilience",i,{verifyFindingTypes:["chaos-experiment","resilience-assessment","failure-injection"],...i.consensusConfig});this.memory=a;this.agentCoordinator=t;this.chaosGovernanceMixin=fc(this.domainName),this.chaosEngineer=new _0({memory:a}),this.loadTester=new W0(a),this.performanceProfiler=new $0(a)}chaosEngineer;loadTester;performanceProfiler;policyGradient;qesona;chaosGovernanceMixin;async onInitialize(){if(this.config.enablePolicyGradient)try{this.policyGradient=new Vi({stateSize:10,actionSize:5,hiddenLayers:[64,64]}),nu.info("PolicyGradient algorithm created successfully")}catch(u){throw nu.error("Failed to create PolicyGradient:",u instanceof Error?u:void 0),new Error(`PolicyGradient creation failed: ${k(u)}`)}if(this.config.enableQESONA)try{this.qesona=await gu({domain:"chaos-resilience",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),nu.info("PersistentSONAEngine initialized successfully")}catch(u){nu.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),nu.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.policyGradient=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runChaosSuite(u){let a=A();try{if(this.startWorkflow(a,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&nu.warn("Topology degraded, using conservative chaos strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn chaos agents"));let t=await this.spawnChaosAgent(a,"coordinator");if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=[],i=[],n=0,o=0;for(let c=0;c<u.length;c++){let E=u[c];this.updateWorkflowProgress(a,Math.round((c+1)/u.length*100));let d=await this.chaosEngineer.runExperiment(E);if(d.success){if(r.push(d.value),d.value.hypothesisValidated)n++;else{o++;let D=this.generateRecommendationsFromExperiment(d.value);i.push(...D)}this.config.publishEvents&&await this.publishExperimentCompleted(d.value)}else o++,i.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${E}: ${d.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(t.value),this.completeWorkflow(a);let l={totalExperiments:u.length,passed:n,failed:o,results:r,recommendations:i};return await this.storeReport("chaos-suite",a,l),p(l)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async runLoadTestSuite(u){let a=A();try{if(this.startWorkflow(a,"load-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&nu.warn("Topology degraded, using conservative load test parameters"),this.minCutMixin.shouldPauseOperations())return m(new Error("Load test suite paused: topology is in critical state"));let t=await this.spawnLoadTestAgent(a,"orchestrator");if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=[],i=[],n=0,o=0;for(let c=0;c<u.length;c++){let E=u[c];this.updateWorkflowProgress(a,Math.round((c+1)/u.length*100));let d=await this.loadTester.runTest(E);if(d.success){r.push(d.value),d.value.status==="completed"?n++:o++;let D=this.detectBottlenecks(d.value);i.push(...D),this.config.publishEvents&&await this.publishLoadTestCompleted(d.value)}else o++}await this.agentCoordinator.stop(t.value),this.completeWorkflow(a);let l={totalTests:u.length,passed:n,failed:o,results:r,bottlenecks:i};return await this.storeReport("load-suite",a,l),p(l)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async assessResilience(u){let a=A();try{if(this.startWorkflow(a,"assessment"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&nu.warn("Topology degraded, assessment may be limited"),this.minCutMixin.shouldPauseOperations())return m(new Error("Resilience assessment paused: topology is in critical state"));let t=new Map,r=[],i=[],n=[],o=await this.spawnAssessmentAgent(a);if(!o.success)return this.failWorkflow(a,o.error.message),m(o.error);this.addAgentToWorkflow(a,o.value);for(let E=0;E<u.length;E++){let d=u[E];this.updateWorkflowProgress(a,Math.round((E+1)/u.length*100));let D=await this.performanceProfiler.testRecovery(d,"latency",5e3),h=await this.performanceProfiler.testCircuitBreaker(d),C=await this.performanceProfiler.testRateLimiting(d,100),y=0;if(D.success&&D.value.passed)y+=33.3,r.push(`${d}: Fast recovery (${D.value.recoveryTime}ms)`);else{let x=D.success?D.value.recoveryTime:"unknown";i.push({service:d,type:"recovery",description:"Slow or failed recovery after fault",risk:P0.create(.7)}),n.push({priority:"high",category:"recovery",recommendation:`Improve ${d} recovery time - currently ${x}ms`,effort:"moderate"})}h.success&&h.value.passed?(y+=33.3,r.push(`${d}: Circuit breaker functioning correctly`)):(i.push({service:d,type:"circuit-breaker",description:"Circuit breaker not functioning as expected",risk:P0.create(.6)}),n.push({priority:"medium",category:"circuit-breaker",recommendation:`Review ${d} circuit breaker configuration`,effort:"minor"})),C.success&&C.value.passed?(y+=33.4,r.push(`${d}: Rate limiting effective`)):(i.push({service:d,type:"rate-limiting",description:"Rate limiting not properly configured",risk:P0.create(.5)}),n.push({priority:"medium",category:"rate-limiting",recommendation:`Configure rate limiting for ${d}`,effort:"minor"})),t.set(d,y)}let l=u.length>0?Array.from(t.values()).reduce((E,d)=>E+d,0)/u.length:0;await this.agentCoordinator.stop(o.value),this.completeWorkflow(a);let c={overallScore:l,serviceScores:t,strengths:r,weaknesses:i,recommendations:n};return await this.storeReport("assessment",a,c),p(c)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async generateExperiments(u){let a=A();try{this.startWorkflow(a,"experiment-generation");let t=[];for(let r of u.services){let i=this.generateServiceExperiments(r,u.dependencies);t.push(...i)}for(let r of u.criticalPaths){let i=this.generateCriticalPathExperiment(r,u);t.push(i)}for(let r of t)await this.chaosEngineer.createExperiment(r);return this.completeWorkflow(a),p(t)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async runStrategicChaosSuite(u,a){let t=A();try{if(this.startWorkflow(t,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&nu.warn("Topology degraded, adjusting strategic chaos parameters"),this.minCutMixin.shouldPauseOperations())return m(new Error("Strategic chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached, cannot spawn chaos agents"));let r=await this.selectChaosStrategy(u,a);if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i=r.value.selectedExperiments;if(nu.info(`[chaos-resilience] Using ${r.value.strategy} strategy with ${i.length} experiments (confidence: ${r.value.confidence.toFixed(2)})`),i.length===0)return this.completeWorkflow(t),p({totalExperiments:0,passed:0,failed:0,results:[],recommendations:[{priority:"low",category:"strategy",recommendation:"No experiments selected - consider adjusting strategy context",effort:"trivial"}]});let n=await this.spawnChaosAgent(t,"coordinator");if(!n.success)return this.failWorkflow(t,n.error.message),m(n.error);this.addAgentToWorkflow(t,n.value);let o=[],l=[],c=0,E=0;for(let D of i)await this.chaosEngineer.createExperiment(D);for(let D=0;D<i.length;D++){let h=i[D];this.updateWorkflowProgress(t,Math.round((D+1)/i.length*100));let C=await this.chaosEngineer.runExperiment(h.id);if(C.success){if(o.push(C.value),C.value.hypothesisValidated)c++;else{E++;let x=this.generateRecommendationsFromExperiment(C.value);l.push(...x)}let y=C.value.hypothesisValidated?.8:.2;await this.storeResiliencePattern(h,C.value,y),this.config.publishEvents&&await this.publishExperimentCompleted(C.value)}else E++,l.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${h.name}: ${C.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(n.value),this.completeWorkflow(t);let d={totalExperiments:i.length,passed:c,failed:E,results:o,recommendations:l};return await this.storeReport("strategic-chaos-suite",t,d),p(d)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async getResilienceDashboard(){try{let u=await this.memory.search("chaos:results:*",10),a=await this.memory.search("loadtest:results:*",10),t,r,i=0,n=0,o=0,l=0,c=0;for(let C of u){let y=await this.memory.get(C);y&&((!t||y.startTime>t)&&(t=y.startTime),i+=y.incidents.filter(x=>!x.resolved).length)}for(let C of a){let y=await this.memory.get(C);if(y&&y.timeline.length>0){let x=y.timeline[0].timestamp;(!r||x>r)&&(r=x),c++,y.status==="failed"&&l++}}let E=o>0?n/o:0,d=c>0?l/c*100:0,D="healthy";return i>5||d>25?D="unhealthy":(i>0||d>10)&&(D="degraded"),p({overallHealth:D,lastExperimentDate:t,lastLoadTestDate:r,activeIncidents:i,uptime:99.9,mttr:E,changeFailureRate:d})}catch(u){return m(g(u))}}async spawnChaosAgent(u,a){let t={name:`chaos-${a}-${u.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["chaos-engineering","fault-injection",a],config:{workflowId:u}};return this.agentCoordinator.spawn(t)}async spawnLoadTestAgent(u,a){let t={name:`loadtest-${a}-${u.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["load-testing","performance",a],config:{workflowId:u}};return this.agentCoordinator.spawn(t)}async spawnAssessmentAgent(u){let a={name:`assessment-${u.slice(0,8)}`,domain:"chaos-resilience",type:"analyzer",capabilities:["resilience-assessment","analysis"],config:{workflowId:u}};return this.agentCoordinator.spawn(a)}async publishExperimentCompleted(u){let a={id:A(),type:"chaos-resilience.ExperimentCompleted",timestamp:new Date,source:"chaos-resilience",payload:{experimentId:u.experimentId,status:u.status,hypothesisValidated:u.hypothesisValidated,incidentCount:u.incidents.length}};await this.eventBus.publish(a)}async publishLoadTestCompleted(u){let a={id:A(),type:"chaos-resilience.LoadTestCompleted",timestamp:new Date,source:"chaos-resilience",payload:{testId:u.testId,status:u.status,summary:u.summary,assertionsPassed:u.assertionResults.filter(t=>t.passed).length,assertionsFailed:u.assertionResults.filter(t=>!t.passed).length}};await this.eventBus.publish(a)}generateRecommendationsFromExperiment(u){let a=[];u.hypothesisValidated||a.push({priority:"high",category:"hypothesis-failure",recommendation:`Experiment ${u.experimentId} hypothesis was not validated - review system behavior under fault conditions`,effort:"moderate"}),u.steadyStateVerified||a.push({priority:"critical",category:"steady-state",recommendation:"System did not maintain steady state - investigate stability issues",effort:"major"});for(let t of u.incidents)(t.severity==="critical"||t.severity==="high")&&a.push({priority:t.severity,category:"incident",recommendation:`Address ${t.type}: ${t.message}`,effort:"moderate"});return a}detectBottlenecks(u){let a=[];return u.summary.p95ResponseTime>1e3&&a.push({location:"api",type:"network",description:`P95 response time is ${u.summary.p95ResponseTime}ms (>1000ms)`,impact:u.summary.p95ResponseTime>2e3?"high":"medium",recommendation:"Investigate API response time, consider caching or query optimization"}),u.summary.errorRate>5&&a.push({location:"service",type:"cpu",description:`Error rate is ${u.summary.errorRate.toFixed(2)}% (>5%)`,impact:u.summary.errorRate>10?"high":"medium",recommendation:"Investigate error causes, scale resources if under load"}),u.summary.requestsPerSecond<10&&a.push({location:"backend",type:"io",description:`Low throughput: ${u.summary.requestsPerSecond.toFixed(2)} RPS`,impact:"medium",recommendation:"Review I/O operations, database queries, and connection pooling"}),a}generateServiceExperiments(u,a){let t=[];t.push(this.createExperiment(`${u.name}-latency`,`Test ${u.name} behavior under latency`,"latency",u.name)),t.push(this.createExperiment(`${u.name}-error`,`Test ${u.name} error handling`,"error",u.name)),t.push(this.createExperiment(`${u.name}-cpu-stress`,`Test ${u.name} under CPU stress`,"cpu-stress",u.name));let r=a.filter(i=>i.from===u.name);for(let i of r)i.criticality==="critical"&&t.push(this.createExperiment(`${u.name}-${i.to}-failure`,`Test ${u.name} when ${i.to} fails`,"error",i.to));return t}generateCriticalPathExperiment(u,a){let t=u.join("-");return{id:A(),name:`critical-path-${t}`,description:`Test critical path: ${u.join(" -> ")}`,hypothesis:{statement:"System should handle partial path failure gracefully",metrics:[{metric:"error_rate",operator:"lt",value:10},{metric:"response_time_ms",operator:"lt",value:2e3}],tolerances:[{metric:"error_rate",maxDeviation:5,unit:"percent"}]},steadyState:{description:"All services in path are healthy",probes:u.map(r=>({name:`${r}-health`,type:"http",target:`http://${r}/health`,expected:{status:200},timeout:5e3}))},faults:u.slice(0,-1).map(r=>({id:A(),type:"latency",target:{type:"service",selector:r},parameters:{latencyMs:500},duration:3e4})),blastRadius:{scope:"subset",percentage:50,excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 20"},{type:"timeout",condition:"duration > 60000"}],steps:[{order:1,action:"Remove all faults",timeout:5e3},{order:2,action:"Verify service health"}]}}}createExperiment(u,a,t,r){return{id:A(),name:u,description:a,hypothesis:{statement:`${r} should recover within 5 seconds from ${t}`,metrics:[{metric:"response_time_ms",operator:"lt",value:1e3},{metric:"error_rate",operator:"lt",value:5}],tolerances:[{metric:"response_time_ms",maxDeviation:50,unit:"percent"}]},steadyState:{description:`${r} is healthy and responsive`,probes:[{name:`${r}-health`,type:"http",target:`http://${r}/health`,expected:{status:200},timeout:5e3}]},faults:[{id:A(),type:t,target:{type:"service",selector:r},parameters:this.getDefaultFaultParameters(t),duration:3e4}],blastRadius:{scope:"single",excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 50"}],steps:[{order:1,action:`Remove ${t} fault`},{order:2,action:"Verify recovery"}]}}}getDefaultFaultParameters(u){return{latency:{latencyMs:500},error:{errorCode:500},timeout:{timeoutMs:3e4},"packet-loss":{packetLossPercent:10},"cpu-stress":{cpuPercent:80},"memory-stress":{memoryBytes:268435456},"disk-stress":{},"network-partition":{},"dns-failure":{},"process-kill":{}}[u]||{}}async storeReport(u,a,t){await this.memory.set(`chaos-resilience:reports:${u}:${a}`,t,{namespace:"chaos-resilience",persist:!0})}async selectChaosStrategy(u,a){if(!this.policyGradient||!this.config.enablePolicyGradient)return p({strategy:"default",selectedExperiments:this.getDefaultExperiments(u.slice(0,3)),confidence:1,reasoning:"Default strategy (PolicyGradient disabled)"});if(u.length===0)return p({strategy:"empty",selectedExperiments:[],confidence:1,reasoning:"No services provided"});try{let t={id:`chaos-strategy-${Date.now()}`,features:[a.riskTolerance,a.availableCapacity/100,u.length/50,u.filter(c=>!c.hasFailover).length/Math.max(1,u.length),u.filter(c=>c.type==="database").length/Math.max(1,u.length),a.environment==="production"?0:1,a.environment==="staging"?1:0,u.filter(c=>c.type==="cache").length/Math.max(1,u.length),u.filter(c=>c.type==="queue").length/Math.max(1,u.length),u.reduce((c,E)=>c+E.replicas,0)/Math.max(1,u.length*5)]},r=await this.policyGradient.predict(t),i=[],n="default";switch(r.action.type){case"allocate":let c=typeof r.action.value=="object"?r.action.value:null;if(c&&"agentType"in c&&c.agentType==="tester"){let d=u.filter(D=>!D.hasFailover||D.type==="database").slice(0,3);i=this.generateExperimentsForServices(d,["latency","error"]),n="allocate-critical"}break;case"reallocate":let E=typeof r.action.value=="object"?r.action.value:null;E&&"domain"in E&&E.domain==="test-execution"&&(i=this.generateExperimentsForServices(u.slice(0,5),["cpu-stress","memory-stress"]),n="reallocate-resource-stress");break;case"scale-up":i=this.generateExperimentsForServices(u,["latency","error","timeout"]),n="scale-up-comprehensive";break;case"scale-down":i=this.generateExperimentsForServices(u.slice(0,2),["latency"]),n="scale-down-minimal";break;default:i=this.getDefaultExperiments(u.slice(0,3)),n="default";break}let o=await this.calculateStrategyReward(i,a),l=r.action;return await this.policyGradient.train({state:t,action:l,reward:o,nextState:t,done:!0}),nu.info(`[chaos-resilience] PolicyGradient selected ${n} strategy for ${u.length} services (confidence: ${r.confidence.toFixed(2)})`),p({strategy:n,selectedExperiments:i,confidence:r.confidence,reasoning:r.reasoning||`PolicyGradient selected: ${n}`})}catch(t){return nu.error("PolicyGradient strategy selection failed:",t instanceof Error?t:void 0),p({strategy:"fallback",selectedExperiments:this.getDefaultExperiments(u.slice(0,3)),confidence:.5,reasoning:"Fallback to default (PolicyGradient error)"})}}generateExperimentsForServices(u,a){let t=[];for(let r of u)for(let i of a)t.push(this.createExperiment(`${r.name}-${i}-${Date.now()}`,`Test ${r.name} with ${i} fault`,i,r.name));return t}getDefaultExperiments(u){return this.generateExperimentsForServices(u,["latency","error"])}async calculateStrategyReward(u,a){let t=.5,r=u.length;(a.riskTolerance>.7&&r>5||a.riskTolerance<.3&&r<=3)&&(t+=.2),(a.availableCapacity>70&&r>5||a.availableCapacity<30&&r<=3)&&(t+=.1);let i=new Set(u.map(n=>n.faults[0]?.type));return t+=Math.min(.1,i.size/5),Math.max(0,Math.min(1,t))}async storeResiliencePattern(u,a,t){if(!(!this.qesona||!this.config.enableQESONA))try{let r={id:`chaos-${u.id}`,features:[u.faults.length/10,u.faults[0]?.duration?u.faults[0].duration/6e4:0,u.steadyState.probes.length/20,u.blastRadius.excludeProduction?1:0,(u.blastRadius.percentage??0)/100,a.hypothesisValidated?1:0,a.steadyStateVerified?1:0,a.incidents.length/10,a.incidents.filter(n=>n.severity==="critical").length/5,t]},i={type:a.hypothesisValidated?"validate":"reject",value:t};this.qesona.createPattern(r,i,{reward:a.hypothesisValidated?t:-t,success:a.hypothesisValidated,quality:t},"defect-prediction","chaos-resilience",{experimentId:u.id,experimentName:u.name,faultType:u.faults[0]?.type,hypothesisValidated:a.hypothesisValidated}),nu.info(`Stored resilience pattern for ${u.id} (validated: ${a.hypothesisValidated}, quality: ${t.toFixed(2)})`)}catch(r){nu.error("Failed to store resilience pattern:",r instanceof Error?r:void 0)}}async adaptStrategies(u,a){if(!this.qesona||!this.config.enableQESONA)return{shouldRunChaos:a.environment!=="production",recommendedFaults:["latency","error"],confidence:.5};try{let t={id:`chaos-adapt-${u.name}-${Date.now()}`,features:[u.hasFailover?0:1,a.riskTolerance,u.type==="api"?1:0,u.type==="database"?1:0,u.type==="cache"?1:0,a.environment==="production"?1:0,a.environment==="staging"?1:0,u.replicas/10,u.type==="worker"?1:0,u.type==="queue"?1:0]},r=await this.qesona.adaptPattern(t,"defect-prediction","chaos-resilience");if(r.success&&r.pattern){let i=r.pattern.outcome.success,n=this.getRecommendedFaults(r.pattern.action.type);return nu.info(`[chaos-resilience] QESONA adapted strategy for ${u.name}: shouldRun=${i}, faults=${n.join(",")}, confidence=${r.similarity.toFixed(2)}`),{shouldRunChaos:i,recommendedFaults:n,confidence:r.similarity}}return{shouldRunChaos:a.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}catch(t){return nu.error("QESONA strategy adaptation failed:",t instanceof Error?t:void 0),{shouldRunChaos:a.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}}getRecommendedFaults(u){switch(u){case"validate":return["latency","error","timeout"];case"reject":return["latency"];case"allocate":return["latency","cpu-stress"];case"scale-up":return["latency","error","timeout","packet-loss"];case"scale-down":return["latency"];default:return["latency","error"]}}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this))}async handleDeploymentApproved(u){if(!this.config.enableAutomatedExperiments)return;let a=u.payload;a.services&&await this.memory.set(`chaos-resilience:pending-assessment:${u.id}`,a.services,{namespace:"chaos-resilience",ttl:3600})}async handleQualityGateEvaluated(u){let a=u.payload;a.passed||await this.memory.set(`chaos-resilience:quality-gate-failures:${u.id}`,a,{namespace:"chaos-resilience",ttl:86400})}async loadWorkflowState(){let u=await this.memory.get("chaos-resilience:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("chaos-resilience:coordinator:workflows",u,{namespace:"chaos-resilience",persist:!0})}async verifyChaosExperiment(u,a){let t=O({id:A(),type:"chaos-experiment",confidence:a,description:`Verify chaos experiment safety: ${u.name} (${u.faultType}) on ${u.target}`,payload:u,detectedBy:"chaos-resilience-coordinator",severity:u.blastRadius==="full"?"critical":a>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(nu.info(`Chaos experiment '${u.name}' verified safe by consensus`),!0):(nu.warn(`Chaos experiment '${u.name}' NOT verified safe: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async verifyResilienceAssessment(u,a){let t=O({id:A(),type:"resilience-assessment",confidence:a,description:`Verify resilience assessment for ${u.service}: score ${u.overallScore}, ${u.weaknessCount} weaknesses`,payload:u,detectedBy:"chaos-resilience-coordinator",severity:u.overallScore<50?"critical":u.overallScore<70?"high":"medium"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(nu.info(`Resilience assessment for '${u.service}' verified by consensus`),!0):(nu.warn(`Resilience assessment for '${u.service}' NOT verified`),!1)}return!0}async verifyFailureInjection(u,a){let t=O({id:A(),type:"failure-injection",confidence:a,description:`Verify failure injection: ${u.faultType} on ${u.target} for ${u.duration}ms`,payload:u,detectedBy:"chaos-resilience-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(nu.info(`Failure injection '${u.faultType}' on '${u.target}' verified safe by consensus`),!0):(nu.warn(`Failure injection '${u.faultType}' NOT verified safe: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}};S();var $l=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}coordinator=null;chaosEngineer=null;loadTester=null;performanceProfiler=null;pluginConfig;get name(){return"chaos-resilience"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runChaosSuite:this.runChaosSuite.bind(this),runLoadTestSuite:this.runLoadTestSuite.bind(this),assessResilience:this.assessResilience.bind(this),generateExperiments:this.generateExperiments.bind(this),getResilienceDashboard:this.getResilienceDashboard.bind(this),createExperiment:this.createExperiment.bind(this),runExperiment:this.runExperiment.bind(this),abortExperiment:this.abortExperiment.bind(this),verifySteadyState:this.verifySteadyState.bind(this),injectFault:this.injectFault.bind(this),removeFault:this.removeFault.bind(this),createTest:this.createTest.bind(this),runTest:this.runTest.bind(this),runLoadTest:this.runTest.bind(this),stopTest:this.stopTest.bind(this),getRealtimeMetrics:this.getRealtimeMetrics.bind(this),generateFromTraffic:this.generateFromTraffic.bind(this),getExperimentHistory:this.getExperimentHistory.bind(this),testRecovery:this.testRecovery.bind(this),testFailover:this.testFailover.bind(this),testCircuitBreaker:this.testCircuitBreaker.bind(this),testRateLimiting:this.testRateLimiting.bind(this),selectChaosStrategy:this.coordinator.selectChaosStrategy.bind(this.coordinator),runStrategicChaosSuite:this.coordinator.runStrategicChaosSuite.bind(this.coordinator),getCoordinator:()=>this.coordinator,getChaosEngineer:()=>this.chaosEngineer,getChaosEngine:()=>this.chaosEngineer,getLoadTester:()=>this.loadTester,getPerformanceProfiler:()=>this.performanceProfiler,getResilienceAssessor:()=>this.performanceProfiler}}getTaskHandlers(){return new Map([["run-experiment",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.experimentId;return a?this.coordinator.runChaosSuite([a]):m(new Error("Invalid run-experiment payload: missing experimentId"))}],["run-load-test",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.testId;return a?this.coordinator.runLoadTestSuite([a]):m(new Error("Invalid run-load-test payload: missing testId"))}],["assess-resilience",async u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.services;return!a||a.length===0?m(new Error("Invalid assess-resilience payload: missing services")):this.coordinator.assessResilience(a)}],["inject-fault",async u=>{if(!this.chaosEngineer)return m(new Error("Chaos engineer not initialized"));let a=u.faultType,t=u.target;if(!a||!t)return m(new Error("Invalid inject-fault payload: missing faultType or target"));let r={id:`fault-${Date.now()}`,type:a,target:{type:"service",selector:t},parameters:u.parameters??{},duration:u.duration??3e4,probability:u.probability};return this.chaosEngineer.injectFault(r)}]])}async onInitialize(){this.chaosEngineer=new _0({memory:this.memory},this.pluginConfig.chaosEngineer),this.loadTester=new W0(this.memory,this.pluginConfig.loadTester),this.performanceProfiler=new $0(this.memory,this.pluginConfig.performanceProfiler),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.chaosEngineer=null,this.loadTester=null,this.performanceProfiler=null}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("security-compliance.VulnerabilityDetected",this.handleVulnerabilityDetected.bind(this))}async onEvent(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"quality-assessment.DeploymentApproved":await this.handleDeploymentApproved(u);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(u);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(u);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(u);break;default:break}}async runChaosSuite(u){this.ensureInitialized();try{let a=await this.coordinator.runChaosSuite(u);return a.success?this.trackSuccessfulOperation("chaos-suite"):this.trackFailedOperation(a.error),a}catch(a){return this.handleError(a)}}async runLoadTestSuite(u){this.ensureInitialized();try{let a=await this.coordinator.runLoadTestSuite(u);return a.success?this.trackSuccessfulOperation("load-suite"):this.trackFailedOperation(a.error),a}catch(a){return this.handleError(a)}}async assessResilience(u){this.ensureInitialized();try{return await this.coordinator.assessResilience(u)}catch(a){return this.handleError(a)}}async generateExperiments(u){this.ensureInitialized();try{return await this.coordinator.generateExperiments(u)}catch(a){return this.handleError(a)}}async getResilienceDashboard(){this.ensureInitialized();try{return await this.coordinator.getResilienceDashboard()}catch(u){return this.handleError(u)}}async createExperiment(u){this.ensureInitialized();try{return await this.chaosEngineer.createExperiment(u)}catch(a){return this.handleError(a)}}async runExperiment(u){this.ensureInitialized();try{let a=await this.chaosEngineer.runExperiment(u);return a.success&&await this.publishExperimentEvent(a.value),a}catch(a){return this.handleError(a)}}async abortExperiment(u,a){this.ensureInitialized();try{return await this.chaosEngineer.abortExperiment(u,a)}catch(t){return this.handleError(t)}}async verifySteadyState(u){this.ensureInitialized();try{return await this.chaosEngineer.verifySteadyState(u)}catch(a){return this.handleError(a)}}async injectFault(u){this.ensureInitialized();try{return await this.chaosEngineer.injectFault(u)}catch(a){return this.handleError(a)}}async removeFault(u){this.ensureInitialized();try{return await this.chaosEngineer.removeFault(u)}catch(a){return this.handleError(a)}}async getExperimentHistory(){this.ensureInitialized();try{return{success:!0,value:await this.memory.get("chaos-resilience:experiment-history")??[]}}catch(u){return this.handleError(u)}}async createTest(u){this.ensureInitialized();try{return await this.loadTester.createTest(u)}catch(a){return this.handleError(a)}}async runTest(u){this.ensureInitialized();try{let a=await this.loadTester.runTest(u);return a.success&&await this.publishLoadTestEvent(a.value),a}catch(a){return this.handleError(a)}}async stopTest(u){this.ensureInitialized();try{return await this.loadTester.stopTest(u)}catch(a){return this.handleError(a)}}async getRealtimeMetrics(u){this.ensureInitialized();try{return await this.loadTester.getRealtimeMetrics(u)}catch(a){return this.handleError(a)}}async generateFromTraffic(u,a){this.ensureInitialized();try{return await this.loadTester.generateFromTraffic(u,a)}catch(t){return this.handleError(t)}}async testRecovery(u,a,t){this.ensureInitialized();try{return await this.performanceProfiler.testRecovery(u,a,t)}catch(r){return this.handleError(r)}}async testFailover(u,a){this.ensureInitialized();try{return await this.performanceProfiler.testFailover(u,a)}catch(t){return this.handleError(t)}}async testCircuitBreaker(u,a){this.ensureInitialized();try{return await this.performanceProfiler.testCircuitBreaker(u,a)}catch(t){return this.handleError(t)}}async testRateLimiting(u,a){this.ensureInitialized();try{return await this.performanceProfiler.testRateLimiting(u,a)}catch(t){return this.handleError(t)}}async handleDeploymentApproved(u){let a=u.payload;a.services&&a.services.length>0&&await this.memory.set(`chaos-resilience:pending-assessment:${u.id}`,{services:a.services,triggeredAt:new Date,source:"deployment-approved"},{namespace:"chaos-resilience",ttl:3600})}async handleTestRunCompleted(u){let a=u.payload;await this.memory.set(`chaos-resilience:test-baseline:${a.runId}`,{duration:a.duration,successRate:a.passed/(a.passed+a.failed),timestamp:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleVulnerabilityDetected(u){let a=u.payload;(a.severity==="critical"||a.severity==="high")&&await this.memory.set(`chaos-resilience:security-tests:${a.vulnId}`,{vulnerabilityId:a.vulnId,severity:a.severity,file:a.file,triggeredAt:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleQualityGateEvaluated(u){let a=u.payload;a.checks?.some(r=>r.name==="resilience")&&await this.memory.set(`chaos-resilience:gate-context:${a.gateId}`,{gateId:a.gateId,passed:a.passed,checks:a.checks,timestamp:Date.now()},{namespace:"chaos-resilience",ttl:3600})}async publishExperimentEvent(u){await this.publishEvent("chaos-resilience.ExperimentCompleted",{experimentId:u.experimentId,status:u.status,hypothesisValidated:u.hypothesisValidated,steadyStateVerified:u.steadyStateVerified,faultCount:u.faultResults.length,incidentCount:u.incidents.length,duration:u.endTime?u.endTime.getTime()-u.startTime.getTime():0})}async publishLoadTestEvent(u){await this.publishEvent("chaos-resilience.LoadTestCompleted",{testId:u.testId,status:u.status,duration:u.duration,totalRequests:u.summary.totalRequests,successRate:u.summary.totalRequests>0?u.summary.successfulRequests/u.summary.totalRequests*100:0,p95ResponseTime:u.summary.p95ResponseTime,errorRate:u.summary.errorRate,assertionsPassed:u.assertionResults.filter(a=>a.passed).length,assertionsFailed:u.assertionResults.filter(a=>!a.passed).length})}ensureInitialized(){if(!this._initialized)throw new Error("ChaosResiliencePlugin is not initialized");if(!this.coordinator||!this.chaosEngineer||!this.loadTester||!this.performanceProfiler)throw new Error("ChaosResiliencePlugin services are not available")}handleError(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}};function OE(s,e,u,a){return new $l(s,e,u,a)}N();S();N();S();var R2u={minExperiencesForPattern:5,patternConfidenceThreshold:.7,maxPatternsPerDomain:100,anomalyDeviationThreshold:2,clusterSimilarityThreshold:.8,enableLLMSynthesis:!0,llmModelTier:2,llmMaxTokens:2048},_E=B.create("learning-optimization/learning-coordinator"),a0=class{config;memory;llmRouter;flashAttention=null;constructor(e,u={}){this.memory=e.memory,this.llmRouter=e.llmRouter,this.config={...R2u,...u}}async initializeFlashAttention(e){return this.flashAttention=await Ku("pattern-adaptation",e),_E.info("FlashAttention initialized for pattern adaptation"),this.flashAttention}injectFlashAttention(e){this.flashAttention=e}isFlashAttentionAvailable(){return this.flashAttention!==null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():[]}async computeSimilarityWithFlashAttention(e,u){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let a=Math.min(e.length,u.length),t=new Float32Array(a),r=new Float32Array(a),i=new Float32Array(a);for(let l=0;l<a;l++)t[l]=e[l],r[l]=u[l],i[l]=1;let n=await this.flashAttention.computeFlashAttention(t,r,i,1,a),o=Math.abs(n[0]);return Math.min(1,o)}async batchComputeSimilarities(e,u,a=5){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let t=new Float32Array(e),r=u.map(i=>new Float32Array(i));return this.flashAttention.computeTestSimilarity(t,r,a)}disposeFlashAttention(){this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null)}isLLMSynthesisAvailable(){return this.config.enableLLMSynthesis&&this.llmRouter!==void 0}getModelForTier(e){let u={1:"claude-3-haiku-20240307",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return u[e]||u[2]}async synthesizePatternsWithLLM(e){if(!this.isLLMSynthesisAvailable())return null;try{let u=e.slice(0,10).map(t=>`- ${t.name}: ${t.type} (confidence: ${t.confidence.toFixed(2)})`).join(`
3020
3020
  `);return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze these learned QE patterns and synthesize insights:
3021
3021
  ${u}
3022
3022
 
@@ -3026,4 +3026,4 @@ Provide:
3026
3026
  3. Recommendations for pattern application`}],maxTokens:this.config.llmMaxTokens})).content}catch{return _E.warn("LLM synthesis failed:"),null}}async learnPattern(e){try{if(e.length<this.config.minExperiencesForPattern)return m(new Error(`Need at least ${this.config.minExperiencesForPattern} experiences to learn a pattern`));let u=this.extractCommonActions(e),a=this.calculateSuccessRate(e);if(a<this.config.patternConfidenceThreshold)return m(new Error(`Success rate ${a} below threshold ${this.config.patternConfidenceThreshold}`));let t=this.inferPatternType(e),r=e[0].domain,i=this.generatePatternTemplate(e,u),n=this.extractPatternContext(e),o={id:A(),type:t,domain:r,name:`${t}-${r}-${Date.now()}`,description:`Learned pattern from ${e.length} experiences with ${a*100}% success rate`,confidence:a,usageCount:0,successRate:a,context:n,template:i,createdAt:new Date,lastUsedAt:new Date};return await this.storePattern(o),await this.recordPatternCreation(o,e),p(o)}catch(u){return m(g(u))}}async findMatchingPatterns(e,u=10){try{let a=[],t=await this.memory.search("learning:pattern:*",100);for(let r of t){let i=await this.memory.get(r);i&&this.matchesContext(i,e)&&a.push(i)}return a.sort((r,i)=>{let n=r.confidence*.6+r.successRate*.4;return i.confidence*.6+i.successRate*.4-n}),p(a.slice(0,u))}catch(a){return m(g(a))}}async applyPattern(e,u){try{let a=e.template.content;for(let t of e.template.variables){let r=u[t.name]??t.defaultValue;if(t.required&&r===void 0)return m(new Error(`Required variable ${t.name} not provided`));a=a.replace(new RegExp(`\\{\\{${t.name}\\}\\}`,"g"),String(r??""))}return await this.updatePatternUsage(e.id),p(a)}catch(a){return m(g(a))}}async updatePatternFeedback(e,u){try{let a=`learning:pattern:${e}`,t=await this.memory.get(a);if(!t)return m(new Error(`Pattern ${e} not found`));let r=.1,i=r*(u?1:0)+(1-r)*t.successRate,n=Math.min(t.usageCount/100,1),o=i*.7+n*.3,l={...t,successRate:i,confidence:o,usageCount:t.usageCount+1,lastUsedAt:new Date};return await this.memory.set(a,l,{namespace:"learning-optimization",persist:!0}),p(void 0)}catch(a){return m(g(a))}}async consolidatePatterns(e){try{if(e.length<2)return m(new Error("Need at least 2 patterns to consolidate"));let u=[];for(let i of e){let n=await this.memory.get(`learning:pattern:${i}`);n&&u.push(n)}if(u.length<2)return m(new Error("Not enough valid patterns found"));let a=u.reduce((i,n)=>n.successRate>i.successRate?n:i),t={language:a.context.language,framework:a.context.framework,testType:a.context.testType,codeContext:a.context.codeContext,tags:[...new Set(u.flatMap(i=>i.context.tags))]},r={id:A(),type:a.type,domain:a.domain,name:`consolidated-${a.name}`,description:`Consolidated from ${u.length} patterns`,confidence:this.calculateConsolidatedConfidence(u),usageCount:u.reduce((i,n)=>i+n.usageCount,0),successRate:this.calculateWeightedSuccessRate(u),context:t,template:a.template,createdAt:new Date,lastUsedAt:new Date};await this.storePattern(r);for(let i of u)await this.archivePattern(i.id);return p(r)}catch(u){return m(g(u))}}async getPatternStats(e){try{let u=await this.memory.search("learning:pattern:*",500),a=[];for(let l of u){let c=await this.memory.get(l);c&&(!e||c.domain===e)&&a.push(c)}let t={"test-pattern":0,"fix-pattern":0,"optimization-pattern":0,"detection-pattern":0,"workflow-pattern":0,"failure-pattern":0},r={"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},i=0,n=0;for(let l of a)t[l.type]++,r[l.domain]++,i+=l.confidence,n+=l.successRate;let o=a.sort((l,c)=>c.successRate-l.successRate).slice(0,10);return p({totalPatterns:a.length,byType:t,byDomain:r,avgConfidence:a.length>0?i/a.length:0,avgSuccessRate:a.length>0?n/a.length:0,topPatterns:o})}catch(u){return m(g(u))}}async recordExperience(e){try{let u=A(),a={...e,id:u,timestamp:new Date};return await this.memory.set(`learning:experience:${u}`,a,{namespace:"learning-optimization",ttl:86400*30}),await this.indexExperience(a),p(u)}catch(u){return m(g(u))}}async mineExperiences(e,u){try{let a=await this.getExperiencesByDomainAndTime(e,u);if(a.length===0)return p({experienceCount:0,successRate:0,avgReward:0,patterns:[],anomalies:[],recommendations:["No experiences found in the given time range"]});let t=this.calculateSuccessRate(a),r=this.calculateAverageReward(a),i=await this.extractPatternsFromExperiences(a),n=this.detectAnomalies(a),o=this.generateRecommendations(a,t,n);return p({experienceCount:a.length,successRate:t,avgReward:r,patterns:i,anomalies:n,recommendations:o})}catch(a){return m(g(a))}}calculateReward(e,u){let a=e.outcome[u.metric]??0,t;u.direction==="maximize"?t=Math.min(a/100,1):t=Math.max(1-a/100,0);let r=0;for(let o of u.constraints){let l=e.outcome[o.metric]??0;this.isConstraintViolated(o,l)&&(r+=.2)}let i=e.success?.5:0,n=Math.max(0,t+i-r);return Math.min(1,n)}async getReplayBuffer(e,u=100){try{let a=await this.memory.search(`learning:experience:index:agent:${e.value}:*`,u),t=[];for(let r of a){let i=await this.memory.get(r);if(i){let n=await this.memory.get(`learning:experience:${i}`);n&&t.push(n)}}return t.sort((r,i)=>i.timestamp.getTime()-r.timestamp.getTime()),p(t.slice(0,u))}catch(a){return m(g(a))}}async clusterExperiences(e){try{if(e.length===0)return p([]);let u=new Map;for(let r of e){let i=!1;for(let[n,o]of u)if(this.actionsSimilar(r.action,n)){o.push(r),i=!0;break}i||u.set(r.action,[r])}let a=[],t=0;for(let[r,i]of u)if(i.length>=2){let n=this.calculateCentroid(i),o=this.extractCommonActions(i),l=this.calculateAverageReward(i);a.push({id:`cluster-${t++}`,centroid:n,experiences:i,commonActions:o,avgReward:l})}return p(a)}catch(u){return m(g(u))}}async storePattern(e){await this.memory.set(`learning:pattern:${e.id}`,e,{namespace:"learning-optimization",persist:!0})}async archivePattern(e){let u=`learning:pattern:${e}`,a=await this.memory.get(u);a&&(await this.memory.set(`learning:pattern:archived:${e}`,a,{namespace:"learning-optimization",persist:!0}),await this.memory.delete(u))}async updatePatternUsage(e){let u=`learning:pattern:${e}`,a=await this.memory.get(u);if(a){let t={...a,usageCount:a.usageCount+1,lastUsedAt:new Date};await this.memory.set(u,t,{namespace:"learning-optimization",persist:!0})}}async recordPatternCreation(e,u){await this.memory.set(`learning:pattern:creation:${e.id}`,{patternId:e.id,experienceIds:u.map(a=>a.id),createdAt:new Date},{namespace:"learning-optimization",persist:!0})}async indexExperience(e){await this.memory.set(`learning:experience:index:agent:${e.agentId.value}:${e.id}`,e.id,{namespace:"learning-optimization",ttl:86400*30}),await this.memory.set(`learning:experience:index:domain:${e.domain}:${e.id}`,e.id,{namespace:"learning-optimization",ttl:86400*30})}async getExperiencesByDomainAndTime(e,u){let a=await this.memory.search(`learning:experience:index:domain:${e}:*`,1e3),t=[];for(let r of a){let i=await this.memory.get(r);if(i){let n=await this.memory.get(`learning:experience:${i}`);n&&u.contains(n.timestamp)&&t.push(n)}}return t}async extractPatternsFromExperiences(e){let u=e.filter(r=>r.result.success),a=new Map;for(let r of u){let i=a.get(r.action)||[];i.push(r),a.set(r.action,i)}let t=[];for(let[r,i]of a)if(i.length>=this.config.minExperiencesForPattern){let n=await this.learnPattern(i);n.success&&t.push(n.value)}return t}matchesContext(e,u){return!(u.language&&e.context.language!==u.language||u.framework&&e.context.framework!==u.framework||u.testType&&e.context.testType!==u.testType||u.tags.length>0&&!u.tags.some(t=>e.context.tags.includes(t)))}extractCommonActions(e){let u=new Map;for(let a of e){let t=u.get(a.action)||0;u.set(a.action,t+1)}return Array.from(u.entries()).filter(([a,t])=>t>=e.length*.3).map(([a])=>a)}calculateAverageReward(e){return e.length===0?0:e.reduce((a,t)=>a+t.reward,0)/e.length}calculateSuccessRate(e){return e.length===0?0:e.filter(a=>a.result.success).length/e.length}inferPatternType(e){let u=e.map(a=>a.action.toLowerCase());return u.some(a=>a.includes("test")||a.includes("generate"))?"test-pattern":u.some(a=>a.includes("fix")||a.includes("repair"))?"fix-pattern":u.some(a=>a.includes("optimize")||a.includes("improve"))?"optimization-pattern":u.some(a=>a.includes("detect")||a.includes("find"))?"detection-pattern":u.some(a=>a.includes("workflow")||a.includes("process"))?"workflow-pattern":u.some(a=>a.includes("fail")||a.includes("error"))?"failure-pattern":"workflow-pattern"}generatePatternTemplate(e,u){let a=[{name:"domain",type:"string",required:!0,description:"Target domain for the pattern"},{name:"action",type:"string",required:!0,defaultValue:u[0],description:"Primary action to execute"}];return{type:"workflow",content:`// Pattern learned from ${e.length} experiences
3027
3027
  // Common actions: ${u.join(", ")}
3028
3028
  // Apply to domain: {{domain}}
3029
- // Execute action: {{action}}`,variables:a}}extractPatternContext(e){let u=new Set,a,t;for(let r of e){let i=r.state.context;if(i.language&&(a=i.language),i.framework&&(t=i.framework),i.tags&&Array.isArray(i.tags))for(let n of i.tags)u.add(n)}return{language:a,framework:t,tags:Array.from(u)}}calculateConsolidatedConfidence(e){let u=e.reduce((t,r)=>t+r.usageCount,0),a=0;for(let t of e){let r=u>0?t.usageCount/u:1/e.length;a+=t.confidence*r}return a}calculateWeightedSuccessRate(e){let u=e.reduce((t,r)=>t+r.usageCount,0),a=0;for(let t of e){let r=u>0?t.usageCount/u:1/e.length;a+=t.successRate*r}return a}detectAnomalies(e){let u=[],a=this.calculateAverageReward(e),t=this.calculateStdDev(e.map(r=>r.reward));for(let r of e){let i=Math.abs(r.reward-a)/(t||1);if(i>this.config.anomalyDeviationThreshold){let n="outlier-reward";r.result.success&&r.reward<a?n="unexpected-success":!r.result.success&&r.reward>a&&(n="unexpected-failure"),u.push({experienceId:r.id,type:n,description:`Reward ${r.reward.toFixed(2)} deviates ${i.toFixed(2)} std from mean ${a.toFixed(2)}`,deviation:i})}}return u}calculateStdDev(e){if(e.length===0)return 0;let u=e.reduce((t,r)=>t+r,0)/e.length,a=e.map(t=>Math.pow(t-u,2));return Math.sqrt(a.reduce((t,r)=>t+r,0)/e.length)}generateRecommendations(e,u,a){let t=[];return u<.5&&t.push("Low success rate detected. Consider reviewing the approach or gathering more training data."),a.length>e.length*.1&&t.push("High anomaly rate detected. Investigate unexpected outcomes for potential improvements."),e.reduce((i,n)=>i+n.result.duration,0)/e.length>6e4&&t.push("Average operation duration is high. Consider optimizing performance."),e.length<10&&t.push("Limited experience data. Collect more data points for better insights."),t.length===0&&t.push("Performance metrics are within acceptable ranges. Continue monitoring."),t}actionsSimilar(e,u){let a=i=>i.toLowerCase().replace(/[^a-z]/g,""),t=a(e),r=a(u);return!!(t===r||t.includes(r)||r.includes(t))}calculateCentroid(e){let u={},a={};for(let t of e)for(let[r,i]of Object.entries(t.state.metrics))u[r]=(u[r]||0)+i,a[r]=(a[r]||0)+1;for(let t of Object.keys(u))u[t]/=a[t];return{context:{},metrics:u}}isConstraintViolated(e,u){switch(e.operator){case"lt":return u>=e.value;case"gt":return u<=e.value;case"lte":return u>e.value;case"gte":return u<e.value;case"eq":return u!==e.value;default:return!1}}};S();var P2u={maxKnowledgeItems:1e3,relevanceThreshold:.5,transferDecayFactor:.1,crossDomainBoost:.2},t0=class{constructor(e,u={}){this.memory=e;this.config={...P2u,...u}}config;async shareKnowledge(e,u){try{await this.memory.set(`learning:knowledge:shared:${e.id}`,e,{namespace:"learning-optimization",persist:!0});for(let a of u)await this.memory.set(`learning:knowledge:access:${a.value}:${e.id}`,{knowledgeId:e.id,agentId:a.value,sharedAt:new Date,accessed:!1},{namespace:"learning-optimization",ttl:86400*7});return await this.recordSharingEvent(e,u),p(void 0)}catch(a){return m(g(a))}}async queryKnowledge(e){try{let u=[],a;e.domain?a=await this.memory.search(`learning:knowledge:*:${e.domain}:*`,e.limit||100):a=await this.memory.search("learning:knowledge:shared:*",e.limit||100);for(let t of a){let r=await this.memory.get(t);r&&this.matchesQuery(r,e)&&u.push(r)}if(u.sort((t,r)=>r.relevanceScore-t.relevanceScore),e.embedding&&e.embedding.length>0){let t=await this.memory.vectorSearch(e.embedding,e.limit||10);for(let r of t){let i=await this.memory.get(r.key);i&&!u.some(n=>n.id===i.id)&&this.matchesQuery(i,e)&&u.push(i)}}return p(u.slice(0,e.limit||100))}catch(u){return m(g(u))}}async synthesizeKnowledge(e){try{if(e.length<2)return m(new Error("Need at least 2 knowledge items to synthesize"));let u=[];for(let l of e){let c=await this.getKnowledgeById(l);c&&u.push(c)}if(u.length<2)return m(new Error("Not enough valid knowledge items found"));let a=this.determineSynthesizedType(u),t=this.determineSynthesizedDomain(u),r=this.mergeKnowledgeContent(u),i=u.reduce((l,c)=>l+c.relevanceScore,0)/u.length,n=Math.min(1,i+this.config.crossDomainBoost),o={id:A(),type:a,domain:t,content:r,sourceAgentId:u[0].sourceAgentId,targetDomains:this.mergeTargetDomains(u),relevanceScore:n,version:1,createdAt:new Date};return await this.storeKnowledge(o),await this.recordSynthesisEvent(o,e),p(o)}catch(u){return m(g(u))}}async transferKnowledge(e,u){try{if(e.domain===u)return m(new Error("Cannot transfer knowledge to the same domain"));let a=this.calculateTransferredRelevance(e,u);if(a<this.config.relevanceThreshold)return m(new Error(`Transferred relevance ${a} below threshold ${this.config.relevanceThreshold}`));let t=await this.adaptContentForDomain(e.content,e.domain,u),r={id:A(),type:e.type,domain:u,content:t,sourceAgentId:e.sourceAgentId,targetDomains:[u],relevanceScore:a,version:e.version+1,createdAt:new Date};return await this.storeKnowledge(r),await this.recordTransferEvent(e,r),p(r)}catch(a){return m(g(a))}}async validateRelevance(e,u){try{let a=e.relevanceScore;if(u.language&&e.content.metadata?.language===u.language&&(a+=.1),u.framework&&e.content.metadata?.framework===u.framework&&(a+=.1),u.tags.length>0&&e.content.metadata?.tags){let n=e.content.metadata.tags,o=u.tags.filter(l=>n.includes(l));a+=o.length/u.tags.length*.2}let r=(Date.now()-e.createdAt.getTime())/(1e3*60*60*24),i=Math.exp(-this.config.transferDecayFactor*r/30);return a*=i,e.expiresAt&&new Date>e.expiresAt&&(a*=.5),p(Math.min(1,Math.max(0,a)))}catch(a){return m(g(a))}}async createKnowledge(e,u,a,t,r=[],i){try{let n={id:A(),type:e,domain:u,content:{format:this.inferContentFormat(a),data:a,metadata:i},sourceAgentId:t,targetDomains:r,relevanceScore:1,version:1,createdAt:new Date};return await this.storeKnowledge(n),e==="embedding"&&Array.isArray(a)&&await this.memory.storeVector(`learning:knowledge:vector:${n.id}`,a,{knowledgeId:n.id}),p(n)}catch(n){return m(g(n))}}async getKnowledgeById(e){return await this.memory.get(`learning:knowledge:shared:${e}`)||null}async bulkTransfer(e,u,a){try{let t=await this.memory.search(`learning:knowledge:project:${e}:*`,500),r=[];for(let i of t){let n=await this.memory.get(i);if(!n||a?.types&&!a.types.includes(n.type)||a?.minRelevance&&n.relevanceScore<a.minRelevance)continue;let o=await this.adaptContentForProject(n.content,e,u),l={...n,id:A(),content:o,relevanceScore:n.relevanceScore*(1-this.config.transferDecayFactor),version:n.version+1,createdAt:new Date};await this.memory.set(`learning:knowledge:project:${u}:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),r.push({knowledgeId:l.id,sourceDomain:n.domain,targetDomain:n.domain,originalRelevance:n.relevanceScore,transferredRelevance:l.relevanceScore,adaptations:["project-context-adapted"]})}return p(r)}catch(t){return m(g(t))}}async storeKnowledge(e){await this.memory.set(`learning:knowledge:shared:${e.id}`,e,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:domain:${e.domain}:${e.id}`,e.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:type:${e.type}:${e.id}`,e.id,{namespace:"learning-optimization",persist:!0})}matchesQuery(e,u){if(u.type&&e.type!==u.type||u.domain&&e.domain!==u.domain||u.minRelevance!==void 0&&e.relevanceScore<u.minRelevance)return!1;if(u.tags&&u.tags.length>0){let a=e.content.metadata?.tags||[];if(!u.tags.some(r=>a.includes(r)))return!1}return!0}determineSynthesizedType(e){let u=new Map;for(let r of e)u.set(r.type,(u.get(r.type)||0)+1);let a=e[0].type,t=0;for(let[r,i]of u)i>t&&(t=i,a=r);return a}determineSynthesizedDomain(e){let u=new Map;for(let r of e)u.set(r.domain,(u.get(r.domain)||0)+1);let a=e[0].domain,t=0;for(let[r,i]of u)i>t&&(t=i,a=r);return a}mergeKnowledgeContent(e){let u={},a=[];for(let t of e)if(a.push(t.content.data),t.content.metadata)for(let[r,i]of Object.entries(t.content.metadata))if(Array.isArray(i)){let n=u[r]||[];u[r]=[...new Set([...n,...i])]}else u[r]=i;return{format:"json",data:{synthesized:!0,sources:a},metadata:{...u,synthesizedFrom:e.map(t=>t.id),synthesizedAt:new Date().toISOString()}}}mergeTargetDomains(e){let u=new Set;for(let a of e){u.add(a.domain);for(let t of a.targetDomains)u.add(t)}return Array.from(u)}calculateTransferredRelevance(e,u){let a=e.relevanceScore;a*=1-this.config.transferDecayFactor;let t=this.getDomainCompatibility(e.domain,u);return a*=t,e.targetDomains.includes(u)&&(a+=this.config.crossDomainBoost),Math.min(1,Math.max(0,a))}getDomainCompatibility(e,u){let a={"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:Fu.filter(t=>t!=="coordination")};return e===u?1:a[e]?.includes(u)?.8:.5}async adaptContentForDomain(e,u,a){return{...e,metadata:{...e.metadata||{},adaptedFrom:u,adaptedTo:a,adaptedAt:new Date().toISOString()}}}async adaptContentForProject(e,u,a){return{...e,metadata:{...e.metadata||{},sourceProject:u,targetProject:a,transferredAt:new Date().toISOString()}}}inferContentFormat(e){return typeof e=="string"?"text":Array.isArray(e)&&e.every(u=>typeof u=="number")?"embedding":"json"}async recordSharingEvent(e,u){await this.memory.set(`learning:knowledge:events:share:${e.id}:${Date.now()}`,{type:"share",knowledgeId:e.id,targetAgents:u.map(a=>a.value),timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordSynthesisEvent(e,u){await this.memory.set(`learning:knowledge:events:synthesis:${e.id}`,{type:"synthesis",synthesizedId:e.id,sourceIds:u,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordTransferEvent(e,u){await this.memory.set(`learning:knowledge:events:transfer:${u.id}`,{type:"transfer",originalId:e.id,transferredId:u.id,originalDomain:e.domain,targetDomain:u.domain,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}};S();cu();var z2u={defaultConfidenceLevel:.95,minSamplesForOptimization:20,maxOptimizationIterations:100,improvementThreshold:.05,explorationRate:.1},L2u=["__proto__","constructor","prototype"];function st(s){return!L2u.includes(s)}var r0=class{constructor(e,u={}){this.memory=e;this.config={...z2u,...u}}config;async optimizeStrategy(e,u,a){try{if(a.length<this.config.minSamplesForOptimization)return m(new Error(`Need at least ${this.config.minSamplesForOptimization} experiences for optimization`));let t=this.evaluateStrategyPerformance(e,a,u),r=await this.optimizeParameters(e.parameters,a,u),i={name:`${e.name}-optimized`,parameters:r,expectedOutcome:this.predictOutcome(r,a)},n=await this.validateOptimization(e,i,a.slice(-10)),o=this.evaluateStrategyPerformance(i,a,u),l=this.calculateImprovement(t,o,u),c=this.calculateOptimizationConfidence(a.length,l,n),E=this.inferDomainFromExperiences(a),d={id:A(),domain:E,objective:u,currentStrategy:e,optimizedStrategy:i,improvement:l,confidence:c,validationResults:n};return await this.storeOptimizationResult(d),p(d)}catch(t){return m(g(t))}}async runABTest(e,u,a){try{let t=await this.collectStrategyMetrics(e,a.metric,a.minSamples),r=await this.collectStrategyMetrics(u,a.metric,a.minSamples),i=this.calculateMean(t),n=this.calculateMean(r),o=this.calculateStdDev(t),l=this.calculateStdDev(r),c=this.calculatePValue(t,r),E;c<1-a.confidenceLevel?E=i>n?"A":"B":E="inconclusive";let d={winner:E,strategyAMetrics:{[a.metric]:i,stdDev:o,samples:t.length},strategyBMetrics:{[a.metric]:n,stdDev:l,samples:r.length},pValue:c,sampleSizeA:t.length,sampleSizeB:r.length};return await this.storeABTestResult(e,u,d),p(d)}catch(t){return m(g(t))}}async recommendStrategy(e){try{let u=await this.memory.search("learning:strategy:optimized:*",100),a=[];for(let t of u){let r=await this.memory.get(t);if(r&&r.confidence>.6){let i=this.scoreContextMatch(r,e),n=r.improvement*r.confidence;a.push({strategy:r.optimizedStrategy,score:i*.4+n*.6})}}return a.length===0?p({name:"default-strategy",parameters:this.getDefaultParameters(e),expectedOutcome:{success_rate:.7}}):(a.sort((t,r)=>r.score-t.score),p(a[0].strategy))}catch(u){return m(g(u))}}async evaluateStrategy(e,u){try{let a={},t=this.calculateSuccessRate(u),r=this.calculateAverageDuration(u),i=this.calculateAverageReward(u);a.success_rate=t,a.avg_duration_ms=r,a.avg_reward=i;let n=[];t>.8&&n.push("High success rate"),r<5e3&&n.push("Fast execution"),i>.7&&n.push("Consistently good rewards");let o=[];t<.5&&o.push("Low success rate needs investigation"),r>3e4&&o.push("Slow execution time"),i<.3&&o.push("Low reward values");let l=this.identifyImprovementAreas(e,a,u),c={strategy:e,metrics:a,strengths:n,weaknesses:o,improvementAreas:l};return await this.storeStrategyEvaluation(c),p(c)}catch(a){return m(g(a))}}async trackMetrics(e,u){try{let a={strategyId:e,metrics:u,timestamp:new Date,samples:1},t=`learning:metrics:history:${e}:${Date.now()}`;return await this.memory.set(t,a,{namespace:"learning-optimization",ttl:86400*30}),await this.updateAggregatedMetrics(e,u),p(void 0)}catch(a){return m(g(a))}}async getMetricsHistory(e,u=100){try{let a=await this.memory.search(`learning:metrics:history:${e}:*`,u),t=[];for(let r of a){let i=await this.memory.get(r);i&&t.push(i)}return t.sort((r,i)=>r.timestamp.getTime()-i.timestamp.getTime()),p(t)}catch(a){return m(g(a))}}async gridSearchOptimize(e,u,a){try{let t=this.generateParameterCombinations(e),r={},i=u.direction==="maximize"?-1/0:1/0;for(let n of t){let o=this.scoreParameters(n,a,u);(u.direction==="maximize"?o>i:o<i)&&(i=o,r=n)}return p(r)}catch(t){return m(g(t))}}evaluateStrategyPerformance(e,u,a){let t=0,r=0;for(let i of u){let n=i.result.outcome[a.metric]??0;t+=n,r++}return r>0?t/r:0}async optimizeParameters(e,u,a){let t={...e};for(let[r,i]of Object.entries(e))if(st(r)&&typeof i=="number"){let n=[-.1,-.05,0,.05,.1],o=0,l=this.scoreParameters(t,u,a);for(let c of n){let E={...t,[r]:i*(1+c)},d=this.scoreParameters(E,u,a);(a.direction==="maximize"?d>l:d<l)&&(l=d,o=c)}t[r]=i*(1+o)}return t}scoreParameters(e,u,a){let t=0,r=0;for(let i of u){let n=i.result.success?1:.5,o=this.calculateParamSimilarity(e,i.state.context),l=i.result.outcome[a.metric]??0;t+=o*l*n,r+=n}return r>0?t/r:0}calculateParamSimilarity(e,u){let a=0,t=0;for(let[r,i]of Object.entries(e))if(u[r]!==void 0)if(t++,typeof i=="number"&&typeof u[r]=="number"){let n=Math.abs(i-u[r]),o=Math.max(Math.abs(i),Math.abs(u[r]),1);a+=1-n/o}else i===u[r]&&a++;return t>0?a/t:.5}predictOutcome(e,u){let a={},t={},r={};for(let i of u)if(i.result.success)for(let[n,o]of Object.entries(i.result.outcome))st(n)&&typeof o=="number"&&(t[n]=(t[n]||0)+o,r[n]=(r[n]||0)+1);for(let[i,n]of Object.entries(t))st(i)&&(a[i]=n/r[i]);return a}async validateOptimization(e,u,a){let t=[];for(let r of a){let i=u.expectedOutcome,n=Object.entries(i).every(([o,l])=>{let c=r.result.outcome[o]??0;return Math.abs(c-l)/Math.max(l,1)<.2});t.push({testId:r.id,passed:n,metrics:r.state.metrics})}return t}calculateImprovement(e,u,a){if(e===0)return u>0?1:0;let t=u-e,r=a.direction==="maximize"?t/e:-t/e;return Math.max(-1,Math.min(1,r))}calculateOptimizationConfidence(e,u,a){let t=Math.min(1,e/(this.config.minSamplesForOptimization*2)),r=a.filter(n=>n.passed).length/Math.max(a.length,1),i=Math.abs(u)>this.config.improvementThreshold?1:.5;return t*.3+r*.5+i*.2}inferDomainFromExperiences(e){let u=new Map;for(let r of e)u.set(r.domain,(u.get(r.domain)||0)+1);let a="learning-optimization",t=0;for(let[r,i]of u)i>t&&(t=i,a=r);return a}async collectStrategyMetrics(e,u,a){let t=await this.memory.search("learning:metrics:history:*:*",a*2),r=[];for(let i of t){let n=await this.memory.get(i);n&&n.metrics[u]!==void 0&&r.push(n.metrics[u])}for(;r.length<a;){let i=e.expectedOutcome[u]||.5,n=(K()-.5)*.2;r.push(i+n)}return r}calculateMean(e){return e.length===0?0:e.reduce((u,a)=>u+a,0)/e.length}calculateStdDev(e){if(e.length===0)return 0;let u=this.calculateMean(e),a=e.map(t=>Math.pow(t-u,2));return Math.sqrt(a.reduce((t,r)=>t+r,0)/e.length)}calculatePValue(e,u){let a=this.calculateMean(e),t=this.calculateMean(u),r=Math.pow(this.calculateStdDev(e),2),i=Math.pow(this.calculateStdDev(u),2),n=e.length,o=u.length,l=Math.sqrt(r/n+i/o);if(l===0)return .5;let c=Math.abs(a-t)/l,E=2*(1-this.normalCDF(c));return Math.max(0,Math.min(1,E))}normalCDF(e){let u=.254829592,a=-.284496736,t=1.421413741,r=-1.453152027,i=1.061405429,n=.3275911,o=e<0?-1:1;e=Math.abs(e)/Math.sqrt(2);let l=1/(1+n*e),c=1-((((i*l+r)*l+t)*l+a)*l+u)*l*Math.exp(-e*e);return .5*(1+o*c)}scoreContextMatch(e,u){let a=0,t=0;return u.tags.some(r=>r===e.objective.metric)&&(a+=1),t+=1,u.tags.some(r=>r===e.domain)&&(a+=1),t+=1,t>0?a/t:.5}getDefaultParameters(e){let u={timeout:3e4,retryCount:3,concurrency:4};return e.framework&&(u.framework=e.framework),e.language&&(u.language=e.language),u}calculateSuccessRate(e){return e.length===0?0:e.filter(u=>u.result.success).length/e.length}calculateAverageDuration(e){return e.length===0?0:e.reduce((u,a)=>u+a.result.duration,0)/e.length}calculateAverageReward(e){return e.length===0?0:e.reduce((u,a)=>u+a.reward,0)/e.length}identifyImprovementAreas(e,u,a){let t=[];u.success_rate<.8&&t.push("Increase success rate by tuning parameters"),u.avg_duration_ms>1e4&&t.push("Optimize for faster execution"),u.avg_reward<.5&&t.push("Improve reward through better strategy selection");let r=e.parameters;return r.retryCount<2&&t.push("Consider increasing retry count for resilience"),r.concurrency>8&&t.push("High concurrency may cause resource contention"),t}generateParameterCombinations(e){let u=Object.keys(e);if(u.length===0)return[{}];let a=[];function t(r,i){if(r===u.length){a.push({...i});return}let n=u[r];if(!st(n)){t(r+1,i);return}for(let o of e[n])i[n]=o,t(r+1,i)}return t(0,{}),a}async updateAggregatedMetrics(e,u){let a=`learning:metrics:aggregated:${e}`,r=(await this.memory.get(a))?.metrics||{};for(let[i,n]of Object.entries(u))st(i)&&(r[i]||(r[i]={sum:0,count:0}),r[i].sum+=n,r[i].count+=1);await this.memory.set(a,{metrics:r,updatedAt:new Date},{namespace:"learning-optimization",persist:!0})}async storeOptimizationResult(e){await this.memory.set(`learning:strategy:optimized:${e.id}`,e,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:strategy:domain:${e.domain}:${e.id}`,e.id,{namespace:"learning-optimization",persist:!0})}async storeABTestResult(e,u,a){let t=A();await this.memory.set(`learning:abtest:${t}`,{testId:t,strategyA:e.name,strategyB:u.name,result:a,timestamp:new Date},{namespace:"learning-optimization",persist:!0})}async storeStrategyEvaluation(e){let u=A();await this.memory.set(`learning:evaluation:${u}`,{...e,evaluatedAt:new Date},{namespace:"learning-optimization",ttl:86400*7})}};S();var N2u={metricsRetentionDays:90,anomalyThreshold:2.5,trendWindowSize:7,alertThresholds:{error_rate:.05,latency_p99:5e3,memory_usage:.9,cpu_usage:.8}},i0=class{constructor(e,u={}){this.memory=e;this.config={...N2u,...u}}config;async recordMetric(e,u,a,t,r=[]){try{let i={id:A(),name:e,value:u,unit:a,domain:t,tags:r,timestamp:new Date};return await this.memory.set(`production:metric:${i.id}`,i,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400}),await this.indexMetric(i),await this.checkForAnomalies(i),p(i.id)}catch(i){return m(g(i))}}async recordMetricsBatch(e){try{let u=[];for(let a of e){let t=await this.recordMetric(a.name,a.value,a.unit,a.domain,a.tags);t.success&&u.push(t.value)}return p(u)}catch(u){return m(g(u))}}async getMetricsHistory(e,u,a){try{let t=a?`production:metric:index:${e}:${a}:*`:`production:metric:index:${e}:*`,r=await this.memory.search(t,1e3),i=[];for(let n of r){let o=await this.memory.get(n);if(o){let l=await this.memory.get(`production:metric:${o}`);l&&u.contains(l.timestamp)&&i.push(l)}}return i.sort((n,o)=>n.timestamp.getTime()-o.timestamp.getTime()),p(i)}catch(t){return m(g(t))}}async recordIncident(e,u,a,t,r){try{let i={id:A(),severity:e,title:u,description:a,domain:t,metrics:r,startedAt:new Date};return await this.memory.set(`production:incident:${i.id}`,i,{namespace:"learning-optimization",persist:!0}),await this.indexIncident(i),await this.createExperienceFromIncident(i),p(i)}catch(i){return m(g(i))}}async resolveIncident(e,u,a){try{let t=await this.memory.get(`production:incident:${e}`);if(!t)return m(new Error(`Incident ${e} not found`));let r={...t,rootCause:u,resolution:a,resolvedAt:new Date};return await this.memory.set(`production:incident:${e}`,r,{namespace:"learning-optimization",persist:!0}),await this.updateExperienceWithResolution(r),p(r)}catch(t){return m(g(t))}}async getRecentIncidents(e=10,u){try{let a=u?`production:incident:index:domain:${u}:*`:"production:incident:*",t=await this.memory.search(a,e*2),r=[];for(let n of t)if(n.includes(":index:")){let o=await this.memory.get(n);if(o){let l=await this.memory.get(`production:incident:${o}`);l&&r.push(l)}}else{let o=await this.memory.get(n);o&&r.push(o)}r.sort((n,o)=>o.startedAt.getTime()-n.startedAt.getTime());let i=Array.from(new Map(r.map(n=>[n.id,n])).values());return p(i.slice(0,e))}catch(a){return m(g(a))}}async getProductionHealth(){try{let e=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","code-intelligence","security-compliance","learning-optimization"],u={},a={},t="healthy",r=0,i=0;for(let E of e){let d=await this.getDomainHealth(E);u[E]=d,d.status==="degraded"&&r++,d.status==="unhealthy"&&i++;for(let[D,h]of Object.entries(d.metrics))a[`${E}_${D}`]=h}i>0?t="unhealthy":r>e.length/3&&(t="degraded");let n=await this.calculateTrends(),o=await this.getRecentIncidents(5),l=o.success?o.value:[],c=this.generateHealthRecommendations(u,a,l);return p({overall:t,domains:u,metrics:a,trends:n,recentIncidents:l,recommendations:c})}catch(e){return m(g(e))}}async getDomainHealth(e){let u=Ju.lastNDays(1),a=await this.getMetricsHistory("*",u,e),t={};if(a.success)for(let o of a.value)t[o.name],t[o.name]=o.value;let r=await this.getRecentIncidents(100,e),i=r.success?r.value.filter(o=>!o.resolvedAt).length:0,n="healthy";return i>2?n="unhealthy":i>0&&(n="degraded"),t.error_rate>this.config.alertThresholds.error_rate?n="unhealthy":t.latency_p99>this.config.alertThresholds.latency_p99&&(n="degraded"),{status:n,metrics:t,activeIncidents:i}}async calculateTrends(){let e=[],u=["error_rate","latency_p99","success_rate"],a=this.config.trendWindowSize;for(let t of u)for(let r=0;r<a;r++){let i=new Date;i.setDate(i.getDate()-r),i.setHours(0,0,0,0);let n=new Date(i);n.setHours(23,59,59,999);let o=Ju.create(i,n),l=await this.getMetricsHistory(t,o);if(l.success&&l.value.length>0){let c=l.value.reduce((E,d)=>E+d.value,0)/l.value.length;e.push({timestamp:i,metric:t,value:c})}}return e}generateHealthRecommendations(e,u,a){let t=[];for(let[n,o]of Object.entries(e))o.status==="unhealthy"?t.push(`Domain ${n} is unhealthy. Review active incidents and metrics.`):o.status==="degraded"&&t.push(`Domain ${n} is degraded. Monitor closely.`);for(let[n,o]of Object.entries(u)){let l=n.split("_").slice(-2).join("_"),c=this.config.alertThresholds[l];c&&o>c&&t.push(`Metric ${n} (${o.toFixed(2)}) exceeds threshold (${c})`)}let r=a.filter(n=>!n.resolvedAt);return r.length>3&&t.push(`${r.length} unresolved incidents require attention`),a.reduce((n,o)=>(n[o.severity]=(n[o.severity]||0)+1,n),{}).critical>2&&t.push("Multiple critical incidents detected. Consider system-wide review."),t.length===0&&t.push("All systems operating within normal parameters."),t}async extractInsights(e,u){try{let a=await this.getMetricsHistory("*",e,u),t=a.success?a.value:[],r=await this.getRecentIncidents(50,u),i=r.success?r.value:[],n=t.length,o=i.filter(D=>D.resolvedAt),l=i.length>0?o.length/i.length:1,c=this.calculateRewardFromIncidents(i),E=this.generateInsightRecommendations(t,i),d=this.detectMetricAnomalies(t);return p({experienceCount:n,successRate:l,avgReward:c,patterns:[],anomalies:d,recommendations:E})}catch(a){return m(g(a))}}async recordMilestone(e,u,a){try{let t={name:e,achievedAt:new Date,domain:u};return await this.memory.set(`production:milestone:${A()}`,{...t,metrics:a},{namespace:"learning-optimization",persist:!0}),p(t)}catch(t){return m(g(t))}}async getRecentMilestones(e=10){try{let u=await this.memory.search("production:milestone:*",e),a=[];for(let t of u){let r=await this.memory.get(t);r&&a.push(r)}return a.sort((t,r)=>r.achievedAt.getTime()-t.achievedAt.getTime()),p(a.slice(0,e))}catch(u){return m(g(u))}}async indexMetric(e){await this.memory.set(`production:metric:index:${e.name}:${e.domain}:${e.id}`,e.id,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400})}async indexIncident(e){await this.memory.set(`production:incident:index:domain:${e.domain}:${e.id}`,e.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`production:incident:index:severity:${e.severity}:${e.id}`,e.id,{namespace:"learning-optimization",persist:!0})}async checkForAnomalies(e){let u=Ju.lastNDays(7),a=await this.getMetricsHistory(e.name,u,e.domain);if(!a.success||a.value.length<10)return;let t=a.value.map(o=>o.value),r=t.reduce((o,l)=>o+l,0)/t.length,i=Math.sqrt(t.reduce((o,l)=>o+Math.pow(l-r,2),0)/t.length),n=Math.abs(e.value-r)/(i||1);n>this.config.anomalyThreshold&&await this.memory.set(`production:anomaly:${A()}`,{metricId:e.id,metricName:e.name,value:e.value,mean:r,stdDev:i,deviation:n,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*7})}async createExperienceFromIncident(e){let u={context:{incidentId:e.id,severity:e.severity,domain:e.domain},metrics:e.metrics},a={success:!1,outcome:e.metrics,duration:0},t={id:A(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:e.domain,action:`incident-${e.severity}`,state:u,result:a,reward:this.calculateIncidentReward(e),timestamp:e.startedAt};await this.memory.set(`learning:experience:${t.id}`,t,{namespace:"learning-optimization",ttl:86400*30})}async updateExperienceWithResolution(e){if(!e.resolvedAt)return;let u={context:{incidentId:e.id,rootCause:e.rootCause,resolution:e.resolution},metrics:e.metrics},a=e.resolvedAt.getTime()-e.startedAt.getTime(),t={success:!0,outcome:{...e.metrics,resolution_time_ms:a},duration:a},r={id:A(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:e.domain,action:`resolution-${e.severity}`,state:u,result:t,reward:1-this.calculateIncidentReward(e),timestamp:e.resolvedAt};await this.memory.set(`learning:experience:${r.id}`,r,{namespace:"learning-optimization",ttl:86400*30})}calculateIncidentReward(e){return-({critical:.9,high:.7,medium:.4,low:.2}[e.severity]||.5)}calculateRewardFromIncidents(e){if(e.length===0)return .8;let u={critical:.1,high:.3,medium:.6,low:.8},a=0,t=0;for(let r of e){let i=u[r.severity]||.5,n=r.resolvedAt?.2:0;a+=i+n,t++}return t>0?a/t:.8}generateInsightRecommendations(e,u){let a=[],t=new Map;for(let r of e){let i=t.get(r.name)||[];i.push(r.value),t.set(r.name,i)}for(let[r,i]of t){let n=this.calculateTrendDirection(i);n==="increasing"&&r.includes("error")?a.push(`${r} is trending upward. Investigate root causes.`):n==="decreasing"&&r.includes("success")&&a.push(`${r} is declining. Review recent changes.`)}if(u.length>0){let r=new Map;for(let i of u)r.set(i.domain,(r.get(i.domain)||0)+1);for(let[i,n]of r)n>3&&a.push(`Domain ${i} has ${n} incidents. Consider preventive measures.`)}return a}detectMetricAnomalies(e){let u=[],a=new Map;for(let t of e){let r=a.get(t.name)||[];r.push(t),a.set(t.name,r)}for(let[t,r]of a){if(r.length<5)continue;let i=r.map(l=>l.value),n=i.reduce((l,c)=>l+c,0)/i.length,o=Math.sqrt(i.reduce((l,c)=>l+Math.pow(c-n,2),0)/i.length);for(let l of r){let c=Math.abs(l.value-n)/(o||1);c>this.config.anomalyThreshold&&u.push({experienceId:l.id,type:"outlier-reward",description:`${t} value ${l.value.toFixed(2)} is ${c.toFixed(1)} std deviations from mean`,deviation:c})}}return u}calculateTrendDirection(e){if(e.length<3)return"stable";let u=e.slice(0,Math.floor(e.length/2)),a=e.slice(Math.floor(e.length/2)),t=u.reduce((n,o)=>n+o,0)/u.length,i=(a.reduce((n,o)=>n+o,0)/a.length-t)/(t||1);return i>.1?"increasing":i<-.1?"decreasing":"stable"}};async function WE(s,e,u){await s.set(`learning:strategy:current:${e}`,u,{namespace:"learning-optimization",persist:!0})}function $E(s,e){let u=s.map(a=>a.result.outcome[e]??0).filter(a=>!isNaN(a));return u.length===0?0:u.reduce((a,t)=>a+t,0)/u.length}function qE(s){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":Fu.filter(u=>u!=="learning-optimization"),"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:Fu.filter(u=>u!=="coordination")}[s]||[]}function JE(s){let e=[],u=new Set;for(let a of s){if(u.has(a.id))continue;let t=[a];u.add(a.id);for(let r of s)u.has(r.id)||a.type===r.type&&a.domain===r.domain&&I2u(a.context,r.context)&&(t.push(r),u.add(r.id));t.length>=2&&e.push(t)}return e}function I2u(s,e){return s.tags.some(u=>e.tags.includes(u))}function UE(s,e,u){let a=JSON.stringify({patternCount:s.length,knowledgeCount:e.length,strategyCount:u.length,patternIds:s.map(r=>r.id).sort(),knowledgeIds:e.map(r=>r.id).sort(),strategyIds:u.map(r=>r.id).sort()}),t=0;for(let r=0;r<a.length;r++){let i=a.charCodeAt(r);t=(t<<5)-t+i,t=t&t}return Math.abs(t).toString(16)}N();var q0=B.create("learning-optimization/consensus");async function ZE(s,e,u,a){let t=O({id:A(),type:"pattern-recommendation",confidence:e,description:`Verify pattern recommendation: ${s.name} (${s.type}) for domain ${s.domain}`,payload:s,detectedBy:"learning-optimization-coordinator",severity:e>.9?"high":"medium"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(q0.info(`Pattern recommendation '${s.name}' verified by consensus`),!0):(q0.warn(`Pattern recommendation '${s.name}' NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async function QE(s,e,u,a){let t=O({id:A(),type:"optimization-suggestion",confidence:e,description:`Verify optimization: ${s.metric} from ${s.currentValue} to ${s.targetValue} via ${s.strategy}`,payload:s,detectedBy:"learning-optimization-coordinator",severity:e>.85?"high":"medium"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(q0.info(`Optimization suggestion for '${s.metric}' verified by consensus`),!0):(q0.warn(`Optimization suggestion for '${s.metric}' NOT verified`),!1)}return!0}async function YE(s,e,u,a){let t=O({id:A(),type:"cross-domain-insight",confidence:e,description:`Verify cross-domain insight: ${s.description}`,payload:s,detectedBy:"learning-optimization-coordinator",severity:"high"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(q0.info(`Cross-domain insight verified by consensus for ${s.targetDomains.length} target domains`),!0):(q0.warn(`Cross-domain insight NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}var H2u={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},Tu=B.create("learning-optimization"),_i=class extends Y{constructor(u,a,t,r={}){let i={...H2u,...r};super(u,"learning-optimization",i,{verifyFindingTypes:["pattern-recommendation","optimization-suggestion","cross-domain-insight"]});this.memory=a;this.agentCoordinator=t;this.learningService=new a0({memory:a}),this.transferService=new t0(a),this.optimizerService=new r0(a),this.productionIntel=new i0(a)}learningService;transferService;optimizerService;productionIntel;sona=null;dreamScheduler=null;async onInitialize(){try{this.sona=await gu({domain:"learning-optimization",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.5}),Tu.info("PersistentSONAEngine initialized for pattern learning")}catch(u){Tu.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),Tu.warn("Continuing without SONA pattern persistence"),this.sona=null}if(this.config.enableDreamScheduler)try{let u=await D4();await u.initialize(),this.dreamScheduler=h4({dreamEngine:u,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(),Tu.info("DreamScheduler initialized and started")}catch{Tu.warn("Failed to initialize DreamScheduler:")}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){if(await this.saveWorkflowState(),this.dreamScheduler){try{await this.dreamScheduler.dispose(),Tu.info("DreamScheduler disposed")}catch(u){Tu.error("Error disposing DreamScheduler:",u instanceof Error?u:void 0)}this.dreamScheduler=null}if(this.initialized&&this.sona)try{await this.sona.close()}catch(u){Tu.error("Error closing SONA engine:",u instanceof Error?u:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async runLearningCycle(u){let a=A();try{if(this.startWorkflow(a,"learning-cycle"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Tu.warn("Topology degraded, using conservative strategy for learning cycle"),this.minCutMixin.shouldPauseOperations())return m(new Error("Learning cycle paused: topology is in critical state"));let t=await this.spawnLearningAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=Ju.lastNDays(1),i=await this.getExperiencesForDomain(u,r),n=i.success?i.value:[];this.updateWorkflowProgress(a,20);let o=await this.learningService.mineExperiences(u,r),l=o.success?o.value.patterns.length:0;this.updateWorkflowProgress(a,50);let c=0,E=[];if(n.length>=10){let h={metric:"success_rate",direction:"maximize",constraints:[]},C=await this.getCurrentStrategy(u),y=await this.optimizerService.optimizeStrategy(C,h,n);y.success&&(c=1,E.push({metric:h.metric,before:this.calculateMetricValue(n,h.metric),after:y.value.optimizedStrategy.expectedOutcome[h.metric]||0,percentChange:y.value.improvement*100}))}this.updateWorkflowProgress(a,80);let d=0;o.success&&o.value.recommendations.length>0&&(await this.transferService.createKnowledge("heuristic",u,o.value.recommendations,{value:`learning-agent-${a.slice(0,8)}`,domain:"learning-optimization",type:"analyzer"},[u])).success&&(d=1),this.completeWorkflow(a),await this.agentCoordinator.stop(t.value);let D={domain:u,experiencesProcessed:n.length,patternsLearned:l,strategiesOptimized:c,knowledgeGenerated:d,improvements:E};return this.config.publishEvents&&l>0&&await this.publishPatternConsolidated(l,[u]),p(D)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async optimizeAllStrategies(){let u=A();try{if(this.startWorkflow(u,"optimization"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Tu.warn("Topology degraded, using conservative optimization strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Optimization paused: topology is in critical state"));let a={},t=0,r=0,i=0,n=Fu.filter(l=>l!=="learning-optimization");for(let l=0;l<n.length;l++){let c=n[l];this.updateWorkflowProgress(u,Math.round(l/n.length*100));let E=Ju.lastNDays(7),d=await this.getExperiencesForDomain(c,E);if(!d.success||d.value.length<10)continue;let D=d.value,h={metric:"success_rate",direction:"maximize",constraints:[]},C=await this.getCurrentStrategy(c),y=await this.optimizerService.optimizeStrategy(C,h,D);y.success&&(t++,r+=y.value.improvement,i++,a[c]={strategiesOptimized:1,avgImprovement:y.value.improvement,bestStrategy:y.value.optimizedStrategy},await this.storeStrategy(c,y.value.optimizedStrategy))}this.completeWorkflow(u);let o={domainsOptimized:i,totalStrategies:t,avgImprovement:t>0?r/t:0,byDomain:a};return this.config.publishEvents&&t>0&&await this.publishOptimizationApplied(o),p(o)}catch(a){return this.failWorkflow(u,String(a)),m(g(a))}}async shareCrossDomainLearnings(){let u=A();try{if(this.startWorkflow(u,"transfer"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Tu.warn("Topology degraded, limiting cross-domain transfer scope"),this.minCutMixin.shouldPauseOperations())return m(new Error("Cross-domain sharing paused: topology is in critical state"));let a=0,t=[],r=0,i=0,n=0,o=await this.transferService.queryKnowledge({minRelevance:.7,limit:100});if(!o.success)return this.failWorkflow(u,o.error.message),m(o.error);let l=o.value;for(let d of l){let D=this.getRelatedDomains(d.domain);for(let h of D){if(h===d.domain)continue;i++,(await this.transferService.transferKnowledge(d,h)).success&&(n++,a++,t.includes(h)||t.push(h))}this.updateWorkflowProgress(u,Math.round(a/(l.length*2)*100))}let c=await this.learningService.getPatternStats();if(c.success){let d=c.value.topPatterns;if(d.length>=2){let D=this.findSimilarPatterns(d);for(let h of D)h.length>=2&&(await this.learningService.consolidatePatterns(h.map(y=>y.id))).success&&r++}}this.completeWorkflow(u);let E={knowledgeShared:a,domainsUpdated:t,transferSuccessRate:i>0?n/i:1,newPatternsCreated:r};return this.config.publishEvents&&a>0&&await this.publishTransferCompleted(E),p(E)}catch(a){return this.failWorkflow(u,String(a)),m(g(a))}}async getLearningDashboard(){try{let u=await this.learningService.getPatternStats(),a=u.success?u.value:null,t=await this.transferService.queryKnowledge({limit:1e3}),r=t.success?t.value.length:0,i=Ju.lastNDays(1),n=0;for(let C of Fu){let y=await this.getExperiencesForDomain(C,i);y.success&&(n+=y.value.length)}let o=await this.productionIntel.getProductionHealth(),l=o.success?o.value.trends:[],c=await this.productionIntel.getRecentMilestones(5),E=c.success?c.value:[],d=a?a.avgSuccessRate*.6+a.avgConfidence*.4:.5,D=[];if(a){let C=Object.entries(a.byDomain).filter(([y,x])=>x>0).map(([y,x])=>({domain:y,score:x})).sort((y,x)=>x.score-y.score);D.push(...C.slice(0,3).map(y=>y.domain))}let h={overallLearningRate:d,totalPatterns:a?.totalPatterns||0,totalKnowledge:r,experiencesLast24h:n,topPerformingDomains:D,learningTrend:l,recentMilestones:E};return p(h)}catch(u){return m(g(u))}}learnPattern(u,a,t,r,i,n){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.createPattern(u,a,t,r,i,n)}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(u,a,t){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.adaptPattern(u,a,t)}getSONAStats(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getStats()}getSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getAllPatterns()}getSONAPatternsByType(u){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByType(u)}getSONAPatternsByDomain(u){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByDomain(u)}updateSONAPattern(u,a,t){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.updatePattern(u,a,t)}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(u){this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.importPatterns(u)}async verifySONAPerformance(u=100){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.verifyPerformance(u)}async triggerDreamCycle(u){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");let a=await this.dreamScheduler.triggerDream(u);return this.config.publishEvents&&await this.publishDreamCycleCompleted(a.cycle.id,a.cycle.durationMs??0,a.cycle.conceptsProcessed,a.insights.map(t=>({id:t.id,type:t.type,description:t.description,noveltyScore:t.noveltyScore,confidenceScore:t.confidenceScore,actionable:t.actionable,suggestedAction:t.suggestedAction,sourceConcepts:t.sourceConcepts})),a.patternsCreated),a}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(u){let a=A();try{this.startWorkflow(a,"export");let t=u||Fu,r=[],i=[],n=[];for(let d of t){let D=await this.memory.search("learning:pattern:*",500);for(let h of D){let C=await this.memory.get(h);C&&t.includes(C.domain)&&r.push(C)}this.updateWorkflowProgress(a,Math.round(r.length/100*30))}let o=await this.transferService.queryKnowledge({limit:1e3});if(o.success)for(let d of o.value)t.includes(d.domain)&&i.push(d);this.updateWorkflowProgress(a,60);let l=await this.memory.search("learning:strategy:optimized:*",200);for(let d of l){let D=await this.memory.get(d);D&&t.includes(D.domain)&&n.push(D)}this.updateWorkflowProgress(a,90);let c=this.calculateChecksum(r,i,n);return this.completeWorkflow(a),p({version:"1.0.0",exportedAt:new Date,patterns:r,knowledge:i,strategies:n,checksum:c})}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async importModels(u){let a=A();try{if(this.startWorkflow(a,"import"),this.calculateChecksum(u.patterns,u.knowledge,u.strategies)!==u.checksum)return this.failWorkflow(a,"Checksum mismatch"),m(new Error("Import failed: checksum mismatch"));let r=0,i=0,n=0,o=[];for(let c of u.patterns){let E=await this.memory.get(`learning:pattern:${c.id}`);E?E.confidence<c.confidence?(await this.memory.set(`learning:pattern:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),r++,o.push({type:"pattern",id:c.id,reason:"Existing pattern had lower confidence",resolution:"overwrite"})):o.push({type:"pattern",id:c.id,reason:"Existing pattern has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:pattern:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),r++),this.updateWorkflowProgress(a,Math.round(r/u.patterns.length*30))}for(let c of u.knowledge){let E=await this.memory.get(`learning:knowledge:shared:${c.id}`);E?c.version>E.version?(await this.memory.set(`learning:knowledge:shared:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),i++,o.push({type:"knowledge",id:c.id,reason:"Import has newer version",resolution:"overwrite"})):o.push({type:"knowledge",id:c.id,reason:"Existing knowledge is same or newer version",resolution:"skip"}):(await this.memory.set(`learning:knowledge:shared:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),i++),this.updateWorkflowProgress(a,30+Math.round(i/u.knowledge.length*30))}for(let c of u.strategies){let E=await this.memory.get(`learning:strategy:optimized:${c.id}`);E?c.confidence>E.confidence?(await this.memory.set(`learning:strategy:optimized:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),n++,o.push({type:"strategy",id:c.id,reason:"Import has higher confidence",resolution:"overwrite"})):o.push({type:"strategy",id:c.id,reason:"Existing strategy has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:strategy:optimized:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),n++),this.updateWorkflowProgress(a,60+Math.round(n/u.strategies.length*40))}return this.completeWorkflow(a),p({patternsImported:r,knowledgeImported:i,strategiesImported:n,conflicts:o,resolved:!0})}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}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(u){let{runId:a,passed:t,failed:r,duration:i}=u.payload,n=t+r>0?t/(t+r):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:a},metrics:{passed:t,failed:r,duration:i}},result:{success:n>.8,outcome:{success_rate:n,passed:t,failed:r},duration:i},reward:n})}async handleCoverageGap(u){let{gapId:a,file:t,riskScore:r}=u.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:a,file:t},metrics:{riskScore:r}},result:{success:!0,outcome:{risk_score:r},duration:0},reward:1-r})}async handleQualityGate(u){let{gateId:a,passed:t}=u.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:a},metrics:{passed:t?1:0}},result:{success:t,outcome:{gate_passed:t?1:0},duration:0},reward:t?1:0})}async handleExperienceCaptured(u){let{experience:a}=u.payload;if(!a.success||a.quality<.7)return;let t=a.domain||"learning-optimization";if(await this.learningService.recordExperience({agentId:{value:a.agent||"unknown",domain:t,type:"specialist"},domain:t,action:a.task,state:{context:{experienceId:a.id,trajectoryId:a.trajectoryId,model:a.model},metrics:{durationMs:a.durationMs,stepCount:a.steps.length,quality:a.quality}},result:{success:a.success,outcome:{quality:a.quality,patterns_extracted:a.patterns?.length||0},duration:a.durationMs},reward:a.quality}),a.patterns&&a.patterns.length>0&&a.domain){let r=this.getRelatedDomains(a.domain);for(let i of r)i!==a.domain&&await this.transferService.transferKnowledge({id:`exp-${a.id}`,domain:a.domain,type:"workflow",content:{format:"json",data:{task:a.task,steps:a.steps,quality:a.quality,patterns:a.patterns}},sourceAgentId:{value:a.agent||"experience-capture",domain:a.domain,type:"specialist"},targetDomains:[i],relevanceScore:a.quality,version:1,createdAt:new Date(a.startedAt)},i);Tu.info(`[LearningOptimizationCoordinator] Experience ${a.id} transferred to ${r.length} related domains`)}this.dreamScheduler&&this.dreamScheduler.recordExperience({id:a.id,agentType:a.agent||"unknown",domain:t,taskType:a.task,success:a.success,duration:a.durationMs,context:{quality:a.quality,steps:a.steps.length,patterns:a.patterns?.length||0},timestamp:new Date(a.startedAt)})}async publishPatternConsolidated(u,a){let t={patternCount:u,domains:a,improvements:0},r=L(Yu.PatternConsolidated,"learning-optimization",t);await this.eventBus.publish(r)}async publishTransferCompleted(u){let a={sourceProject:"current",targetProject:"current",patternsTransferred:u.knowledgeShared,successRate:u.transferSuccessRate},t=L(Yu.TransferCompleted,"learning-optimization",a);await this.eventBus.publish(t)}async publishOptimizationApplied(u){let a=L(Yu.OptimizationApplied,"learning-optimization",{domainsOptimized:u.domainsOptimized,avgImprovement:u.avgImprovement});await this.eventBus.publish(a)}async publishDreamCycleCompleted(u,a,t,r,i){if(!this.config.publishEvents)return;let n={cycleId:u,durationMs:a,conceptsProcessed:t,insights:r,patternsCreated:i},o=L(Yu.DreamCycleCompleted,"learning-optimization",n);await this.eventBus.publish(o),Tu.info(`[LearningOptimizationCoordinator] Published dream cycle completion: ${r.length} insights for ${t} concepts`)}async spawnLearningAgent(u,a){if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached"));let t={name:`learning-agent-${u.slice(0,8)}`,domain:"learning-optimization",type:"optimizer",capabilities:["pattern-learning","experience-mining",a],config:{workflowId:u,targetDomain:a}};return this.agentCoordinator.spawn(t)}async loadWorkflowState(){let u=await this.memory.get("learning-optimization:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("learning-optimization:coordinator:workflows",u,{namespace:"learning-optimization",persist:!0})}async getExperiencesForDomain(u,a){let t=await this.memory.search(`learning:experience:index:domain:${u}:*`,500),r=[];for(let i of t){let n=await this.memory.get(i);if(n){let o=await this.memory.get(`learning:experience:${n}`);o&&a.contains(o.timestamp)&&r.push(o)}}return p(r)}async getCurrentStrategy(u){let a=`learning:strategy:current:${u}`,t=await this.memory.get(a);return t||{name:`default-${u}`,parameters:{timeout:3e4,retryCount:3,concurrency:4},expectedOutcome:{success_rate:.8}}}async storeStrategy(u,a){await WE(this.memory,u,a)}calculateMetricValue(u,a){return $E(u,a)}getRelatedDomains(u){return qE(u)}findSimilarPatterns(u){return JE(u)}calculateChecksum(u,a,t){return UE(u,a,t)}async verifyPatternRecommendation(u,a){return ZE(u,a,this.consensusMixin,this.domainName)}async verifyOptimizationSuggestion(u,a){return QE(u,a,this.consensusMixin,this.domainName)}async verifyCrossDomainInsight(u,a){return YE(u,a,this.consensusMixin,this.domainName)}};S();var ql=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.domain;return a?this.coordinator.runLearningCycle(a):m(new Error("Invalid run-learning-cycle payload: missing domain"))}],["optimize-strategies",async u=>this.coordinator?this.coordinator.optimizeAllStrategies():m(new Error("Coordinator not initialized"))],["share-learnings",async u=>this.coordinator?this.coordinator.shareCrossDomainLearnings():m(new Error("Coordinator not initialized"))],["learn-pattern",async u=>{if(!this.learningService)return m(new Error("Learning service not initialized"));let a=u.experiences;return!a||a.length===0?m(new Error("Invalid learn-pattern payload: missing experiences")):this.learningService.learnPattern(a)}],["query-knowledge",async u=>{if(!this.transferService)return m(new Error("Transfer service not initialized"));let a=u.query;return a?this.transferService.queryKnowledge(a):m(new Error("Invalid query-knowledge payload: missing query"))}]])}async onInitialize(){this.learningService=new a0({memory:this.memory},this.pluginConfig.learningService),this.transferService=new t0(this.memory,this.pluginConfig.transferService),this.optimizerService=new r0(this.memory,this.pluginConfig.optimizerService),this.productionIntel=new i0(this.memory,this.pluginConfig.productionIntel),this.coordinator=new _i(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"test-generation.TestGenerated":await this.handleTestGenerated(u);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(u);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(u);break;default:break}}async runLearningCycle(u){this.ensureInitialized();try{let a=await this.coordinator.runLearningCycle(u);return a.success?this.trackSuccessfulOperation("learning-cycle"):this.trackFailedOperation("learning-cycle",a.error),a}catch(a){return this.handleError(a)}}async optimizeAllStrategies(){this.ensureInitialized();try{let u=await this.coordinator.optimizeAllStrategies();return u.success?this.trackSuccessfulOperation("optimization"):this.trackFailedOperation("optimization",u.error),u}catch(u){return this.handleError(u)}}async shareCrossDomainLearnings(){this.ensureInitialized();try{return await this.coordinator.shareCrossDomainLearnings()}catch(u){return this.handleError(u)}}async getLearningDashboard(){this.ensureInitialized();try{return await this.coordinator.getLearningDashboard()}catch(u){return this.handleError(u)}}async exportModels(u){this.ensureInitialized();try{return await this.coordinator.exportModels(u)}catch(a){return this.handleError(a)}}async importModels(u){this.ensureInitialized();try{return await this.coordinator.importModels(u)}catch(a){return this.handleError(a)}}async learnPattern(u){this.ensureInitialized();try{return await this.learningService.learnPattern(u)}catch(a){return this.handleError(a)}}async findMatchingPatterns(u,a){this.ensureInitialized();try{return await this.learningService.findMatchingPatterns(u,a)}catch(t){return this.handleError(t)}}async applyPattern(u,a){this.ensureInitialized();try{return await this.learningService.applyPattern(u,a)}catch(t){return this.handleError(t)}}async updatePatternFeedback(u,a){this.ensureInitialized();try{return await this.learningService.updatePatternFeedback(u,a)}catch(t){return this.handleError(t)}}async getPatternStats(u){this.ensureInitialized();try{return await this.learningService.getPatternStats(u)}catch(a){return this.handleError(a)}}async queryKnowledge(u){this.ensureInitialized();try{return await this.transferService.queryKnowledge(u)}catch(a){return this.handleError(a)}}async transferKnowledge(u,a){this.ensureInitialized();try{return await this.transferService.transferKnowledge(u,a)}catch(t){return this.handleError(t)}}async optimizeStrategy(u,a,t){this.ensureInitialized();try{return await this.optimizerService.optimizeStrategy(u,a,t)}catch(r){return this.handleError(r)}}async runABTest(u,a,t){this.ensureInitialized();try{return await this.optimizerService.runABTest(u,a,t)}catch(r){return this.handleError(r)}}async recommendStrategy(u){this.ensureInitialized();try{return await this.optimizerService.recommendStrategy(u)}catch(a){return this.handleError(a)}}async evaluateStrategy(u,a){this.ensureInitialized();try{return await this.optimizerService.evaluateStrategy(u,a)}catch(t){return this.handleError(t)}}async handleTestGenerated(u){let a=u.payload;await this.learningService.recordExperience({agentId:{value:"test-generation",domain:"test-generation",type:"generator"},domain:"test-generation",action:"test-generated",state:{context:{testId:a.testId,testType:a.testType},metrics:{}},result:{success:!0,outcome:{generated:1},duration:0},reward:.8})}async handleTestRunCompleted(u){let a=u.payload,t=a.passed+a.failed>0?a.passed/(a.passed+a.failed):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:a.runId},metrics:{passed:a.passed,failed:a.failed,duration:a.duration}},result:{success:t>.8,outcome:{success_rate:t,passed:a.passed,failed:a.failed},duration:a.duration},reward:t}),await this.productionIntel.recordMetric("test_success_rate",t,"ratio","test-execution",["automated"])}async handleCoverageGap(u){let a=u.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:a.gapId,file:a.file},metrics:{riskScore:a.riskScore}},result:{success:!0,outcome:{risk_score:a.riskScore},duration:0},reward:1-a.riskScore})}async handleQualityGate(u){let a=u.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:a.gateId},metrics:{passed:a.passed?1:0}},result:{success:a.passed,outcome:{gate_passed:a.passed?1:0},duration:0},reward:a.passed?1:0})}async handleDefectPredicted(u){let a=u.payload;await this.learningService.recordExperience({agentId:{value:"defect-intelligence",domain:"defect-intelligence",type:"analyzer"},domain:"defect-intelligence",action:"defect-prediction",state:{context:{predictionId:a.predictionId},metrics:{probability:a.probability}},result:{success:!0,outcome:{probability:a.probability},duration:0},reward:.7})}async handleImpactAnalysis(u){let a=u.payload;await this.learningService.recordExperience({agentId:{value:"code-intelligence",domain:"code-intelligence",type:"analyzer"},domain:"code-intelligence",action:"impact-analysis",state:{context:{analysisId:a.analysisId},metrics:{changedFiles:a.changedFiles.length,impactedFiles:a.impactedFiles.length}},result:{success:!0,outcome:{changed_count:a.changedFiles.length,impacted_count:a.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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),m(a)}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u,a){let t=this.getHealth();this.updateHealth({agents:{...t.agents,failed:t.agents.failed+1},errors:[...t.errors.slice(-9),a.message]})}};function XE(s,e,u,a){return new ql(s,e,u,a)}var Jl=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}workflowOrchestrator=null;pluginConfig;get name(){return"coordination"}get version(){return"1.0.0"}get dependencies(){return Fu.filter(u=>u!=="coordination")}getAPI(){return{listWorkflows:async()=>{if(!this.workflowOrchestrator)throw new Error("Workflow orchestrator not initialized");return this.workflowOrchestrator.listWorkflows()}}}async onInitialize(){this.workflowOrchestrator=p4(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(u){u.type.startsWith("coordination.")&&await this.handleCoordinationEvent(u)}subscribeToEvents(){this.eventBus.subscribe("coordination.workflow.execute",async u=>{await this.handleEvent(u)})}async handleCoordinationEvent(u){u.type.split(".")[1]==="workflow"&&await this.handleWorkflowEvent(u)}async handleWorkflowEvent(u){this.workflowOrchestrator}};function u3(s,e,u,a){return new Jl(s,e,u,a)}var Mu={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"},Ul=class{factories=new Map;register(e,u){this.factories.set(e,u)}resolve(e){let u=this.factories.get(e);if(!u)throw new Error(`DomainServiceRegistry: service '${e}' not registered. Ensure the domain module is initialized before coordination.`);return u}has(e){return this.factories.has(e)}clear(){this.factories.clear()}keys(){return Array.from(this.factories.keys())}},Ru=new Ul;Ru.register(Mu.createTestGeneratorService,s=>Ie(s));Ru.register(Mu.CoverageAnalyzerService,s=>new ve(s));Ru.register(Mu.SecurityScannerService,s=>new Ou(s));Ru.register(Mu.isSemgrepAvailable,Xa);Ru.register(Mu.runSemgrepWithRules,li);Ru.register(Mu.convertSemgrepFindings,ci);Ru.register(Mu.KnowledgeGraphService,s=>new ze(s));S();Ru.register(Mu.QualityAnalyzerService,s=>new oe(s));S();N();S();var n0={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"},_2u={maxConcurrentWorkflows:8,defaultTimeout:12e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Wi=B.create("enterprise-integration"),$i=class extends Y{constructor(u,a,t,r={}){let i={..._2u,...r};super(u,"enterprise-integration",i,{verifyFindingTypes:["soap-fault","message-ordering-violation","rfc-compatibility-break","idoc-validation-failure","odata-contract-break","sod-conflict"],modelTimeout:12e4});this.memory=a;this.agentCoordinator=t}async onInitialize(){this.subscribeToEvents(),Wi.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(u){let a=A();try{if(this.startWorkflow(a,"soap"),this.minCutMixin.shouldPauseOperations())return m(new Error("WSDL validation paused: topology is in critical state"));let t=await this.spawnAgent(a,"qe-soap-tester",{task:"validate-wsdl",url:u});if(!t.success)return this.failWorkflow(a,t.error.message),t;let r={url:u,version:"1.1",services:[],schemas:[]};return await this.memory.set(`enterprise-integration:wsdl:${encodeURIComponent(u)}`,r,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(a),p(r)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async testSoapOperation(u,a,t){let r=A();try{this.startWorkflow(r,"soap");let i=await this.spawnAgent(r,"qe-soap-tester",{task:"test-operation",wsdl:u,operation:a,input:t});if(!i.success)return this.failWorkflow(r,i.error.message),m(i.error);let n={operation:a,passed:!0,request:JSON.stringify(t),response:"",validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(L(n0.SoapOperationTested,this.domainName,{operation:a,wsdlUrl:u.url,passed:n.passed,errors:n.validationErrors.length})),this.completeWorkflow(r),p(n)}catch(i){return this.failWorkflow(r,String(i)),m(g(i))}}async testMessageFlow(u,a){let t=A();try{this.startWorkflow(t,"messaging");let r=await this.spawnAgent(t,"qe-message-broker-tester",{task:"test-message-flow",brokerConfig:u,testCase:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={testCaseId:a.id,passed:!0,sentAt:new Date,receivedAt:new Date,latency:0,actualOutcome:a.expectedOutcome,errors:[]};return this.config.publishEvents&&await this.eventBus.publish(L(n0.MessageFlowTested,this.domainName,{protocol:u.protocol,queue:a.queue,passed:i.passed,latency:i.latency})),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async testDlqHandling(u,a){let t=A();try{this.startWorkflow(t,"messaging");let r=await this.spawnAgent(t,"qe-message-broker-tester",{task:"test-dlq",brokerConfig:u,queue:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={queue:a,messageCount:0,poisonMessages:0,reprocessable:0,errors:[]};return this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async testBapiCall(u,a){let t=A();try{if(this.startWorkflow(t,"rfc"),this.minCutMixin.shouldPauseOperations())return m(new Error("BAPI testing paused: topology is in critical state"));let r=await this.spawnAgent(t,"qe-sap-rfc-tester",{task:"test-bapi",connection:u,bapi:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={bapiName:a.name,passed:!0,returnMessages:[],exportValues:{},tableData:{},duration:0,transactionCommitted:!1};return this.config.publishEvents&&await this.eventBus.publish(L(n0.BapiTested,this.domainName,{bapiName:a.name,passed:i.passed,returnType:i.returnMessages.length>0?i.returnMessages[0].type:"S"})),await this.memory.set(`enterprise-integration:bapi:${a.name}:${Date.now()}`,{bapiName:a.name,importParams:Object.keys(a.importParams),passed:i.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async validateIdoc(u,a){let t=A();try{this.startWorkflow(t,"idoc");let r=await this.spawnAgent(t,"qe-sap-idoc-tester",{task:"validate-idoc",definition:u,content:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={idocType:u.type,direction:"inbound",passed:!0,statusCode:3,statusMessage:"IDoc validated successfully",segmentValidation:[],processingTime:0};return this.config.publishEvents&&await this.eventBus.publish(L(n0.IDocValidated,this.domainName,{idocType:u.type,direction:i.direction,passed:i.passed,statusCode:i.statusCode})),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async validateODataMetadata(u){let a=A();try{this.startWorkflow(a,"odata");let t=await this.spawnAgent(a,"qe-odata-contract-tester",{task:"validate-metadata",serviceUrl:u});if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);let r={version:"v4",serviceUrl:u,entitySets:[],functionImports:[],actions:[]};return await this.memory.set(`enterprise-integration:odata:${encodeURIComponent(u)}`,r,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(a),p(r)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async testODataEntitySet(u,a){let t=A();try{this.startWorkflow(t,"odata");let r=await this.spawnAgent(t,"qe-odata-contract-tester",{task:"test-entity-set",metadata:u,entitySet:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={entitySet:a,operation:"CRUD",passed:!0,statusCode:200,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(L(n0.ODataTested,this.domainName,{entitySet:a,operation:i.operation,passed:i.passed,version:u.version})),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async validateMessageFlow(u,a){let t=A();try{this.startWorkflow(t,"middleware");let r=await this.spawnAgent(t,"qe-middleware-validator",{task:"validate-flow",flow:u,input:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={flowName:u.name,passed:!0,routingCorrect:!0,transformationCorrect:!0,errorHandlingCorrect:!0,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(L(n0.MiddlewareFlowTested,this.domainName,{flowName:u.name,passed:i.passed,routingCorrect:i.routingCorrect,transformationCorrect:i.transformationCorrect})),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async validateTransformation(u,a,t){let r=A();try{this.startWorkflow(r,"middleware");let i=await this.spawnAgent(r,"qe-middleware-validator",{task:"validate-transformation",spec:u,input:a,expectedOutput:t});return i.success?(this.completeWorkflow(r),p(!0)):(this.failWorkflow(r,i.error.message),m(i.error))}catch(i){return this.failWorkflow(r,String(i)),m(g(i))}}async analyzeSod(u,a){let t=A();try{this.startWorkflow(t,"sod");let r=await this.spawnAgent(t,"qe-sod-analyzer",{task:"analyze-sod",userId:u,ruleset:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={userId:u,conflicts:[],riskScore:0,compliant:!0,recommendations:[]};return this.config.publishEvents&&await this.eventBus.publish(L(n0.SodAnalyzed,this.domainName,{userId:u,conflicts:i.conflicts.length,compliant:i.compliant,riskScore:i.riskScore})),await this.memory.set(`enterprise-integration:sod:${u}:${Date.now()}`,{userId:u,ruleset:a.name,conflicts:i.conflicts.length,compliant:i.compliant,riskScore:i.riskScore,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async spawnAgent(u,a,t){let r={name:`${a}-${u.slice(0,8)}`,domain:"enterprise-integration",type:a,capabilities:[a],config:{workflowId:u,...t}},i=await this.agentCoordinator.spawn(r);return i.success&&this.addAgentToWorkflow(u,i.value),i}async verifyCriticalFinding(u,a){let t=O({id:A(),type:u.type,confidence:a,description:u.description,payload:u.payload,detectedBy:"enterprise-integration-coordinator",severity:a>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(Wi.info(`Finding verified by consensus: ${u.type}`),!0):(Wi.warn(`Finding NOT verified: ${u.type}`),!1)}return!0}async handleContractVerified(u){let a=u.payload;(a?.contractType==="soap"||a?.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-event:${Date.now()}`,{contractId:a.contractId,type:a.contractType,passed:a.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(u){let a=u.payload;(a?.targetService?.includes("middleware")||a?.targetService?.includes("esb"))&&Wi.info(`Middleware fault injection detected: ${a.targetService}`)}};var Zl=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.wsdl,t=u.operation,r=u.input;return u.url&&!a?this.coordinator.validateWsdl(u.url):!a||!t?m(new Error("Invalid soap-test payload: missing wsdl or operation")):this.coordinator.testSoapOperation(a,t,r)}],["enterprise-integration:message-broker-test",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.brokerConfig,t=u.testCase,r=u.queue;return a?r&&!t?this.coordinator.testDlqHandling(a,r):t?this.coordinator.testMessageFlow(a,t):m(new Error("Invalid message-broker-test payload: missing testCase")):m(new Error("Invalid message-broker-test payload: missing brokerConfig"))}],["enterprise-integration:sap-rfc-test",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.connection,t=u.bapi;return!a||!t?m(new Error("Invalid sap-rfc-test payload: missing connection or bapi")):this.coordinator.testBapiCall(a,t)}],["enterprise-integration:sap-idoc-validate",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.definition,t=u.content;return!a||!t?m(new Error("Invalid sap-idoc-validate payload: missing definition or content")):this.coordinator.validateIdoc(a,t)}],["enterprise-integration:odata-test",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.serviceUrl,t=u.metadata,r=u.entitySet;return a&&!t?this.coordinator.validateODataMetadata(a):!t||!r?m(new Error("Invalid odata-test payload: missing metadata or entitySet")):this.coordinator.testODataEntitySet(t,r)}],["enterprise-integration:esb-flow-test",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.flow,t=u.input,r=u.spec;if(r){let i=u.transformInput,n=u.expectedOutput;return!i||!n?m(new Error("Invalid esb-flow-test payload: missing transformInput or expectedOutput for transformation")):this.coordinator.validateTransformation(r,i,n)}return!a||!t?m(new Error("Invalid esb-flow-test payload: missing flow or input")):this.coordinator.validateMessageFlow(a,t)}],["enterprise-integration:sod-analyze",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.userId,t=u.ruleset;return!a||!t?m(new Error("Invalid sod-analyze payload: missing userId or ruleset")):this.coordinator.analyzeSod(a,t)}]])}async onInitialize(){this.coordinator=new $i(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"contract-testing.ContractVerified":await this.handleContractVerified(u);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(u);break;case"chaos-resilience.FaultInjected":await this.handleFaultInjected(u);break;default:break}}async validateWsdl(u){this.ensureInitialized();try{let a=await this.coordinator.validateWsdl(u);return a.success?this.trackSuccessfulOperation("validateWsdl"):this.trackFailedOperation(new Error(a.error.message)),a}catch(a){return this.handleError(a)}}async testSoapOperation(u,a,t){this.ensureInitialized();try{let r=await this.coordinator.testSoapOperation(u,a,t);return r.success?this.trackSuccessfulOperation("testSoapOperation"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testMessageFlow(u,a){this.ensureInitialized();try{let t=await this.coordinator.testMessageFlow(u,a);return t.success?this.trackSuccessfulOperation("testMessageFlow"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async testDlqHandling(u,a){this.ensureInitialized();try{let t=await this.coordinator.testDlqHandling(u,a);return t.success?this.trackSuccessfulOperation("testDlqHandling"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async testBapiCall(u,a){this.ensureInitialized();try{let t=await this.coordinator.testBapiCall(u,a);return t.success?this.trackSuccessfulOperation("testBapiCall"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async validateIdoc(u,a){this.ensureInitialized();try{let t=await this.coordinator.validateIdoc(u,a);return t.success?this.trackSuccessfulOperation("validateIdoc"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async validateODataMetadata(u){this.ensureInitialized();try{let a=await this.coordinator.validateODataMetadata(u);return a.success?this.trackSuccessfulOperation("validateODataMetadata"):this.trackFailedOperation(new Error(a.error.message)),a}catch(a){return this.handleError(a)}}async testODataEntitySet(u,a){this.ensureInitialized();try{let t=await this.coordinator.testODataEntitySet(u,a);return t.success?this.trackSuccessfulOperation("testODataEntitySet"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async validateMessageFlow(u,a){this.ensureInitialized();try{let t=await this.coordinator.validateMessageFlow(u,a);return t.success?this.trackSuccessfulOperation("validateMessageFlow"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async validateTransformation(u,a,t){this.ensureInitialized();try{let r=await this.coordinator.validateTransformation(u,a,t);return r.success?this.trackSuccessfulOperation("validateTransformation"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async analyzeSod(u,a){this.ensureInitialized();try{let t=await this.coordinator.analyzeSod(u,a);return t.success?this.trackSuccessfulOperation("analyzeSod"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async handleContractVerified(u){let a=u.payload;(a.contractType==="soap"||a.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-verified:${a.contractId}`,{contractId:a.contractId,type:a.contractType,passed:a.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleQualityGate(u){let a=u.payload;a.checks.find(r=>r.name==="enterprise-integration")||await this.memory.set(`enterprise-integration:quality-gate-warning:${a.gateId}`,{warning:"Enterprise integration testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(u){let a=u.payload;(a.targetService?.includes("middleware")||a.targetService?.includes("esb")||a.targetService?.includes("broker")||a.targetService?.includes("mq"))&&await this.memory.set(`enterprise-integration:fault-correlation:${a.faultId||Date.now()}`,{targetService:a.targetService,faultType:a.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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}};function a3(s,e,u,a){return new Zl(s,e,u,a)}var t3={"test-generation":(s,e,u)=>Cs(s,e,u),"test-execution":(s,e)=>Qc(s,e),"coverage-analysis":(s,e)=>Ws(s,e),"quality-assessment":(s,e,u)=>el(s,e,u),"defect-intelligence":(s,e,u)=>P1(s,e,u),"requirements-validation":(s,e,u)=>I1(s,e,u),"code-intelligence":(s,e,u)=>pl(s,e,u),"security-compliance":(s,e,u)=>jl(s,e,u),"contract-testing":(s,e,u)=>bE(s,e,u),"visual-accessibility":(s,e,u)=>HE(s,e,u),"chaos-resilience":(s,e,u)=>OE(s,e,u),"learning-optimization":(s,e,u)=>XE(s,e,u),"enterprise-integration":(s,e,u)=>a3(s,e,u),coordination:(s,e,u)=>u3(s,e,u)},$2u={maxConcurrentAgents:J0.MAX_CONCURRENT_AGENTS,memoryBackend:"hybrid",hnswEnabled:!0,lazyLoading:!0,enabledDomains:[...Fu],dataDir:void 0},Ql=class{_eventBus;_coordinator;_plugins;_memory;_config;_startTime;_initialized=!1;_loopTracker;constructor(e={}){this._config={...$2u,...e},this._startTime=new Date,this._memory=new Qi,this._eventBus=new xt,this._coordinator=new ft(this._config.maxConcurrentAgents),this._plugins=new aa(this._eventBus,this._memory,this._config.lazyLoading),this._loopTracker=new vt}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 e=u4(),u=this._config.dataDir||o0.join(e,".agentic-qe");if(qi.existsSync(u)||qi.mkdirSync(u,{recursive:!0}),this._config.memoryBackend==="memory"){let t=o0.join(Ji("os").tmpdir(),`aqe-test-${Date.now()}-${W2u().slice(0,12)}.db`);await a4({dbPath:t})}else this._memory=new e4({sqlite:{path:o0.join(u,"memory.db"),walMode:!0,poolSize:3,busyTimeout:Xl.BUSY_TIMEOUT_MS},enableFallback:!0,defaultNamespace:"qe-kernel"}),this._plugins=new aa(this._eventBus,this._memory,this._config.lazyLoading);for(let t of this._config.enabledDomains){let r=t3[t];r&&this._plugins.registerFactory(t,async(i,n)=>Promise.resolve(r(i,n,this._coordinator)))}await this._memory.initialize();let a=new bt({agentId:"qe-kernel"});this._eventBus.registerMiddleware(a);try{let t=o0.join(u,"plugins"),r=new t4({cacheDir:t}),n=new r4({cache:r}).resolveLoadOrder();for(let o of n.ordered){let l=o.manifest,c=r.get(l.name,l.version);if(!c)continue;let E=o0.join(c.path,l.entryPoint);for(let d of l.domains){let D=d;if(t3[D])continue;this._plugins.registerFactory(D,async(C,y)=>{let x=await import(E),b=x.default??x.createPlugin;if(typeof b!="function")throw new Error(`Plugin "${l.name}" entry point must export a default function or "createPlugin" function`);return b(C,y,this._coordinator)})}}}catch{}this._config.lazyLoading||await this._plugins.loadAll();try{let{isAgentMemoryBranchingEnabled:t,isRVFPatternStoreEnabled:r}=await import("./feature-flags-NQHRPIUT.js");if(t()&&r()){let{getSharedRvfAdapter:i}=await import("./shared-rvf-adapter-KBGYVHKT.js"),{AgentMemoryBranch:n}=await import("./agent-memory-branch-XAM3NPTO.js"),o=i(u,384);if(o){let l=new n(o,{branchDir:o0.join(u,"branches")});this._coordinator.setMemoryBranch(l)}}}catch{}try{let{getRvfMigrationStage:t}=await import("./feature-flags-NQHRPIUT.js"),r=t();if(r>=2){let{RvfMigrationCoordinator:i}=await import("./rvf-migration-coordinator-ROE2JI6M.js");await i.getInstance({stage:r}).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(e){return this._plugins.getPlugin(e)?.getAPI()}async getDomainAPIAsync(e){let u=this._plugins.getPlugin(e);if(!u&&this._config.lazyLoading&&this._config.enabledDomains.includes(e))try{u=await this._plugins.load(e)}catch(a){console.error(`[QEKernel] Failed to lazy load domain ${e}:`,a);return}return u?.getAPI()}async ensureDomainLoaded(e){if(this._plugins.isLoaded(e))return!0;if(!this._config.enabledDomains.includes(e))return console.warn(`[QEKernel] Domain ${e} is not enabled`),!1;try{return await this._plugins.load(e),!0}catch(u){return console.error(`[QEKernel] Failed to load domain ${e}:`,u),!1}}isDomainLoaded(e){return this._plugins.isLoaded(e)}getLoadedDomains(){return this._plugins.getLoaded()}getPendingDomains(){let e=new Set(this._plugins.getLoaded());return this._config.enabledDomains.filter(u=>!e.has(u))}getHealth(){let e=this._coordinator.listAgents(),u={};for(let l of this._plugins.getLoaded()){let c=this._plugins.getPlugin(l);c&&(u[l]=c.getHealth())}for(let l of Fu)if(!u[l]){let c=this._config.enabledDomains.includes(l),E=this._config.lazyLoading&&c;u[l]={status:E?"healthy":c?"degraded":"healthy",agents:{total:0,active:0,idle:0,failed:0},errors:E?[]:c?["Domain not yet loaded"]:[],loaded:!1,lazyLoadable:E}}let a=this._coordinator.getActiveCount(),t=0,r=Number.MAX_SAFE_INTEGER;if(this._memory instanceof Qi){let l=this._memory.getStats();t=l.entries+l.vectors}else t=0;let n=this._eventBus.getMiddlewares().find(l=>l.name==="semantic-anti-drift"),o=n?n.getStats():void 0;return{status:this.determineOverallStatus(u),uptime:Date.now()-this._startTime.getTime(),domains:u,agents:{total:e.length,active:a,maxAllowed:this._config.maxConcurrentAgents},memory:{used:t,available:r},...o?{antiDrift:o}:{}}}determineOverallStatus(e){let u=Object.values(e).map(a=>a.status);return u.some(a=>a==="unhealthy")?"unhealthy":u.some(a=>a==="degraded")?"degraded":"healthy"}getConfig(){return{...this._config}}checkToolCall(e,u,a){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return this._loopTracker.trackCall(e,u,a);let t=this._loopTracker.trackCall(e,u,a);if(t.action==="warn"){let r={id:`loop-warn-${e}-${Date.now()}`,type:on.LOOP_WARNING,timestamp:new Date,source:"coordination",correlationId:e,payload:{agentId:e,toolName:u,callCount:t.callCount,signature:t.signature}};this._eventBus.publish(r)}else if(t.action==="steer"){let r={id:`loop-detected-${e}-${Date.now()}`,type:on.LOOP_DETECTED,timestamp:new Date,source:"coordination",correlationId:e,payload:{agentId:e,toolName:u,callCount:t.callCount,signature:t.signature,steeringMessage:t.steeringMessage}};this._eventBus.publish(r)}return t}get loopTracker(){return this._loopTracker}};function dre(s){return new Ql(s)}export{Ie as a,ve as b,f0 as c,b0 as d,Ue as e,Dl as f,yu as g,Ju as h,Xe as i,Al as j,si as k,K0 as l,j0 as m,Ni as n,V0 as o,_0 as p,a0 as q,t0 as r,r0 as s,Mu as t,Ru as u,Ql as v,dre as w};
3029
+ // Execute action: {{action}}`,variables:a}}extractPatternContext(e){let u=new Set,a,t;for(let r of e){let i=r.state.context;if(i.language&&(a=i.language),i.framework&&(t=i.framework),i.tags&&Array.isArray(i.tags))for(let n of i.tags)u.add(n)}return{language:a,framework:t,tags:Array.from(u)}}calculateConsolidatedConfidence(e){let u=e.reduce((t,r)=>t+r.usageCount,0),a=0;for(let t of e){let r=u>0?t.usageCount/u:1/e.length;a+=t.confidence*r}return a}calculateWeightedSuccessRate(e){let u=e.reduce((t,r)=>t+r.usageCount,0),a=0;for(let t of e){let r=u>0?t.usageCount/u:1/e.length;a+=t.successRate*r}return a}detectAnomalies(e){let u=[],a=this.calculateAverageReward(e),t=this.calculateStdDev(e.map(r=>r.reward));for(let r of e){let i=Math.abs(r.reward-a)/(t||1);if(i>this.config.anomalyDeviationThreshold){let n="outlier-reward";r.result.success&&r.reward<a?n="unexpected-success":!r.result.success&&r.reward>a&&(n="unexpected-failure"),u.push({experienceId:r.id,type:n,description:`Reward ${r.reward.toFixed(2)} deviates ${i.toFixed(2)} std from mean ${a.toFixed(2)}`,deviation:i})}}return u}calculateStdDev(e){if(e.length===0)return 0;let u=e.reduce((t,r)=>t+r,0)/e.length,a=e.map(t=>Math.pow(t-u,2));return Math.sqrt(a.reduce((t,r)=>t+r,0)/e.length)}generateRecommendations(e,u,a){let t=[];return u<.5&&t.push("Low success rate detected. Consider reviewing the approach or gathering more training data."),a.length>e.length*.1&&t.push("High anomaly rate detected. Investigate unexpected outcomes for potential improvements."),e.reduce((i,n)=>i+n.result.duration,0)/e.length>6e4&&t.push("Average operation duration is high. Consider optimizing performance."),e.length<10&&t.push("Limited experience data. Collect more data points for better insights."),t.length===0&&t.push("Performance metrics are within acceptable ranges. Continue monitoring."),t}actionsSimilar(e,u){let a=i=>i.toLowerCase().replace(/[^a-z]/g,""),t=a(e),r=a(u);return!!(t===r||t.includes(r)||r.includes(t))}calculateCentroid(e){let u={},a={};for(let t of e)for(let[r,i]of Object.entries(t.state.metrics))u[r]=(u[r]||0)+i,a[r]=(a[r]||0)+1;for(let t of Object.keys(u))u[t]/=a[t];return{context:{},metrics:u}}isConstraintViolated(e,u){switch(e.operator){case"lt":return u>=e.value;case"gt":return u<=e.value;case"lte":return u>e.value;case"gte":return u<e.value;case"eq":return u!==e.value;default:return!1}}};S();var P2u={maxKnowledgeItems:1e3,relevanceThreshold:.5,transferDecayFactor:.1,crossDomainBoost:.2},t0=class{constructor(e,u={}){this.memory=e;this.config={...P2u,...u}}config;async shareKnowledge(e,u){try{await this.memory.set(`learning:knowledge:shared:${e.id}`,e,{namespace:"learning-optimization",persist:!0});for(let a of u)await this.memory.set(`learning:knowledge:access:${a.value}:${e.id}`,{knowledgeId:e.id,agentId:a.value,sharedAt:new Date,accessed:!1},{namespace:"learning-optimization",ttl:86400*7});return await this.recordSharingEvent(e,u),p(void 0)}catch(a){return m(g(a))}}async queryKnowledge(e){try{let u=[],a;e.domain?a=await this.memory.search(`learning:knowledge:*:${e.domain}:*`,e.limit||100):a=await this.memory.search("learning:knowledge:shared:*",e.limit||100);for(let t of a){let r=await this.memory.get(t);r&&this.matchesQuery(r,e)&&u.push(r)}if(u.sort((t,r)=>r.relevanceScore-t.relevanceScore),e.embedding&&e.embedding.length>0){let t=await this.memory.vectorSearch(e.embedding,e.limit||10);for(let r of t){let i=await this.memory.get(r.key);i&&!u.some(n=>n.id===i.id)&&this.matchesQuery(i,e)&&u.push(i)}}return p(u.slice(0,e.limit||100))}catch(u){return m(g(u))}}async synthesizeKnowledge(e){try{if(e.length<2)return m(new Error("Need at least 2 knowledge items to synthesize"));let u=[];for(let l of e){let c=await this.getKnowledgeById(l);c&&u.push(c)}if(u.length<2)return m(new Error("Not enough valid knowledge items found"));let a=this.determineSynthesizedType(u),t=this.determineSynthesizedDomain(u),r=this.mergeKnowledgeContent(u),i=u.reduce((l,c)=>l+c.relevanceScore,0)/u.length,n=Math.min(1,i+this.config.crossDomainBoost),o={id:A(),type:a,domain:t,content:r,sourceAgentId:u[0].sourceAgentId,targetDomains:this.mergeTargetDomains(u),relevanceScore:n,version:1,createdAt:new Date};return await this.storeKnowledge(o),await this.recordSynthesisEvent(o,e),p(o)}catch(u){return m(g(u))}}async transferKnowledge(e,u){try{if(e.domain===u)return m(new Error("Cannot transfer knowledge to the same domain"));let a=this.calculateTransferredRelevance(e,u);if(a<this.config.relevanceThreshold)return m(new Error(`Transferred relevance ${a} below threshold ${this.config.relevanceThreshold}`));let t=await this.adaptContentForDomain(e.content,e.domain,u),r={id:A(),type:e.type,domain:u,content:t,sourceAgentId:e.sourceAgentId,targetDomains:[u],relevanceScore:a,version:e.version+1,createdAt:new Date};return await this.storeKnowledge(r),await this.recordTransferEvent(e,r),p(r)}catch(a){return m(g(a))}}async validateRelevance(e,u){try{let a=e.relevanceScore;if(u.language&&e.content.metadata?.language===u.language&&(a+=.1),u.framework&&e.content.metadata?.framework===u.framework&&(a+=.1),u.tags.length>0&&e.content.metadata?.tags){let n=e.content.metadata.tags,o=u.tags.filter(l=>n.includes(l));a+=o.length/u.tags.length*.2}let r=(Date.now()-e.createdAt.getTime())/(1e3*60*60*24),i=Math.exp(-this.config.transferDecayFactor*r/30);return a*=i,e.expiresAt&&new Date>e.expiresAt&&(a*=.5),p(Math.min(1,Math.max(0,a)))}catch(a){return m(g(a))}}async createKnowledge(e,u,a,t,r=[],i){try{let n={id:A(),type:e,domain:u,content:{format:this.inferContentFormat(a),data:a,metadata:i},sourceAgentId:t,targetDomains:r,relevanceScore:1,version:1,createdAt:new Date};return await this.storeKnowledge(n),e==="embedding"&&Array.isArray(a)&&await this.memory.storeVector(`learning:knowledge:vector:${n.id}`,a,{knowledgeId:n.id}),p(n)}catch(n){return m(g(n))}}async getKnowledgeById(e){return await this.memory.get(`learning:knowledge:shared:${e}`)||null}async bulkTransfer(e,u,a){try{let t=await this.memory.search(`learning:knowledge:project:${e}:*`,500),r=[];for(let i of t){let n=await this.memory.get(i);if(!n||a?.types&&!a.types.includes(n.type)||a?.minRelevance&&n.relevanceScore<a.minRelevance)continue;let o=await this.adaptContentForProject(n.content,e,u),l={...n,id:A(),content:o,relevanceScore:n.relevanceScore*(1-this.config.transferDecayFactor),version:n.version+1,createdAt:new Date};await this.memory.set(`learning:knowledge:project:${u}:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),r.push({knowledgeId:l.id,sourceDomain:n.domain,targetDomain:n.domain,originalRelevance:n.relevanceScore,transferredRelevance:l.relevanceScore,adaptations:["project-context-adapted"]})}return p(r)}catch(t){return m(g(t))}}async storeKnowledge(e){await this.memory.set(`learning:knowledge:shared:${e.id}`,e,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:domain:${e.domain}:${e.id}`,e.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:type:${e.type}:${e.id}`,e.id,{namespace:"learning-optimization",persist:!0})}matchesQuery(e,u){if(u.type&&e.type!==u.type||u.domain&&e.domain!==u.domain||u.minRelevance!==void 0&&e.relevanceScore<u.minRelevance)return!1;if(u.tags&&u.tags.length>0){let a=e.content.metadata?.tags||[];if(!u.tags.some(r=>a.includes(r)))return!1}return!0}determineSynthesizedType(e){let u=new Map;for(let r of e)u.set(r.type,(u.get(r.type)||0)+1);let a=e[0].type,t=0;for(let[r,i]of u)i>t&&(t=i,a=r);return a}determineSynthesizedDomain(e){let u=new Map;for(let r of e)u.set(r.domain,(u.get(r.domain)||0)+1);let a=e[0].domain,t=0;for(let[r,i]of u)i>t&&(t=i,a=r);return a}mergeKnowledgeContent(e){let u={},a=[];for(let t of e)if(a.push(t.content.data),t.content.metadata)for(let[r,i]of Object.entries(t.content.metadata))if(Array.isArray(i)){let n=u[r]||[];u[r]=[...new Set([...n,...i])]}else u[r]=i;return{format:"json",data:{synthesized:!0,sources:a},metadata:{...u,synthesizedFrom:e.map(t=>t.id),synthesizedAt:new Date().toISOString()}}}mergeTargetDomains(e){let u=new Set;for(let a of e){u.add(a.domain);for(let t of a.targetDomains)u.add(t)}return Array.from(u)}calculateTransferredRelevance(e,u){let a=e.relevanceScore;a*=1-this.config.transferDecayFactor;let t=this.getDomainCompatibility(e.domain,u);return a*=t,e.targetDomains.includes(u)&&(a+=this.config.crossDomainBoost),Math.min(1,Math.max(0,a))}getDomainCompatibility(e,u){let a={"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:Fu.filter(t=>t!=="coordination")};return e===u?1:a[e]?.includes(u)?.8:.5}async adaptContentForDomain(e,u,a){return{...e,metadata:{...e.metadata||{},adaptedFrom:u,adaptedTo:a,adaptedAt:new Date().toISOString()}}}async adaptContentForProject(e,u,a){return{...e,metadata:{...e.metadata||{},sourceProject:u,targetProject:a,transferredAt:new Date().toISOString()}}}inferContentFormat(e){return typeof e=="string"?"text":Array.isArray(e)&&e.every(u=>typeof u=="number")?"embedding":"json"}async recordSharingEvent(e,u){await this.memory.set(`learning:knowledge:events:share:${e.id}:${Date.now()}`,{type:"share",knowledgeId:e.id,targetAgents:u.map(a=>a.value),timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordSynthesisEvent(e,u){await this.memory.set(`learning:knowledge:events:synthesis:${e.id}`,{type:"synthesis",synthesizedId:e.id,sourceIds:u,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordTransferEvent(e,u){await this.memory.set(`learning:knowledge:events:transfer:${u.id}`,{type:"transfer",originalId:e.id,transferredId:u.id,originalDomain:e.domain,targetDomain:u.domain,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}};S();cu();var z2u={defaultConfidenceLevel:.95,minSamplesForOptimization:20,maxOptimizationIterations:100,improvementThreshold:.05,explorationRate:.1},L2u=["__proto__","constructor","prototype"];function st(s){return!L2u.includes(s)}var r0=class{constructor(e,u={}){this.memory=e;this.config={...z2u,...u}}config;async optimizeStrategy(e,u,a){try{if(a.length<this.config.minSamplesForOptimization)return m(new Error(`Need at least ${this.config.minSamplesForOptimization} experiences for optimization`));let t=this.evaluateStrategyPerformance(e,a,u),r=await this.optimizeParameters(e.parameters,a,u),i={name:`${e.name}-optimized`,parameters:r,expectedOutcome:this.predictOutcome(r,a)},n=await this.validateOptimization(e,i,a.slice(-10)),o=this.evaluateStrategyPerformance(i,a,u),l=this.calculateImprovement(t,o,u),c=this.calculateOptimizationConfidence(a.length,l,n),E=this.inferDomainFromExperiences(a),d={id:A(),domain:E,objective:u,currentStrategy:e,optimizedStrategy:i,improvement:l,confidence:c,validationResults:n};return await this.storeOptimizationResult(d),p(d)}catch(t){return m(g(t))}}async runABTest(e,u,a){try{let t=await this.collectStrategyMetrics(e,a.metric,a.minSamples),r=await this.collectStrategyMetrics(u,a.metric,a.minSamples),i=this.calculateMean(t),n=this.calculateMean(r),o=this.calculateStdDev(t),l=this.calculateStdDev(r),c=this.calculatePValue(t,r),E;c<1-a.confidenceLevel?E=i>n?"A":"B":E="inconclusive";let d={winner:E,strategyAMetrics:{[a.metric]:i,stdDev:o,samples:t.length},strategyBMetrics:{[a.metric]:n,stdDev:l,samples:r.length},pValue:c,sampleSizeA:t.length,sampleSizeB:r.length};return await this.storeABTestResult(e,u,d),p(d)}catch(t){return m(g(t))}}async recommendStrategy(e){try{let u=await this.memory.search("learning:strategy:optimized:*",100),a=[];for(let t of u){let r=await this.memory.get(t);if(r&&r.confidence>.6){let i=this.scoreContextMatch(r,e),n=r.improvement*r.confidence;a.push({strategy:r.optimizedStrategy,score:i*.4+n*.6})}}return a.length===0?p({name:"default-strategy",parameters:this.getDefaultParameters(e),expectedOutcome:{success_rate:.7}}):(a.sort((t,r)=>r.score-t.score),p(a[0].strategy))}catch(u){return m(g(u))}}async evaluateStrategy(e,u){try{let a={},t=this.calculateSuccessRate(u),r=this.calculateAverageDuration(u),i=this.calculateAverageReward(u);a.success_rate=t,a.avg_duration_ms=r,a.avg_reward=i;let n=[];t>.8&&n.push("High success rate"),r<5e3&&n.push("Fast execution"),i>.7&&n.push("Consistently good rewards");let o=[];t<.5&&o.push("Low success rate needs investigation"),r>3e4&&o.push("Slow execution time"),i<.3&&o.push("Low reward values");let l=this.identifyImprovementAreas(e,a,u),c={strategy:e,metrics:a,strengths:n,weaknesses:o,improvementAreas:l};return await this.storeStrategyEvaluation(c),p(c)}catch(a){return m(g(a))}}async trackMetrics(e,u){try{let a={strategyId:e,metrics:u,timestamp:new Date,samples:1},t=`learning:metrics:history:${e}:${Date.now()}`;return await this.memory.set(t,a,{namespace:"learning-optimization",ttl:86400*30}),await this.updateAggregatedMetrics(e,u),p(void 0)}catch(a){return m(g(a))}}async getMetricsHistory(e,u=100){try{let a=await this.memory.search(`learning:metrics:history:${e}:*`,u),t=[];for(let r of a){let i=await this.memory.get(r);i&&t.push(i)}return t.sort((r,i)=>r.timestamp.getTime()-i.timestamp.getTime()),p(t)}catch(a){return m(g(a))}}async gridSearchOptimize(e,u,a){try{let t=this.generateParameterCombinations(e),r={},i=u.direction==="maximize"?-1/0:1/0;for(let n of t){let o=this.scoreParameters(n,a,u);(u.direction==="maximize"?o>i:o<i)&&(i=o,r=n)}return p(r)}catch(t){return m(g(t))}}evaluateStrategyPerformance(e,u,a){let t=0,r=0;for(let i of u){let n=i.result.outcome[a.metric]??0;t+=n,r++}return r>0?t/r:0}async optimizeParameters(e,u,a){let t={...e};for(let[r,i]of Object.entries(e))if(st(r)&&typeof i=="number"){let n=[-.1,-.05,0,.05,.1],o=0,l=this.scoreParameters(t,u,a);for(let c of n){let E={...t,[r]:i*(1+c)},d=this.scoreParameters(E,u,a);(a.direction==="maximize"?d>l:d<l)&&(l=d,o=c)}t[r]=i*(1+o)}return t}scoreParameters(e,u,a){let t=0,r=0;for(let i of u){let n=i.result.success?1:.5,o=this.calculateParamSimilarity(e,i.state.context),l=i.result.outcome[a.metric]??0;t+=o*l*n,r+=n}return r>0?t/r:0}calculateParamSimilarity(e,u){let a=0,t=0;for(let[r,i]of Object.entries(e))if(u[r]!==void 0)if(t++,typeof i=="number"&&typeof u[r]=="number"){let n=Math.abs(i-u[r]),o=Math.max(Math.abs(i),Math.abs(u[r]),1);a+=1-n/o}else i===u[r]&&a++;return t>0?a/t:.5}predictOutcome(e,u){let a={},t={},r={};for(let i of u)if(i.result.success)for(let[n,o]of Object.entries(i.result.outcome))st(n)&&typeof o=="number"&&(t[n]=(t[n]||0)+o,r[n]=(r[n]||0)+1);for(let[i,n]of Object.entries(t))st(i)&&(a[i]=n/r[i]);return a}async validateOptimization(e,u,a){let t=[];for(let r of a){let i=u.expectedOutcome,n=Object.entries(i).every(([o,l])=>{let c=r.result.outcome[o]??0;return Math.abs(c-l)/Math.max(l,1)<.2});t.push({testId:r.id,passed:n,metrics:r.state.metrics})}return t}calculateImprovement(e,u,a){if(e===0)return u>0?1:0;let t=u-e,r=a.direction==="maximize"?t/e:-t/e;return Math.max(-1,Math.min(1,r))}calculateOptimizationConfidence(e,u,a){let t=Math.min(1,e/(this.config.minSamplesForOptimization*2)),r=a.filter(n=>n.passed).length/Math.max(a.length,1),i=Math.abs(u)>this.config.improvementThreshold?1:.5;return t*.3+r*.5+i*.2}inferDomainFromExperiences(e){let u=new Map;for(let r of e)u.set(r.domain,(u.get(r.domain)||0)+1);let a="learning-optimization",t=0;for(let[r,i]of u)i>t&&(t=i,a=r);return a}async collectStrategyMetrics(e,u,a){let t=await this.memory.search("learning:metrics:history:*:*",a*2),r=[];for(let i of t){let n=await this.memory.get(i);n&&n.metrics[u]!==void 0&&r.push(n.metrics[u])}for(;r.length<a;){let i=e.expectedOutcome[u]||.5,n=(K()-.5)*.2;r.push(i+n)}return r}calculateMean(e){return e.length===0?0:e.reduce((u,a)=>u+a,0)/e.length}calculateStdDev(e){if(e.length===0)return 0;let u=this.calculateMean(e),a=e.map(t=>Math.pow(t-u,2));return Math.sqrt(a.reduce((t,r)=>t+r,0)/e.length)}calculatePValue(e,u){let a=this.calculateMean(e),t=this.calculateMean(u),r=Math.pow(this.calculateStdDev(e),2),i=Math.pow(this.calculateStdDev(u),2),n=e.length,o=u.length,l=Math.sqrt(r/n+i/o);if(l===0)return .5;let c=Math.abs(a-t)/l,E=2*(1-this.normalCDF(c));return Math.max(0,Math.min(1,E))}normalCDF(e){let u=.254829592,a=-.284496736,t=1.421413741,r=-1.453152027,i=1.061405429,n=.3275911,o=e<0?-1:1;e=Math.abs(e)/Math.sqrt(2);let l=1/(1+n*e),c=1-((((i*l+r)*l+t)*l+a)*l+u)*l*Math.exp(-e*e);return .5*(1+o*c)}scoreContextMatch(e,u){let a=0,t=0;return u.tags.some(r=>r===e.objective.metric)&&(a+=1),t+=1,u.tags.some(r=>r===e.domain)&&(a+=1),t+=1,t>0?a/t:.5}getDefaultParameters(e){let u={timeout:3e4,retryCount:3,concurrency:4};return e.framework&&(u.framework=e.framework),e.language&&(u.language=e.language),u}calculateSuccessRate(e){return e.length===0?0:e.filter(u=>u.result.success).length/e.length}calculateAverageDuration(e){return e.length===0?0:e.reduce((u,a)=>u+a.result.duration,0)/e.length}calculateAverageReward(e){return e.length===0?0:e.reduce((u,a)=>u+a.reward,0)/e.length}identifyImprovementAreas(e,u,a){let t=[];u.success_rate<.8&&t.push("Increase success rate by tuning parameters"),u.avg_duration_ms>1e4&&t.push("Optimize for faster execution"),u.avg_reward<.5&&t.push("Improve reward through better strategy selection");let r=e.parameters;return r.retryCount<2&&t.push("Consider increasing retry count for resilience"),r.concurrency>8&&t.push("High concurrency may cause resource contention"),t}generateParameterCombinations(e){let u=Object.keys(e);if(u.length===0)return[{}];let a=[];function t(r,i){if(r===u.length){a.push({...i});return}let n=u[r];if(!st(n)){t(r+1,i);return}for(let o of e[n])i[n]=o,t(r+1,i)}return t(0,{}),a}async updateAggregatedMetrics(e,u){let a=`learning:metrics:aggregated:${e}`,r=(await this.memory.get(a))?.metrics||{};for(let[i,n]of Object.entries(u))st(i)&&(r[i]||(r[i]={sum:0,count:0}),r[i].sum+=n,r[i].count+=1);await this.memory.set(a,{metrics:r,updatedAt:new Date},{namespace:"learning-optimization",persist:!0})}async storeOptimizationResult(e){await this.memory.set(`learning:strategy:optimized:${e.id}`,e,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:strategy:domain:${e.domain}:${e.id}`,e.id,{namespace:"learning-optimization",persist:!0})}async storeABTestResult(e,u,a){let t=A();await this.memory.set(`learning:abtest:${t}`,{testId:t,strategyA:e.name,strategyB:u.name,result:a,timestamp:new Date},{namespace:"learning-optimization",persist:!0})}async storeStrategyEvaluation(e){let u=A();await this.memory.set(`learning:evaluation:${u}`,{...e,evaluatedAt:new Date},{namespace:"learning-optimization",ttl:86400*7})}};S();var N2u={metricsRetentionDays:90,anomalyThreshold:2.5,trendWindowSize:7,alertThresholds:{error_rate:.05,latency_p99:5e3,memory_usage:.9,cpu_usage:.8}},i0=class{constructor(e,u={}){this.memory=e;this.config={...N2u,...u}}config;async recordMetric(e,u,a,t,r=[]){try{let i={id:A(),name:e,value:u,unit:a,domain:t,tags:r,timestamp:new Date};return await this.memory.set(`production:metric:${i.id}`,i,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400}),await this.indexMetric(i),await this.checkForAnomalies(i),p(i.id)}catch(i){return m(g(i))}}async recordMetricsBatch(e){try{let u=[];for(let a of e){let t=await this.recordMetric(a.name,a.value,a.unit,a.domain,a.tags);t.success&&u.push(t.value)}return p(u)}catch(u){return m(g(u))}}async getMetricsHistory(e,u,a){try{let t=a?`production:metric:index:${e}:${a}:*`:`production:metric:index:${e}:*`,r=await this.memory.search(t,1e3),i=[];for(let n of r){let o=await this.memory.get(n);if(o){let l=await this.memory.get(`production:metric:${o}`);l&&u.contains(l.timestamp)&&i.push(l)}}return i.sort((n,o)=>n.timestamp.getTime()-o.timestamp.getTime()),p(i)}catch(t){return m(g(t))}}async recordIncident(e,u,a,t,r){try{let i={id:A(),severity:e,title:u,description:a,domain:t,metrics:r,startedAt:new Date};return await this.memory.set(`production:incident:${i.id}`,i,{namespace:"learning-optimization",persist:!0}),await this.indexIncident(i),await this.createExperienceFromIncident(i),p(i)}catch(i){return m(g(i))}}async resolveIncident(e,u,a){try{let t=await this.memory.get(`production:incident:${e}`);if(!t)return m(new Error(`Incident ${e} not found`));let r={...t,rootCause:u,resolution:a,resolvedAt:new Date};return await this.memory.set(`production:incident:${e}`,r,{namespace:"learning-optimization",persist:!0}),await this.updateExperienceWithResolution(r),p(r)}catch(t){return m(g(t))}}async getRecentIncidents(e=10,u){try{let a=u?`production:incident:index:domain:${u}:*`:"production:incident:*",t=await this.memory.search(a,e*2),r=[];for(let n of t)if(n.includes(":index:")){let o=await this.memory.get(n);if(o){let l=await this.memory.get(`production:incident:${o}`);l&&r.push(l)}}else{let o=await this.memory.get(n);o&&r.push(o)}r.sort((n,o)=>o.startedAt.getTime()-n.startedAt.getTime());let i=Array.from(new Map(r.map(n=>[n.id,n])).values());return p(i.slice(0,e))}catch(a){return m(g(a))}}async getProductionHealth(){try{let e=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","code-intelligence","security-compliance","learning-optimization"],u={},a={},t="healthy",r=0,i=0;for(let E of e){let d=await this.getDomainHealth(E);u[E]=d,d.status==="degraded"&&r++,d.status==="unhealthy"&&i++;for(let[D,h]of Object.entries(d.metrics))a[`${E}_${D}`]=h}i>0?t="unhealthy":r>e.length/3&&(t="degraded");let n=await this.calculateTrends(),o=await this.getRecentIncidents(5),l=o.success?o.value:[],c=this.generateHealthRecommendations(u,a,l);return p({overall:t,domains:u,metrics:a,trends:n,recentIncidents:l,recommendations:c})}catch(e){return m(g(e))}}async getDomainHealth(e){let u=Ju.lastNDays(1),a=await this.getMetricsHistory("*",u,e),t={};if(a.success)for(let o of a.value)t[o.name],t[o.name]=o.value;let r=await this.getRecentIncidents(100,e),i=r.success?r.value.filter(o=>!o.resolvedAt).length:0,n="healthy";return i>2?n="unhealthy":i>0&&(n="degraded"),t.error_rate>this.config.alertThresholds.error_rate?n="unhealthy":t.latency_p99>this.config.alertThresholds.latency_p99&&(n="degraded"),{status:n,metrics:t,activeIncidents:i}}async calculateTrends(){let e=[],u=["error_rate","latency_p99","success_rate"],a=this.config.trendWindowSize;for(let t of u)for(let r=0;r<a;r++){let i=new Date;i.setDate(i.getDate()-r),i.setHours(0,0,0,0);let n=new Date(i);n.setHours(23,59,59,999);let o=Ju.create(i,n),l=await this.getMetricsHistory(t,o);if(l.success&&l.value.length>0){let c=l.value.reduce((E,d)=>E+d.value,0)/l.value.length;e.push({timestamp:i,metric:t,value:c})}}return e}generateHealthRecommendations(e,u,a){let t=[];for(let[n,o]of Object.entries(e))o.status==="unhealthy"?t.push(`Domain ${n} is unhealthy. Review active incidents and metrics.`):o.status==="degraded"&&t.push(`Domain ${n} is degraded. Monitor closely.`);for(let[n,o]of Object.entries(u)){let l=n.split("_").slice(-2).join("_"),c=this.config.alertThresholds[l];c&&o>c&&t.push(`Metric ${n} (${o.toFixed(2)}) exceeds threshold (${c})`)}let r=a.filter(n=>!n.resolvedAt);return r.length>3&&t.push(`${r.length} unresolved incidents require attention`),a.reduce((n,o)=>(n[o.severity]=(n[o.severity]||0)+1,n),{}).critical>2&&t.push("Multiple critical incidents detected. Consider system-wide review."),t.length===0&&t.push("All systems operating within normal parameters."),t}async extractInsights(e,u){try{let a=await this.getMetricsHistory("*",e,u),t=a.success?a.value:[],r=await this.getRecentIncidents(50,u),i=r.success?r.value:[],n=t.length,o=i.filter(D=>D.resolvedAt),l=i.length>0?o.length/i.length:1,c=this.calculateRewardFromIncidents(i),E=this.generateInsightRecommendations(t,i),d=this.detectMetricAnomalies(t);return p({experienceCount:n,successRate:l,avgReward:c,patterns:[],anomalies:d,recommendations:E})}catch(a){return m(g(a))}}async recordMilestone(e,u,a){try{let t={name:e,achievedAt:new Date,domain:u};return await this.memory.set(`production:milestone:${A()}`,{...t,metrics:a},{namespace:"learning-optimization",persist:!0}),p(t)}catch(t){return m(g(t))}}async getRecentMilestones(e=10){try{let u=await this.memory.search("production:milestone:*",e),a=[];for(let t of u){let r=await this.memory.get(t);r&&a.push(r)}return a.sort((t,r)=>r.achievedAt.getTime()-t.achievedAt.getTime()),p(a.slice(0,e))}catch(u){return m(g(u))}}async indexMetric(e){await this.memory.set(`production:metric:index:${e.name}:${e.domain}:${e.id}`,e.id,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400})}async indexIncident(e){await this.memory.set(`production:incident:index:domain:${e.domain}:${e.id}`,e.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`production:incident:index:severity:${e.severity}:${e.id}`,e.id,{namespace:"learning-optimization",persist:!0})}async checkForAnomalies(e){let u=Ju.lastNDays(7),a=await this.getMetricsHistory(e.name,u,e.domain);if(!a.success||a.value.length<10)return;let t=a.value.map(o=>o.value),r=t.reduce((o,l)=>o+l,0)/t.length,i=Math.sqrt(t.reduce((o,l)=>o+Math.pow(l-r,2),0)/t.length),n=Math.abs(e.value-r)/(i||1);n>this.config.anomalyThreshold&&await this.memory.set(`production:anomaly:${A()}`,{metricId:e.id,metricName:e.name,value:e.value,mean:r,stdDev:i,deviation:n,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*7})}async createExperienceFromIncident(e){let u={context:{incidentId:e.id,severity:e.severity,domain:e.domain},metrics:e.metrics},a={success:!1,outcome:e.metrics,duration:0},t={id:A(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:e.domain,action:`incident-${e.severity}`,state:u,result:a,reward:this.calculateIncidentReward(e),timestamp:e.startedAt};await this.memory.set(`learning:experience:${t.id}`,t,{namespace:"learning-optimization",ttl:86400*30})}async updateExperienceWithResolution(e){if(!e.resolvedAt)return;let u={context:{incidentId:e.id,rootCause:e.rootCause,resolution:e.resolution},metrics:e.metrics},a=e.resolvedAt.getTime()-e.startedAt.getTime(),t={success:!0,outcome:{...e.metrics,resolution_time_ms:a},duration:a},r={id:A(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:e.domain,action:`resolution-${e.severity}`,state:u,result:t,reward:1-this.calculateIncidentReward(e),timestamp:e.resolvedAt};await this.memory.set(`learning:experience:${r.id}`,r,{namespace:"learning-optimization",ttl:86400*30})}calculateIncidentReward(e){return-({critical:.9,high:.7,medium:.4,low:.2}[e.severity]||.5)}calculateRewardFromIncidents(e){if(e.length===0)return .8;let u={critical:.1,high:.3,medium:.6,low:.8},a=0,t=0;for(let r of e){let i=u[r.severity]||.5,n=r.resolvedAt?.2:0;a+=i+n,t++}return t>0?a/t:.8}generateInsightRecommendations(e,u){let a=[],t=new Map;for(let r of e){let i=t.get(r.name)||[];i.push(r.value),t.set(r.name,i)}for(let[r,i]of t){let n=this.calculateTrendDirection(i);n==="increasing"&&r.includes("error")?a.push(`${r} is trending upward. Investigate root causes.`):n==="decreasing"&&r.includes("success")&&a.push(`${r} is declining. Review recent changes.`)}if(u.length>0){let r=new Map;for(let i of u)r.set(i.domain,(r.get(i.domain)||0)+1);for(let[i,n]of r)n>3&&a.push(`Domain ${i} has ${n} incidents. Consider preventive measures.`)}return a}detectMetricAnomalies(e){let u=[],a=new Map;for(let t of e){let r=a.get(t.name)||[];r.push(t),a.set(t.name,r)}for(let[t,r]of a){if(r.length<5)continue;let i=r.map(l=>l.value),n=i.reduce((l,c)=>l+c,0)/i.length,o=Math.sqrt(i.reduce((l,c)=>l+Math.pow(c-n,2),0)/i.length);for(let l of r){let c=Math.abs(l.value-n)/(o||1);c>this.config.anomalyThreshold&&u.push({experienceId:l.id,type:"outlier-reward",description:`${t} value ${l.value.toFixed(2)} is ${c.toFixed(1)} std deviations from mean`,deviation:c})}}return u}calculateTrendDirection(e){if(e.length<3)return"stable";let u=e.slice(0,Math.floor(e.length/2)),a=e.slice(Math.floor(e.length/2)),t=u.reduce((n,o)=>n+o,0)/u.length,i=(a.reduce((n,o)=>n+o,0)/a.length-t)/(t||1);return i>.1?"increasing":i<-.1?"decreasing":"stable"}};async function WE(s,e,u){await s.set(`learning:strategy:current:${e}`,u,{namespace:"learning-optimization",persist:!0})}function $E(s,e){let u=s.map(a=>a.result.outcome[e]??0).filter(a=>!isNaN(a));return u.length===0?0:u.reduce((a,t)=>a+t,0)/u.length}function qE(s){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":Fu.filter(u=>u!=="learning-optimization"),"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:Fu.filter(u=>u!=="coordination")}[s]||[]}function JE(s){let e=[],u=new Set;for(let a of s){if(u.has(a.id))continue;let t=[a];u.add(a.id);for(let r of s)u.has(r.id)||a.type===r.type&&a.domain===r.domain&&I2u(a.context,r.context)&&(t.push(r),u.add(r.id));t.length>=2&&e.push(t)}return e}function I2u(s,e){return s.tags.some(u=>e.tags.includes(u))}function UE(s,e,u){let a=JSON.stringify({patternCount:s.length,knowledgeCount:e.length,strategyCount:u.length,patternIds:s.map(r=>r.id).sort(),knowledgeIds:e.map(r=>r.id).sort(),strategyIds:u.map(r=>r.id).sort()}),t=0;for(let r=0;r<a.length;r++){let i=a.charCodeAt(r);t=(t<<5)-t+i,t=t&t}return Math.abs(t).toString(16)}N();var q0=B.create("learning-optimization/consensus");async function ZE(s,e,u,a){let t=O({id:A(),type:"pattern-recommendation",confidence:e,description:`Verify pattern recommendation: ${s.name} (${s.type}) for domain ${s.domain}`,payload:s,detectedBy:"learning-optimization-coordinator",severity:e>.9?"high":"medium"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(q0.info(`Pattern recommendation '${s.name}' verified by consensus`),!0):(q0.warn(`Pattern recommendation '${s.name}' NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}async function QE(s,e,u,a){let t=O({id:A(),type:"optimization-suggestion",confidence:e,description:`Verify optimization: ${s.metric} from ${s.currentValue} to ${s.targetValue} via ${s.strategy}`,payload:s,detectedBy:"learning-optimization-coordinator",severity:e>.85?"high":"medium"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(q0.info(`Optimization suggestion for '${s.metric}' verified by consensus`),!0):(q0.warn(`Optimization suggestion for '${s.metric}' NOT verified`),!1)}return!0}async function YE(s,e,u,a){let t=O({id:A(),type:"cross-domain-insight",confidence:e,description:`Verify cross-domain insight: ${s.description}`,payload:s,detectedBy:"learning-optimization-coordinator",severity:"high"});if(u.requiresConsensus(t)){let r=await u.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(q0.info(`Cross-domain insight verified by consensus for ${s.targetDomains.length} target domains`),!0):(q0.warn(`Cross-domain insight NOT verified: ${r.success?r.value.verdict:r.error.message}`),!1)}return!0}var H2u={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},Tu=B.create("learning-optimization"),_i=class extends Y{constructor(u,a,t,r={}){let i={...H2u,...r};super(u,"learning-optimization",i,{verifyFindingTypes:["pattern-recommendation","optimization-suggestion","cross-domain-insight"]});this.memory=a;this.agentCoordinator=t;this.learningService=new a0({memory:a}),this.transferService=new t0(a),this.optimizerService=new r0(a),this.productionIntel=new i0(a)}learningService;transferService;optimizerService;productionIntel;sona=null;dreamScheduler=null;async onInitialize(){try{this.sona=await gu({domain:"learning-optimization",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.5}),Tu.info("PersistentSONAEngine initialized for pattern learning")}catch(u){Tu.error("Failed to initialize PersistentSONAEngine:",u instanceof Error?u:void 0),Tu.warn("Continuing without SONA pattern persistence"),this.sona=null}if(this.config.enableDreamScheduler)try{let u=await D4();await u.initialize(),this.dreamScheduler=h4({dreamEngine:u,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(),Tu.info("DreamScheduler initialized and started")}catch{Tu.warn("Failed to initialize DreamScheduler:")}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){if(await this.saveWorkflowState(),this.dreamScheduler){try{await this.dreamScheduler.dispose(),Tu.info("DreamScheduler disposed")}catch(u){Tu.error("Error disposing DreamScheduler:",u instanceof Error?u:void 0)}this.dreamScheduler=null}if(this.initialized&&this.sona)try{await this.sona.close()}catch(u){Tu.error("Error closing SONA engine:",u instanceof Error?u:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async runLearningCycle(u){let a=A();try{if(this.startWorkflow(a,"learning-cycle"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Tu.warn("Topology degraded, using conservative strategy for learning cycle"),this.minCutMixin.shouldPauseOperations())return m(new Error("Learning cycle paused: topology is in critical state"));let t=await this.spawnLearningAgent(a,u);if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);this.addAgentToWorkflow(a,t.value);let r=Ju.lastNDays(1),i=await this.getExperiencesForDomain(u,r),n=i.success?i.value:[];this.updateWorkflowProgress(a,20);let o=await this.learningService.mineExperiences(u,r),l=o.success?o.value.patterns.length:0;this.updateWorkflowProgress(a,50);let c=0,E=[];if(n.length>=10){let h={metric:"success_rate",direction:"maximize",constraints:[]},C=await this.getCurrentStrategy(u),y=await this.optimizerService.optimizeStrategy(C,h,n);y.success&&(c=1,E.push({metric:h.metric,before:this.calculateMetricValue(n,h.metric),after:y.value.optimizedStrategy.expectedOutcome[h.metric]||0,percentChange:y.value.improvement*100}))}this.updateWorkflowProgress(a,80);let d=0;o.success&&o.value.recommendations.length>0&&(await this.transferService.createKnowledge("heuristic",u,o.value.recommendations,{value:`learning-agent-${a.slice(0,8)}`,domain:"learning-optimization",type:"analyzer"},[u])).success&&(d=1),this.completeWorkflow(a),await this.agentCoordinator.stop(t.value);let D={domain:u,experiencesProcessed:n.length,patternsLearned:l,strategiesOptimized:c,knowledgeGenerated:d,improvements:E};return this.config.publishEvents&&l>0&&await this.publishPatternConsolidated(l,[u]),p(D)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async optimizeAllStrategies(){let u=A();try{if(this.startWorkflow(u,"optimization"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Tu.warn("Topology degraded, using conservative optimization strategy"),this.minCutMixin.shouldPauseOperations())return m(new Error("Optimization paused: topology is in critical state"));let a={},t=0,r=0,i=0,n=Fu.filter(l=>l!=="learning-optimization");for(let l=0;l<n.length;l++){let c=n[l];this.updateWorkflowProgress(u,Math.round(l/n.length*100));let E=Ju.lastNDays(7),d=await this.getExperiencesForDomain(c,E);if(!d.success||d.value.length<10)continue;let D=d.value,h={metric:"success_rate",direction:"maximize",constraints:[]},C=await this.getCurrentStrategy(c),y=await this.optimizerService.optimizeStrategy(C,h,D);y.success&&(t++,r+=y.value.improvement,i++,a[c]={strategiesOptimized:1,avgImprovement:y.value.improvement,bestStrategy:y.value.optimizedStrategy},await this.storeStrategy(c,y.value.optimizedStrategy))}this.completeWorkflow(u);let o={domainsOptimized:i,totalStrategies:t,avgImprovement:t>0?r/t:0,byDomain:a};return this.config.publishEvents&&t>0&&await this.publishOptimizationApplied(o),p(o)}catch(a){return this.failWorkflow(u,String(a)),m(g(a))}}async shareCrossDomainLearnings(){let u=A();try{if(this.startWorkflow(u,"transfer"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Tu.warn("Topology degraded, limiting cross-domain transfer scope"),this.minCutMixin.shouldPauseOperations())return m(new Error("Cross-domain sharing paused: topology is in critical state"));let a=0,t=[],r=0,i=0,n=0,o=await this.transferService.queryKnowledge({minRelevance:.7,limit:100});if(!o.success)return this.failWorkflow(u,o.error.message),m(o.error);let l=o.value;for(let d of l){let D=this.getRelatedDomains(d.domain);for(let h of D){if(h===d.domain)continue;i++,(await this.transferService.transferKnowledge(d,h)).success&&(n++,a++,t.includes(h)||t.push(h))}this.updateWorkflowProgress(u,Math.round(a/(l.length*2)*100))}let c=await this.learningService.getPatternStats();if(c.success){let d=c.value.topPatterns;if(d.length>=2){let D=this.findSimilarPatterns(d);for(let h of D)h.length>=2&&(await this.learningService.consolidatePatterns(h.map(y=>y.id))).success&&r++}}this.completeWorkflow(u);let E={knowledgeShared:a,domainsUpdated:t,transferSuccessRate:i>0?n/i:1,newPatternsCreated:r};return this.config.publishEvents&&a>0&&await this.publishTransferCompleted(E),p(E)}catch(a){return this.failWorkflow(u,String(a)),m(g(a))}}async getLearningDashboard(){try{let u=await this.learningService.getPatternStats(),a=u.success?u.value:null,t=await this.transferService.queryKnowledge({limit:1e3}),r=t.success?t.value.length:0,i=Ju.lastNDays(1),n=0;for(let C of Fu){let y=await this.getExperiencesForDomain(C,i);y.success&&(n+=y.value.length)}let o=await this.productionIntel.getProductionHealth(),l=o.success?o.value.trends:[],c=await this.productionIntel.getRecentMilestones(5),E=c.success?c.value:[],d=a?a.avgSuccessRate*.6+a.avgConfidence*.4:.5,D=[];if(a){let C=Object.entries(a.byDomain).filter(([y,x])=>x>0).map(([y,x])=>({domain:y,score:x})).sort((y,x)=>x.score-y.score);D.push(...C.slice(0,3).map(y=>y.domain))}let h={overallLearningRate:d,totalPatterns:a?.totalPatterns||0,totalKnowledge:r,experiencesLast24h:n,topPerformingDomains:D,learningTrend:l,recentMilestones:E};return p(h)}catch(u){return m(g(u))}}learnPattern(u,a,t,r,i,n){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.createPattern(u,a,t,r,i,n)}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(u,a,t){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.adaptPattern(u,a,t)}getSONAStats(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getStats()}getSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getAllPatterns()}getSONAPatternsByType(u){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByType(u)}getSONAPatternsByDomain(u){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByDomain(u)}updateSONAPattern(u,a,t){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.updatePattern(u,a,t)}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(u){this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.importPatterns(u)}async verifySONAPerformance(u=100){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.verifyPerformance(u)}async triggerDreamCycle(u){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");let a=await this.dreamScheduler.triggerDream(u);return this.config.publishEvents&&await this.publishDreamCycleCompleted(a.cycle.id,a.cycle.durationMs??0,a.cycle.conceptsProcessed,a.insights.map(t=>({id:t.id,type:t.type,description:t.description,noveltyScore:t.noveltyScore,confidenceScore:t.confidenceScore,actionable:t.actionable,suggestedAction:t.suggestedAction,sourceConcepts:t.sourceConcepts})),a.patternsCreated),a}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(u){let a=A();try{this.startWorkflow(a,"export");let t=u||Fu,r=[],i=[],n=[];for(let d of t){let D=await this.memory.search("learning:pattern:*",500);for(let h of D){let C=await this.memory.get(h);C&&t.includes(C.domain)&&r.push(C)}this.updateWorkflowProgress(a,Math.round(r.length/100*30))}let o=await this.transferService.queryKnowledge({limit:1e3});if(o.success)for(let d of o.value)t.includes(d.domain)&&i.push(d);this.updateWorkflowProgress(a,60);let l=await this.memory.search("learning:strategy:optimized:*",200);for(let d of l){let D=await this.memory.get(d);D&&t.includes(D.domain)&&n.push(D)}this.updateWorkflowProgress(a,90);let c=this.calculateChecksum(r,i,n);return this.completeWorkflow(a),p({version:"1.0.0",exportedAt:new Date,patterns:r,knowledge:i,strategies:n,checksum:c})}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async importModels(u){let a=A();try{if(this.startWorkflow(a,"import"),this.calculateChecksum(u.patterns,u.knowledge,u.strategies)!==u.checksum)return this.failWorkflow(a,"Checksum mismatch"),m(new Error("Import failed: checksum mismatch"));let r=0,i=0,n=0,o=[];for(let c of u.patterns){let E=await this.memory.get(`learning:pattern:${c.id}`);E?E.confidence<c.confidence?(await this.memory.set(`learning:pattern:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),r++,o.push({type:"pattern",id:c.id,reason:"Existing pattern had lower confidence",resolution:"overwrite"})):o.push({type:"pattern",id:c.id,reason:"Existing pattern has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:pattern:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),r++),this.updateWorkflowProgress(a,Math.round(r/u.patterns.length*30))}for(let c of u.knowledge){let E=await this.memory.get(`learning:knowledge:shared:${c.id}`);E?c.version>E.version?(await this.memory.set(`learning:knowledge:shared:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),i++,o.push({type:"knowledge",id:c.id,reason:"Import has newer version",resolution:"overwrite"})):o.push({type:"knowledge",id:c.id,reason:"Existing knowledge is same or newer version",resolution:"skip"}):(await this.memory.set(`learning:knowledge:shared:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),i++),this.updateWorkflowProgress(a,30+Math.round(i/u.knowledge.length*30))}for(let c of u.strategies){let E=await this.memory.get(`learning:strategy:optimized:${c.id}`);E?c.confidence>E.confidence?(await this.memory.set(`learning:strategy:optimized:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),n++,o.push({type:"strategy",id:c.id,reason:"Import has higher confidence",resolution:"overwrite"})):o.push({type:"strategy",id:c.id,reason:"Existing strategy has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:strategy:optimized:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),n++),this.updateWorkflowProgress(a,60+Math.round(n/u.strategies.length*40))}return this.completeWorkflow(a),p({patternsImported:r,knowledgeImported:i,strategiesImported:n,conflicts:o,resolved:!0})}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}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(u){let{runId:a,passed:t,failed:r,duration:i}=u.payload,n=t+r>0?t/(t+r):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:a},metrics:{passed:t,failed:r,duration:i}},result:{success:n>.8,outcome:{success_rate:n,passed:t,failed:r},duration:i},reward:n})}async handleCoverageGap(u){let{gapId:a,file:t,riskScore:r}=u.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:a,file:t},metrics:{riskScore:r}},result:{success:!0,outcome:{risk_score:r},duration:0},reward:1-r})}async handleQualityGate(u){let{gateId:a,passed:t}=u.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:a},metrics:{passed:t?1:0}},result:{success:t,outcome:{gate_passed:t?1:0},duration:0},reward:t?1:0})}async handleExperienceCaptured(u){let{experience:a}=u.payload;if(!a.success||a.quality<.7)return;let t=a.domain||"learning-optimization";if(await this.learningService.recordExperience({agentId:{value:a.agent||"unknown",domain:t,type:"specialist"},domain:t,action:a.task,state:{context:{experienceId:a.id,trajectoryId:a.trajectoryId,model:a.model},metrics:{durationMs:a.durationMs,stepCount:a.steps.length,quality:a.quality}},result:{success:a.success,outcome:{quality:a.quality,patterns_extracted:a.patterns?.length||0},duration:a.durationMs},reward:a.quality}),a.patterns&&a.patterns.length>0&&a.domain){let r=this.getRelatedDomains(a.domain);for(let i of r)i!==a.domain&&await this.transferService.transferKnowledge({id:`exp-${a.id}`,domain:a.domain,type:"workflow",content:{format:"json",data:{task:a.task,steps:a.steps,quality:a.quality,patterns:a.patterns}},sourceAgentId:{value:a.agent||"experience-capture",domain:a.domain,type:"specialist"},targetDomains:[i],relevanceScore:a.quality,version:1,createdAt:new Date(a.startedAt)},i);Tu.info(`[LearningOptimizationCoordinator] Experience ${a.id} transferred to ${r.length} related domains`)}this.dreamScheduler&&this.dreamScheduler.recordExperience({id:a.id,agentType:a.agent||"unknown",domain:t,taskType:a.task,success:a.success,duration:a.durationMs,context:{quality:a.quality,steps:a.steps.length,patterns:a.patterns?.length||0},timestamp:new Date(a.startedAt)})}async publishPatternConsolidated(u,a){let t={patternCount:u,domains:a,improvements:0},r=L(Yu.PatternConsolidated,"learning-optimization",t);await this.eventBus.publish(r)}async publishTransferCompleted(u){let a={sourceProject:"current",targetProject:"current",patternsTransferred:u.knowledgeShared,successRate:u.transferSuccessRate},t=L(Yu.TransferCompleted,"learning-optimization",a);await this.eventBus.publish(t)}async publishOptimizationApplied(u){let a=L(Yu.OptimizationApplied,"learning-optimization",{domainsOptimized:u.domainsOptimized,avgImprovement:u.avgImprovement});await this.eventBus.publish(a)}async publishDreamCycleCompleted(u,a,t,r,i){if(!this.config.publishEvents)return;let n={cycleId:u,durationMs:a,conceptsProcessed:t,insights:r,patternsCreated:i},o=L(Yu.DreamCycleCompleted,"learning-optimization",n);await this.eventBus.publish(o),Tu.info(`[LearningOptimizationCoordinator] Published dream cycle completion: ${r.length} insights for ${t} concepts`)}async spawnLearningAgent(u,a){if(!this.agentCoordinator.canSpawn())return m(new Error("Agent limit reached"));let t={name:`learning-agent-${u.slice(0,8)}`,domain:"learning-optimization",type:"optimizer",capabilities:["pattern-learning","experience-mining",a],config:{workflowId:u,targetDomain:a}};return this.agentCoordinator.spawn(t)}async loadWorkflowState(){let u=await this.memory.get("learning-optimization:coordinator:workflows");if(u)for(let a of u)a.status==="running"&&(a.status="failed",a.error="Coordinator restarted",a.completedAt=new Date),this.workflows.set(a.id,a)}async saveWorkflowState(){let u=Array.from(this.workflows.values());await this.memory.set("learning-optimization:coordinator:workflows",u,{namespace:"learning-optimization",persist:!0})}async getExperiencesForDomain(u,a){let t=await this.memory.search(`learning:experience:index:domain:${u}:*`,500),r=[];for(let i of t){let n=await this.memory.get(i);if(n){let o=await this.memory.get(`learning:experience:${n}`);o&&a.contains(o.timestamp)&&r.push(o)}}return p(r)}async getCurrentStrategy(u){let a=`learning:strategy:current:${u}`,t=await this.memory.get(a);return t||{name:`default-${u}`,parameters:{timeout:3e4,retryCount:3,concurrency:4},expectedOutcome:{success_rate:.8}}}async storeStrategy(u,a){await WE(this.memory,u,a)}calculateMetricValue(u,a){return $E(u,a)}getRelatedDomains(u){return qE(u)}findSimilarPatterns(u){return JE(u)}calculateChecksum(u,a,t){return UE(u,a,t)}async verifyPatternRecommendation(u,a){return ZE(u,a,this.consensusMixin,this.domainName)}async verifyOptimizationSuggestion(u,a){return QE(u,a,this.consensusMixin,this.domainName)}async verifyCrossDomainInsight(u,a){return YE(u,a,this.consensusMixin,this.domainName)}};S();var ql=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Coordinator not initialized"));let a=u.domain;return a?this.coordinator.runLearningCycle(a):m(new Error("Invalid run-learning-cycle payload: missing domain"))}],["optimize-strategies",async u=>this.coordinator?this.coordinator.optimizeAllStrategies():m(new Error("Coordinator not initialized"))],["share-learnings",async u=>this.coordinator?this.coordinator.shareCrossDomainLearnings():m(new Error("Coordinator not initialized"))],["learn-pattern",async u=>{if(!this.learningService)return m(new Error("Learning service not initialized"));let a=u.experiences;return!a||a.length===0?m(new Error("Invalid learn-pattern payload: missing experiences")):this.learningService.learnPattern(a)}],["query-knowledge",async u=>{if(!this.transferService)return m(new Error("Transfer service not initialized"));let a=u.query;return a?this.transferService.queryKnowledge(a):m(new Error("Invalid query-knowledge payload: missing query"))}]])}async onInitialize(){this.learningService=new a0({memory:this.memory},this.pluginConfig.learningService),this.transferService=new t0(this.memory,this.pluginConfig.transferService),this.optimizerService=new r0(this.memory,this.pluginConfig.optimizerService),this.productionIntel=new i0(this.memory,this.pluginConfig.productionIntel),this.coordinator=new _i(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"test-generation.TestGenerated":await this.handleTestGenerated(u);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(u);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(u);break;default:break}}async runLearningCycle(u){this.ensureInitialized();try{let a=await this.coordinator.runLearningCycle(u);return a.success?this.trackSuccessfulOperation("learning-cycle"):this.trackFailedOperation("learning-cycle",a.error),a}catch(a){return this.handleError(a)}}async optimizeAllStrategies(){this.ensureInitialized();try{let u=await this.coordinator.optimizeAllStrategies();return u.success?this.trackSuccessfulOperation("optimization"):this.trackFailedOperation("optimization",u.error),u}catch(u){return this.handleError(u)}}async shareCrossDomainLearnings(){this.ensureInitialized();try{return await this.coordinator.shareCrossDomainLearnings()}catch(u){return this.handleError(u)}}async getLearningDashboard(){this.ensureInitialized();try{return await this.coordinator.getLearningDashboard()}catch(u){return this.handleError(u)}}async exportModels(u){this.ensureInitialized();try{return await this.coordinator.exportModels(u)}catch(a){return this.handleError(a)}}async importModels(u){this.ensureInitialized();try{return await this.coordinator.importModels(u)}catch(a){return this.handleError(a)}}async learnPattern(u){this.ensureInitialized();try{return await this.learningService.learnPattern(u)}catch(a){return this.handleError(a)}}async findMatchingPatterns(u,a){this.ensureInitialized();try{return await this.learningService.findMatchingPatterns(u,a)}catch(t){return this.handleError(t)}}async applyPattern(u,a){this.ensureInitialized();try{return await this.learningService.applyPattern(u,a)}catch(t){return this.handleError(t)}}async updatePatternFeedback(u,a){this.ensureInitialized();try{return await this.learningService.updatePatternFeedback(u,a)}catch(t){return this.handleError(t)}}async getPatternStats(u){this.ensureInitialized();try{return await this.learningService.getPatternStats(u)}catch(a){return this.handleError(a)}}async queryKnowledge(u){this.ensureInitialized();try{return await this.transferService.queryKnowledge(u)}catch(a){return this.handleError(a)}}async transferKnowledge(u,a){this.ensureInitialized();try{return await this.transferService.transferKnowledge(u,a)}catch(t){return this.handleError(t)}}async optimizeStrategy(u,a,t){this.ensureInitialized();try{return await this.optimizerService.optimizeStrategy(u,a,t)}catch(r){return this.handleError(r)}}async runABTest(u,a,t){this.ensureInitialized();try{return await this.optimizerService.runABTest(u,a,t)}catch(r){return this.handleError(r)}}async recommendStrategy(u){this.ensureInitialized();try{return await this.optimizerService.recommendStrategy(u)}catch(a){return this.handleError(a)}}async evaluateStrategy(u,a){this.ensureInitialized();try{return await this.optimizerService.evaluateStrategy(u,a)}catch(t){return this.handleError(t)}}async handleTestGenerated(u){let a=u.payload;await this.learningService.recordExperience({agentId:{value:"test-generation",domain:"test-generation",type:"generator"},domain:"test-generation",action:"test-generated",state:{context:{testId:a.testId,testType:a.testType},metrics:{}},result:{success:!0,outcome:{generated:1},duration:0},reward:.8})}async handleTestRunCompleted(u){let a=u.payload,t=a.passed+a.failed>0?a.passed/(a.passed+a.failed):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:a.runId},metrics:{passed:a.passed,failed:a.failed,duration:a.duration}},result:{success:t>.8,outcome:{success_rate:t,passed:a.passed,failed:a.failed},duration:a.duration},reward:t}),await this.productionIntel.recordMetric("test_success_rate",t,"ratio","test-execution",["automated"])}async handleCoverageGap(u){let a=u.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:a.gapId,file:a.file},metrics:{riskScore:a.riskScore}},result:{success:!0,outcome:{risk_score:a.riskScore},duration:0},reward:1-a.riskScore})}async handleQualityGate(u){let a=u.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:a.gateId},metrics:{passed:a.passed?1:0}},result:{success:a.passed,outcome:{gate_passed:a.passed?1:0},duration:0},reward:a.passed?1:0})}async handleDefectPredicted(u){let a=u.payload;await this.learningService.recordExperience({agentId:{value:"defect-intelligence",domain:"defect-intelligence",type:"analyzer"},domain:"defect-intelligence",action:"defect-prediction",state:{context:{predictionId:a.predictionId},metrics:{probability:a.probability}},result:{success:!0,outcome:{probability:a.probability},duration:0},reward:.7})}async handleImpactAnalysis(u){let a=u.payload;await this.learningService.recordExperience({agentId:{value:"code-intelligence",domain:"code-intelligence",type:"analyzer"},domain:"code-intelligence",action:"impact-analysis",state:{context:{analysisId:a.analysisId},metrics:{changedFiles:a.changedFiles.length,impactedFiles:a.impactedFiles.length}},result:{success:!0,outcome:{changed_count:a.changedFiles.length,impacted_count:a.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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),m(a)}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u,a){let t=this.getHealth();this.updateHealth({agents:{...t.agents,failed:t.agents.failed+1},errors:[...t.errors.slice(-9),a.message]})}};function XE(s,e,u,a){return new ql(s,e,u,a)}var Jl=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}workflowOrchestrator=null;pluginConfig;get name(){return"coordination"}get version(){return"1.0.0"}get dependencies(){return Fu.filter(u=>u!=="coordination")}getAPI(){return{listWorkflows:async()=>{if(!this.workflowOrchestrator)throw new Error("Workflow orchestrator not initialized");return this.workflowOrchestrator.listWorkflows()}}}async onInitialize(){this.workflowOrchestrator=p4(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(u){u.type.startsWith("coordination.")&&await this.handleCoordinationEvent(u)}subscribeToEvents(){this.eventBus.subscribe("coordination.workflow.execute",async u=>{await this.handleEvent(u)})}async handleCoordinationEvent(u){u.type.split(".")[1]==="workflow"&&await this.handleWorkflowEvent(u)}async handleWorkflowEvent(u){this.workflowOrchestrator}};function u3(s,e,u,a){return new Jl(s,e,u,a)}var Mu={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"},Ul=class{factories=new Map;register(e,u){this.factories.set(e,u)}resolve(e){let u=this.factories.get(e);if(!u)throw new Error(`DomainServiceRegistry: service '${e}' not registered. Ensure the domain module is initialized before coordination.`);return u}has(e){return this.factories.has(e)}clear(){this.factories.clear()}keys(){return Array.from(this.factories.keys())}},Ru=new Ul;Ru.register(Mu.createTestGeneratorService,s=>Ie(s));Ru.register(Mu.CoverageAnalyzerService,s=>new ve(s));Ru.register(Mu.SecurityScannerService,s=>new Ou(s));Ru.register(Mu.isSemgrepAvailable,Xa);Ru.register(Mu.runSemgrepWithRules,li);Ru.register(Mu.convertSemgrepFindings,ci);Ru.register(Mu.KnowledgeGraphService,s=>new ze(s));S();Ru.register(Mu.QualityAnalyzerService,s=>new oe(s));S();N();S();var n0={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"},_2u={maxConcurrentWorkflows:8,defaultTimeout:12e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Wi=B.create("enterprise-integration"),$i=class extends Y{constructor(u,a,t,r={}){let i={..._2u,...r};super(u,"enterprise-integration",i,{verifyFindingTypes:["soap-fault","message-ordering-violation","rfc-compatibility-break","idoc-validation-failure","odata-contract-break","sod-conflict"],modelTimeout:12e4});this.memory=a;this.agentCoordinator=t}async onInitialize(){this.subscribeToEvents(),Wi.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(u){let a=A();try{if(this.startWorkflow(a,"soap"),this.minCutMixin.shouldPauseOperations())return m(new Error("WSDL validation paused: topology is in critical state"));let t=await this.spawnAgent(a,"qe-soap-tester",{task:"validate-wsdl",url:u});if(!t.success)return this.failWorkflow(a,t.error.message),t;let r={url:u,version:"1.1",services:[],schemas:[]};return await this.memory.set(`enterprise-integration:wsdl:${encodeURIComponent(u)}`,r,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(a),p(r)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async testSoapOperation(u,a,t){let r=A();try{this.startWorkflow(r,"soap");let i=await this.spawnAgent(r,"qe-soap-tester",{task:"test-operation",wsdl:u,operation:a,input:t});if(!i.success)return this.failWorkflow(r,i.error.message),m(i.error);let n={operation:a,passed:!0,request:JSON.stringify(t),response:"",validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(L(n0.SoapOperationTested,this.domainName,{operation:a,wsdlUrl:u.url,passed:n.passed,errors:n.validationErrors.length})),this.completeWorkflow(r),p(n)}catch(i){return this.failWorkflow(r,String(i)),m(g(i))}}async testMessageFlow(u,a){let t=A();try{this.startWorkflow(t,"messaging");let r=await this.spawnAgent(t,"qe-message-broker-tester",{task:"test-message-flow",brokerConfig:u,testCase:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={testCaseId:a.id,passed:!0,sentAt:new Date,receivedAt:new Date,latency:0,actualOutcome:a.expectedOutcome,errors:[]};return this.config.publishEvents&&await this.eventBus.publish(L(n0.MessageFlowTested,this.domainName,{protocol:u.protocol,queue:a.queue,passed:i.passed,latency:i.latency})),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async testDlqHandling(u,a){let t=A();try{this.startWorkflow(t,"messaging");let r=await this.spawnAgent(t,"qe-message-broker-tester",{task:"test-dlq",brokerConfig:u,queue:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={queue:a,messageCount:0,poisonMessages:0,reprocessable:0,errors:[]};return this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async testBapiCall(u,a){let t=A();try{if(this.startWorkflow(t,"rfc"),this.minCutMixin.shouldPauseOperations())return m(new Error("BAPI testing paused: topology is in critical state"));let r=await this.spawnAgent(t,"qe-sap-rfc-tester",{task:"test-bapi",connection:u,bapi:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={bapiName:a.name,passed:!0,returnMessages:[],exportValues:{},tableData:{},duration:0,transactionCommitted:!1};return this.config.publishEvents&&await this.eventBus.publish(L(n0.BapiTested,this.domainName,{bapiName:a.name,passed:i.passed,returnType:i.returnMessages.length>0?i.returnMessages[0].type:"S"})),await this.memory.set(`enterprise-integration:bapi:${a.name}:${Date.now()}`,{bapiName:a.name,importParams:Object.keys(a.importParams),passed:i.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async validateIdoc(u,a){let t=A();try{this.startWorkflow(t,"idoc");let r=await this.spawnAgent(t,"qe-sap-idoc-tester",{task:"validate-idoc",definition:u,content:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={idocType:u.type,direction:"inbound",passed:!0,statusCode:3,statusMessage:"IDoc validated successfully",segmentValidation:[],processingTime:0};return this.config.publishEvents&&await this.eventBus.publish(L(n0.IDocValidated,this.domainName,{idocType:u.type,direction:i.direction,passed:i.passed,statusCode:i.statusCode})),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async validateODataMetadata(u){let a=A();try{this.startWorkflow(a,"odata");let t=await this.spawnAgent(a,"qe-odata-contract-tester",{task:"validate-metadata",serviceUrl:u});if(!t.success)return this.failWorkflow(a,t.error.message),m(t.error);let r={version:"v4",serviceUrl:u,entitySets:[],functionImports:[],actions:[]};return await this.memory.set(`enterprise-integration:odata:${encodeURIComponent(u)}`,r,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(a),p(r)}catch(t){return this.failWorkflow(a,String(t)),m(g(t))}}async testODataEntitySet(u,a){let t=A();try{this.startWorkflow(t,"odata");let r=await this.spawnAgent(t,"qe-odata-contract-tester",{task:"test-entity-set",metadata:u,entitySet:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={entitySet:a,operation:"CRUD",passed:!0,statusCode:200,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(L(n0.ODataTested,this.domainName,{entitySet:a,operation:i.operation,passed:i.passed,version:u.version})),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async validateMessageFlow(u,a){let t=A();try{this.startWorkflow(t,"middleware");let r=await this.spawnAgent(t,"qe-middleware-validator",{task:"validate-flow",flow:u,input:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={flowName:u.name,passed:!0,routingCorrect:!0,transformationCorrect:!0,errorHandlingCorrect:!0,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(L(n0.MiddlewareFlowTested,this.domainName,{flowName:u.name,passed:i.passed,routingCorrect:i.routingCorrect,transformationCorrect:i.transformationCorrect})),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async validateTransformation(u,a,t){let r=A();try{this.startWorkflow(r,"middleware");let i=await this.spawnAgent(r,"qe-middleware-validator",{task:"validate-transformation",spec:u,input:a,expectedOutput:t});return i.success?(this.completeWorkflow(r),p(!0)):(this.failWorkflow(r,i.error.message),m(i.error))}catch(i){return this.failWorkflow(r,String(i)),m(g(i))}}async analyzeSod(u,a){let t=A();try{this.startWorkflow(t,"sod");let r=await this.spawnAgent(t,"qe-sod-analyzer",{task:"analyze-sod",userId:u,ruleset:a});if(!r.success)return this.failWorkflow(t,r.error.message),m(r.error);let i={userId:u,conflicts:[],riskScore:0,compliant:!0,recommendations:[]};return this.config.publishEvents&&await this.eventBus.publish(L(n0.SodAnalyzed,this.domainName,{userId:u,conflicts:i.conflicts.length,compliant:i.compliant,riskScore:i.riskScore})),await this.memory.set(`enterprise-integration:sod:${u}:${Date.now()}`,{userId:u,ruleset:a.name,conflicts:i.conflicts.length,compliant:i.compliant,riskScore:i.riskScore,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(t),p(i)}catch(r){return this.failWorkflow(t,String(r)),m(g(r))}}async spawnAgent(u,a,t){let r={name:`${a}-${u.slice(0,8)}`,domain:"enterprise-integration",type:a,capabilities:[a],config:{workflowId:u,...t}},i=await this.agentCoordinator.spawn(r);return i.success&&this.addAgentToWorkflow(u,i.value),i}async verifyCriticalFinding(u,a){let t=O({id:A(),type:u.type,confidence:a,description:u.description,payload:u.payload,detectedBy:"enterprise-integration-coordinator",severity:a>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(t)){let r=await this.consensusMixin.verifyFinding(t);return r.success&&r.value.verdict==="verified"?(Wi.info(`Finding verified by consensus: ${u.type}`),!0):(Wi.warn(`Finding NOT verified: ${u.type}`),!1)}return!0}async handleContractVerified(u){let a=u.payload;(a?.contractType==="soap"||a?.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-event:${Date.now()}`,{contractId:a.contractId,type:a.contractType,passed:a.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(u){let a=u.payload;(a?.targetService?.includes("middleware")||a?.targetService?.includes("esb"))&&Wi.info(`Middleware fault injection detected: ${a.targetService}`)}};var Zl=class extends U{constructor(u,a,t,r={}){super(u,a);this.agentCoordinator=t;this.pluginConfig=r}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 u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.wsdl,t=u.operation,r=u.input;return u.url&&!a?this.coordinator.validateWsdl(u.url):!a||!t?m(new Error("Invalid soap-test payload: missing wsdl or operation")):this.coordinator.testSoapOperation(a,t,r)}],["enterprise-integration:message-broker-test",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.brokerConfig,t=u.testCase,r=u.queue;return a?r&&!t?this.coordinator.testDlqHandling(a,r):t?this.coordinator.testMessageFlow(a,t):m(new Error("Invalid message-broker-test payload: missing testCase")):m(new Error("Invalid message-broker-test payload: missing brokerConfig"))}],["enterprise-integration:sap-rfc-test",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.connection,t=u.bapi;return!a||!t?m(new Error("Invalid sap-rfc-test payload: missing connection or bapi")):this.coordinator.testBapiCall(a,t)}],["enterprise-integration:sap-idoc-validate",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.definition,t=u.content;return!a||!t?m(new Error("Invalid sap-idoc-validate payload: missing definition or content")):this.coordinator.validateIdoc(a,t)}],["enterprise-integration:odata-test",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.serviceUrl,t=u.metadata,r=u.entitySet;return a&&!t?this.coordinator.validateODataMetadata(a):!t||!r?m(new Error("Invalid odata-test payload: missing metadata or entitySet")):this.coordinator.testODataEntitySet(t,r)}],["enterprise-integration:esb-flow-test",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.flow,t=u.input,r=u.spec;if(r){let i=u.transformInput,n=u.expectedOutput;return!i||!n?m(new Error("Invalid esb-flow-test payload: missing transformInput or expectedOutput for transformation")):this.coordinator.validateTransformation(r,i,n)}return!a||!t?m(new Error("Invalid esb-flow-test payload: missing flow or input")):this.coordinator.validateMessageFlow(a,t)}],["enterprise-integration:sod-analyze",async u=>{if(!this.coordinator)return m(new Error("Enterprise integration coordinator not initialized"));let a=u.userId,t=u.ruleset;return!a||!t?m(new Error("Invalid sod-analyze payload: missing userId or ruleset")):this.coordinator.analyzeSod(a,t)}]])}async onInitialize(){this.coordinator=new $i(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(u){switch(this.updateHealth({lastActivity:new Date}),u.type){case"contract-testing.ContractVerified":await this.handleContractVerified(u);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(u);break;case"chaos-resilience.FaultInjected":await this.handleFaultInjected(u);break;default:break}}async validateWsdl(u){this.ensureInitialized();try{let a=await this.coordinator.validateWsdl(u);return a.success?this.trackSuccessfulOperation("validateWsdl"):this.trackFailedOperation(new Error(a.error.message)),a}catch(a){return this.handleError(a)}}async testSoapOperation(u,a,t){this.ensureInitialized();try{let r=await this.coordinator.testSoapOperation(u,a,t);return r.success?this.trackSuccessfulOperation("testSoapOperation"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testMessageFlow(u,a){this.ensureInitialized();try{let t=await this.coordinator.testMessageFlow(u,a);return t.success?this.trackSuccessfulOperation("testMessageFlow"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async testDlqHandling(u,a){this.ensureInitialized();try{let t=await this.coordinator.testDlqHandling(u,a);return t.success?this.trackSuccessfulOperation("testDlqHandling"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async testBapiCall(u,a){this.ensureInitialized();try{let t=await this.coordinator.testBapiCall(u,a);return t.success?this.trackSuccessfulOperation("testBapiCall"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async validateIdoc(u,a){this.ensureInitialized();try{let t=await this.coordinator.validateIdoc(u,a);return t.success?this.trackSuccessfulOperation("validateIdoc"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async validateODataMetadata(u){this.ensureInitialized();try{let a=await this.coordinator.validateODataMetadata(u);return a.success?this.trackSuccessfulOperation("validateODataMetadata"):this.trackFailedOperation(new Error(a.error.message)),a}catch(a){return this.handleError(a)}}async testODataEntitySet(u,a){this.ensureInitialized();try{let t=await this.coordinator.testODataEntitySet(u,a);return t.success?this.trackSuccessfulOperation("testODataEntitySet"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async validateMessageFlow(u,a){this.ensureInitialized();try{let t=await this.coordinator.validateMessageFlow(u,a);return t.success?this.trackSuccessfulOperation("validateMessageFlow"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async validateTransformation(u,a,t){this.ensureInitialized();try{let r=await this.coordinator.validateTransformation(u,a,t);return r.success?this.trackSuccessfulOperation("validateTransformation"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async analyzeSod(u,a){this.ensureInitialized();try{let t=await this.coordinator.analyzeSod(u,a);return t.success?this.trackSuccessfulOperation("analyzeSod"):this.trackFailedOperation(new Error(t.error.message)),t}catch(t){return this.handleError(t)}}async handleContractVerified(u){let a=u.payload;(a.contractType==="soap"||a.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-verified:${a.contractId}`,{contractId:a.contractId,type:a.contractType,passed:a.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleQualityGate(u){let a=u.payload;a.checks.find(r=>r.name==="enterprise-integration")||await this.memory.set(`enterprise-integration:quality-gate-warning:${a.gateId}`,{warning:"Enterprise integration testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(u){let a=u.payload;(a.targetService?.includes("middleware")||a.targetService?.includes("esb")||a.targetService?.includes("broker")||a.targetService?.includes("mq"))&&await this.memory.set(`enterprise-integration:fault-correlation:${a.faultId||Date.now()}`,{targetService:a.targetService,faultType:a.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(u){let a=g(u),t=this.getHealth();return this.updateHealth({errors:[...t.errors.slice(-9),a.message],status:t.errors.length>=5?"degraded":t.status}),{success:!1,error:a}}trackSuccessfulOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,total:a.agents.total+1,idle:a.agents.idle+1},lastActivity:new Date})}trackFailedOperation(u){let a=this.getHealth();this.updateHealth({agents:{...a.agents,failed:a.agents.failed+1},errors:[...a.errors.slice(-9),u.message]})}};function a3(s,e,u,a){return new Zl(s,e,u,a)}var t3={"test-generation":(s,e,u)=>Cs(s,e,u),"test-execution":(s,e)=>Qc(s,e),"coverage-analysis":(s,e)=>Ws(s,e),"quality-assessment":(s,e,u)=>el(s,e,u),"defect-intelligence":(s,e,u)=>P1(s,e,u),"requirements-validation":(s,e,u)=>I1(s,e,u),"code-intelligence":(s,e,u)=>pl(s,e,u),"security-compliance":(s,e,u)=>jl(s,e,u),"contract-testing":(s,e,u)=>bE(s,e,u),"visual-accessibility":(s,e,u)=>HE(s,e,u),"chaos-resilience":(s,e,u)=>OE(s,e,u),"learning-optimization":(s,e,u)=>XE(s,e,u),"enterprise-integration":(s,e,u)=>a3(s,e,u),coordination:(s,e,u)=>u3(s,e,u)},$2u={maxConcurrentAgents:J0.MAX_CONCURRENT_AGENTS,memoryBackend:"hybrid",hnswEnabled:!0,lazyLoading:!0,enabledDomains:[...Fu],dataDir:void 0},Ql=class{_eventBus;_coordinator;_plugins;_memory;_config;_startTime;_initialized=!1;_loopTracker;constructor(e={}){this._config={...$2u,...e},this._startTime=new Date,this._memory=new Qi,this._eventBus=new xt,this._coordinator=new ft(this._config.maxConcurrentAgents),this._plugins=new aa(this._eventBus,this._memory,this._config.lazyLoading),this._loopTracker=new vt}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 e=u4(),u=this._config.dataDir||o0.join(e,".agentic-qe");if(qi.existsSync(u)||qi.mkdirSync(u,{recursive:!0}),this._config.memoryBackend==="memory"){let t=o0.join(Ji("os").tmpdir(),`aqe-test-${Date.now()}-${W2u().slice(0,12)}.db`);await a4({dbPath:t})}else this._memory=new e4({sqlite:{path:o0.join(u,"memory.db"),walMode:!0,poolSize:3,busyTimeout:Xl.BUSY_TIMEOUT_MS},enableFallback:!0,defaultNamespace:"qe-kernel"}),this._plugins=new aa(this._eventBus,this._memory,this._config.lazyLoading);for(let t of this._config.enabledDomains){let r=t3[t];r&&this._plugins.registerFactory(t,async(i,n)=>Promise.resolve(r(i,n,this._coordinator)))}await this._memory.initialize();let a=new bt({agentId:"qe-kernel"});this._eventBus.registerMiddleware(a);try{let t=o0.join(u,"plugins"),r=new t4({cacheDir:t}),n=new r4({cache:r}).resolveLoadOrder();for(let o of n.ordered){let l=o.manifest,c=r.get(l.name,l.version);if(!c)continue;let E=o0.join(c.path,l.entryPoint);for(let d of l.domains){let D=d;if(t3[D])continue;this._plugins.registerFactory(D,async(C,y)=>{let x=await import(E),b=x.default??x.createPlugin;if(typeof b!="function")throw new Error(`Plugin "${l.name}" entry point must export a default function or "createPlugin" function`);return b(C,y,this._coordinator)})}}}catch{}this._config.lazyLoading||await this._plugins.loadAll();try{let{isAgentMemoryBranchingEnabled:t,isRVFPatternStoreEnabled:r}=await import("./feature-flags-V34UZPHG.js");if(t()&&r()){let{getSharedRvfAdapter:i}=await import("./shared-rvf-adapter-6JWYF7WV.js"),{AgentMemoryBranch:n}=await import("./agent-memory-branch-V6EXWWMY.js"),o=i(u,384);if(o){let l=new n(o,{branchDir:o0.join(u,"branches")});this._coordinator.setMemoryBranch(l)}}}catch{}try{let{getRvfMigrationStage:t}=await import("./feature-flags-V34UZPHG.js"),r=t();if(r>=2){let{RvfMigrationCoordinator:i}=await import("./rvf-migration-coordinator-MCJDNKXG.js");await i.getInstance({stage:r}).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(e){return this._plugins.getPlugin(e)?.getAPI()}async getDomainAPIAsync(e){let u=this._plugins.getPlugin(e);if(!u&&this._config.lazyLoading&&this._config.enabledDomains.includes(e))try{u=await this._plugins.load(e)}catch(a){console.error(`[QEKernel] Failed to lazy load domain ${e}:`,a);return}return u?.getAPI()}async ensureDomainLoaded(e){if(this._plugins.isLoaded(e))return!0;if(!this._config.enabledDomains.includes(e))return console.warn(`[QEKernel] Domain ${e} is not enabled`),!1;try{return await this._plugins.load(e),!0}catch(u){return console.error(`[QEKernel] Failed to load domain ${e}:`,u),!1}}isDomainLoaded(e){return this._plugins.isLoaded(e)}getLoadedDomains(){return this._plugins.getLoaded()}getPendingDomains(){let e=new Set(this._plugins.getLoaded());return this._config.enabledDomains.filter(u=>!e.has(u))}getHealth(){let e=this._coordinator.listAgents(),u={};for(let l of this._plugins.getLoaded()){let c=this._plugins.getPlugin(l);c&&(u[l]=c.getHealth())}for(let l of Fu)if(!u[l]){let c=this._config.enabledDomains.includes(l),E=this._config.lazyLoading&&c;u[l]={status:E?"healthy":c?"degraded":"healthy",agents:{total:0,active:0,idle:0,failed:0},errors:E?[]:c?["Domain not yet loaded"]:[],loaded:!1,lazyLoadable:E}}let a=this._coordinator.getActiveCount(),t=0,r=Number.MAX_SAFE_INTEGER;if(this._memory instanceof Qi){let l=this._memory.getStats();t=l.entries+l.vectors}else t=0;let n=this._eventBus.getMiddlewares().find(l=>l.name==="semantic-anti-drift"),o=n?n.getStats():void 0;return{status:this.determineOverallStatus(u),uptime:Date.now()-this._startTime.getTime(),domains:u,agents:{total:e.length,active:a,maxAllowed:this._config.maxConcurrentAgents},memory:{used:t,available:r},...o?{antiDrift:o}:{}}}determineOverallStatus(e){let u=Object.values(e).map(a=>a.status);return u.some(a=>a==="unhealthy")?"unhealthy":u.some(a=>a==="degraded")?"degraded":"healthy"}getConfig(){return{...this._config}}checkToolCall(e,u,a){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return this._loopTracker.trackCall(e,u,a);let t=this._loopTracker.trackCall(e,u,a);if(t.action==="warn"){let r={id:`loop-warn-${e}-${Date.now()}`,type:on.LOOP_WARNING,timestamp:new Date,source:"coordination",correlationId:e,payload:{agentId:e,toolName:u,callCount:t.callCount,signature:t.signature}};this._eventBus.publish(r)}else if(t.action==="steer"){let r={id:`loop-detected-${e}-${Date.now()}`,type:on.LOOP_DETECTED,timestamp:new Date,source:"coordination",correlationId:e,payload:{agentId:e,toolName:u,callCount:t.callCount,signature:t.signature,steeringMessage:t.steeringMessage}};this._eventBus.publish(r)}return t}get loopTracker(){return this._loopTracker}};function dre(s){return new Ql(s)}export{Ie as a,ve as b,f0 as c,b0 as d,Ue as e,Dl as f,yu as g,Ju as h,Xe as i,Al as j,si as k,K0 as l,j0 as m,Ni as n,V0 as o,_0 as p,a0 as q,t0 as r,r0 as s,Mu as t,Ru as u,Ql as v,dre as w};