agentic-qe 3.9.19 → 3.9.21

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 (307) hide show
  1. package/.claude/skills/skills-manifest.json +1 -1
  2. package/CHANGELOG.md +52 -0
  3. package/README.md +39 -0
  4. package/assets/skills/skills-manifest.json +1 -1
  5. package/dist/adapters/claude-flow/trajectory-bridge.d.ts +12 -1
  6. package/dist/adapters/claude-flow/trajectory-bridge.js +33 -31
  7. package/dist/cli/bundle.js +5 -5
  8. package/dist/cli/chunks/adapter-WOEZOCHJ.js +2 -0
  9. package/dist/cli/chunks/{agent-booster-wasm-HVBKHNIS.js → agent-booster-wasm-55SQPP6T.js} +2 -2
  10. package/dist/cli/chunks/{agent-handler-XNBDYRSJ.js → agent-handler-Q2UXL73Y.js} +2 -2
  11. package/dist/cli/chunks/{agent-memory-branch-YCVTQEMJ.js → agent-memory-branch-56GIYNGH.js} +2 -2
  12. package/dist/cli/chunks/aqe-learning-engine-5AHKLABJ.js +2 -0
  13. package/dist/cli/chunks/{audit-6C2PE7OY.js → audit-2JQ3URVN.js} +2 -2
  14. package/dist/cli/chunks/base-RNCRGTZJ.js +2 -0
  15. package/dist/cli/chunks/{better-sqlite3-HZPCHUQU.js → better-sqlite3-XGA7Z5YL.js} +2 -2
  16. package/dist/cli/chunks/{brain-handler-OV75Q2NM.js → brain-handler-TOOZFEK5.js} +3 -3
  17. package/dist/cli/chunks/{branch-enumerator-QW6D42HJ.js → branch-enumerator-2BLPN73D.js} +2 -2
  18. package/dist/cli/chunks/{browser-5BA7Q7OR.js → browser-FSVNN36N.js} +2 -2
  19. package/dist/cli/chunks/browser-workflow-MXHA63OC.js +2 -0
  20. package/dist/cli/chunks/{chunk-K554X3T4.js → chunk-2AEWOQWU.js} +2 -2
  21. package/dist/cli/chunks/{chunk-GVDLCJC5.js → chunk-34BTSZ5D.js} +1 -1
  22. package/dist/cli/chunks/{chunk-CYLQTVIA.js → chunk-3Y7OZ2PC.js} +2 -2
  23. package/dist/cli/chunks/{chunk-HVNW3TZS.js → chunk-44BAZASI.js} +1 -1
  24. package/dist/cli/chunks/{chunk-O5ZP3CBF.js → chunk-4O7YJIOS.js} +2 -2
  25. package/dist/cli/chunks/{chunk-HJ7CRPZY.js → chunk-4XZPDEK5.js} +1 -1
  26. package/dist/cli/chunks/{chunk-FL2DMHOQ.js → chunk-4Z4C7BXV.js} +1 -1
  27. package/dist/cli/chunks/{chunk-WULMXLNN.js → chunk-4ZUXTOUG.js} +1 -1
  28. package/dist/cli/chunks/{chunk-JYHZK44T.js → chunk-56DGV2Q3.js} +1 -1
  29. package/dist/cli/chunks/{chunk-SKNHAGYP.js → chunk-5EYQP3V3.js} +2 -2
  30. package/dist/cli/chunks/{chunk-TXCOK5DC.js → chunk-5FNEOJSD.js} +2 -2
  31. package/dist/cli/chunks/{chunk-FT3MAIRW.js → chunk-5PZG4WUA.js} +3 -3
  32. package/dist/cli/chunks/{chunk-WZUQT2BE.js → chunk-63PHZGO2.js} +2 -2
  33. package/dist/cli/chunks/chunk-65U55JIH.js +12 -0
  34. package/dist/cli/chunks/{chunk-MTHO6A3V.js → chunk-6MGACOLN.js} +1 -1
  35. package/dist/cli/chunks/{chunk-AOASQYOO.js → chunk-6OYRNNP2.js} +1 -1
  36. package/dist/cli/chunks/{chunk-XP4T7CZY.js → chunk-7P4IZQVQ.js} +2 -2
  37. package/dist/cli/chunks/{chunk-PUUTYV32.js → chunk-ACOEV3YB.js} +2 -2
  38. package/dist/cli/chunks/{chunk-UIASVDYG.js → chunk-ADC73GLJ.js} +2 -2
  39. package/dist/cli/chunks/{chunk-NMYZSZHW.js → chunk-AEQNCDYD.js} +2 -2
  40. package/dist/cli/chunks/chunk-AMOCYHP3.js +2 -0
  41. package/dist/cli/chunks/{chunk-KTDGHN2J.js → chunk-AT25VXEO.js} +1 -1
  42. package/dist/cli/chunks/{chunk-MN4366PQ.js → chunk-C4CZXAOE.js} +2 -2
  43. package/dist/cli/chunks/{chunk-GYDE5TCN.js → chunk-CJKR47YY.js} +1 -1
  44. package/dist/cli/chunks/{chunk-VXUIIZNG.js → chunk-D24HN6BG.js} +1 -1
  45. package/dist/cli/chunks/{chunk-U2WMCNNR.js → chunk-DBW745QA.js} +2 -2
  46. package/dist/cli/chunks/{chunk-BOUCIIUI.js → chunk-DQI5ZR34.js} +1 -1
  47. package/dist/cli/chunks/{chunk-SKDDAPBV.js → chunk-E2XIPBJ7.js} +1 -1
  48. package/dist/cli/chunks/{chunk-2WJLEZKP.js → chunk-E55MYZGP.js} +2 -2
  49. package/dist/cli/chunks/{chunk-44SPMVML.js → chunk-E5TGH4V3.js} +2 -2
  50. package/dist/cli/chunks/{chunk-OEQCZBBM.js → chunk-E7J32PW2.js} +2 -2
  51. package/dist/cli/chunks/{chunk-VSI45JCP.js → chunk-ETEV7IZI.js} +1 -1
  52. package/dist/cli/chunks/{chunk-TCUIYIZ4.js → chunk-EVWNZEYV.js} +1 -1
  53. package/dist/cli/chunks/{chunk-AEET2WOI.js → chunk-F4VJ4PPI.js} +59 -47
  54. package/dist/cli/chunks/{chunk-GYESQBDU.js → chunk-FBCLQTXO.js} +2 -2
  55. package/dist/cli/chunks/{chunk-IG2RCBHJ.js → chunk-FZ2SYLSK.js} +1 -1
  56. package/dist/cli/chunks/{chunk-XXHJKAE6.js → chunk-G276EI3G.js} +2 -2
  57. package/dist/cli/chunks/{chunk-ALYUJEYA.js → chunk-G7ZYDJZ3.js} +2 -2
  58. package/dist/cli/chunks/{chunk-I3JRRFVT.js → chunk-GB6ATLR3.js} +2 -2
  59. package/dist/cli/chunks/{chunk-MIQAFOFO.js → chunk-GDZ6XQRI.js} +1 -1
  60. package/dist/cli/chunks/{chunk-QOK4TIE4.js → chunk-GJGFPXWG.js} +2 -2
  61. package/dist/cli/chunks/{chunk-H4QM37XS.js → chunk-GLQ6LLKC.js} +1 -1
  62. package/dist/cli/chunks/{chunk-BGTYOZRK.js → chunk-GR4RXQXV.js} +2 -2
  63. package/dist/cli/chunks/{chunk-C5YFCM2H.js → chunk-HC4VOQZJ.js} +2 -2
  64. package/dist/cli/chunks/{chunk-NBBIA3QA.js → chunk-HIEP3L7H.js} +2 -2
  65. package/dist/cli/chunks/{chunk-DZS7XQ2Z.js → chunk-HJCJWPN5.js} +2 -2
  66. package/dist/cli/chunks/{chunk-BFBR2ZZJ.js → chunk-HMMJ6ZI6.js} +2 -2
  67. package/dist/cli/chunks/{chunk-XKD6AFY5.js → chunk-HRHKLRBB.js} +1 -1
  68. package/dist/cli/chunks/{chunk-AG7J7DTM.js → chunk-I3HLZASP.js} +2 -2
  69. package/dist/cli/chunks/{chunk-3HQ4AZDH.js → chunk-ICPQR533.js} +2 -2
  70. package/dist/cli/chunks/{chunk-AZKVGH5I.js → chunk-IM7X6BDZ.js} +2 -2
  71. package/dist/cli/chunks/{chunk-XQZ63XSL.js → chunk-IS6IES7Q.js} +1 -1
  72. package/dist/cli/chunks/{chunk-Y3GX66VZ.js → chunk-ISNDQOXC.js} +2 -2
  73. package/dist/cli/chunks/{chunk-2SSDY6OE.js → chunk-J3GG3Q4X.js} +2 -2
  74. package/dist/cli/chunks/{chunk-2XATUQIG.js → chunk-KDOA7YHW.js} +2 -2
  75. package/dist/cli/chunks/{chunk-U257SS7D.js → chunk-KENZAFI2.js} +2 -2
  76. package/dist/cli/chunks/{chunk-5LXWEAEJ.js → chunk-KID7PTBZ.js} +2 -2
  77. package/dist/cli/chunks/{chunk-M6EP724N.js → chunk-KRXJ7LFP.js} +1 -1
  78. package/dist/cli/chunks/{chunk-IPLQPBJA.js → chunk-KWPPF7O4.js} +2 -2
  79. package/dist/cli/chunks/{chunk-XF32XZMY.js → chunk-KYPN6G7T.js} +2 -2
  80. package/dist/cli/chunks/{chunk-B65GTWF3.js → chunk-LHXIAPKR.js} +2 -2
  81. package/dist/cli/chunks/chunk-LP52AQE2.js +2 -0
  82. package/dist/cli/chunks/{chunk-5X2AUPK2.js → chunk-LYZUB3NP.js} +1 -1
  83. package/dist/cli/chunks/{chunk-3X3QQZ7Q.js → chunk-MJGMH7TW.js} +2 -2
  84. package/dist/cli/chunks/{chunk-5KGFDNYI.js → chunk-MYZ43VKA.js} +2 -2
  85. package/dist/cli/chunks/{chunk-7WMHLBNZ.js → chunk-ND2TFQF5.js} +1 -1
  86. package/dist/cli/chunks/{chunk-R5IL3XD5.js → chunk-NGT3VL66.js} +24 -16
  87. package/dist/cli/chunks/{chunk-YXLQJ226.js → chunk-NJICCYCB.js} +2 -2
  88. package/dist/cli/chunks/{chunk-DAPBSAVT.js → chunk-NKOGDRZE.js} +2 -2
  89. package/dist/cli/chunks/{chunk-PS72GF4R.js → chunk-NS2ZWXUK.js} +3 -3
  90. package/dist/cli/chunks/{chunk-W3IO4FQ5.js → chunk-NV6AUEIH.js} +2 -2
  91. package/dist/cli/chunks/{chunk-3546SG2L.js → chunk-OEB3V633.js} +2 -2
  92. package/dist/cli/chunks/chunk-OHR5ILR3.js +2 -0
  93. package/dist/cli/chunks/{chunk-N2PLNYEV.js → chunk-OK5JHHXK.js} +1 -1
  94. package/dist/cli/chunks/{chunk-VRGXYOIN.js → chunk-OXXCWRFU.js} +1 -1
  95. package/dist/cli/chunks/{chunk-GJ5FON37.js → chunk-P4Q5TMDH.js} +2 -2
  96. package/dist/cli/chunks/{chunk-7IV2RK5M.js → chunk-PAXSPZ3F.js} +2 -2
  97. package/dist/cli/chunks/{chunk-5R2DUR3A.js → chunk-PEOTZFNZ.js} +2 -2
  98. package/dist/cli/chunks/{chunk-VHG67L7O.js → chunk-PGHTRQK6.js} +2 -2
  99. package/dist/cli/chunks/{chunk-HQFREZRX.js → chunk-QERANESS.js} +2 -2
  100. package/dist/cli/chunks/{chunk-NPSWRGNT.js → chunk-QPSPIESU.js} +2 -2
  101. package/dist/cli/chunks/{chunk-V7ZPTEP7.js → chunk-QREO5LNR.js} +1 -1
  102. package/dist/cli/chunks/{chunk-J7F65KKG.js → chunk-QSLXOYPR.js} +6 -6
  103. package/dist/cli/chunks/{chunk-VWWLJBRA.js → chunk-QU3VFWZZ.js} +14 -14
  104. package/dist/cli/chunks/{chunk-KU7OXAFY.js → chunk-RDUIN7LO.js} +1 -1
  105. package/dist/cli/chunks/{chunk-O6UMETOH.js → chunk-RHAUASC6.js} +2 -2
  106. package/dist/cli/chunks/{chunk-P6EYD4V3.js → chunk-RIVX6YLS.js} +2 -2
  107. package/dist/cli/chunks/{chunk-FPVXXQVX.js → chunk-ROC2SSV3.js} +3 -3
  108. package/dist/cli/chunks/{chunk-B2EHSFUW.js → chunk-S3TU7B7D.js} +2 -2
  109. package/dist/cli/chunks/{chunk-LTE3CDOY.js → chunk-S5RNBBJ6.js} +2 -2
  110. package/dist/cli/chunks/{chunk-TMAIHTE3.js → chunk-S6FFUCVZ.js} +4 -4
  111. package/dist/cli/chunks/{chunk-GL742O2V.js → chunk-SIW4N4NE.js} +4 -4
  112. package/dist/cli/chunks/{chunk-37DTXQ6P.js → chunk-SMAC5IX4.js} +2 -2
  113. package/dist/cli/chunks/{chunk-5MGRZ4YD.js → chunk-SMBQERK7.js} +2 -2
  114. package/dist/cli/chunks/{chunk-G2V4GMPR.js → chunk-T5Z5LL5Y.js} +3 -3
  115. package/dist/cli/chunks/{chunk-NXO7CT5K.js → chunk-TCNJ5NGT.js} +2 -2
  116. package/dist/cli/chunks/{chunk-JCPJG2KU.js → chunk-TFAS5UND.js} +3 -3
  117. package/dist/cli/chunks/{chunk-SLDYG7LC.js → chunk-TMKJXKY2.js} +2 -2
  118. package/dist/cli/chunks/{chunk-D74RGYKI.js → chunk-TOE6DKE4.js} +1 -1
  119. package/dist/cli/chunks/{chunk-MMVSIESL.js → chunk-UOLIGPDW.js} +2 -2
  120. package/dist/cli/chunks/{chunk-SRKBR4DU.js → chunk-V5AVC4D4.js} +2 -2
  121. package/dist/cli/chunks/{chunk-RL5CBCBV.js → chunk-V6GJ3EMZ.js} +1 -1
  122. package/dist/cli/chunks/{chunk-2SIQ742L.js → chunk-VGAG5TG7.js} +1 -1
  123. package/dist/cli/chunks/{chunk-255CWHTF.js → chunk-VQLHHNOH.js} +2 -2
  124. package/dist/cli/chunks/{chunk-LDBHCOM3.js → chunk-VQXHHEPD.js} +2 -2
  125. package/dist/cli/chunks/{chunk-EZZJ5XD6.js → chunk-WI5HBS3C.js} +2 -2
  126. package/dist/cli/chunks/{chunk-HCSTXZYE.js → chunk-WL5IRCU4.js} +2 -2
  127. package/dist/cli/chunks/{chunk-FNVA7U7X.js → chunk-WY3H7VHF.js} +2 -2
  128. package/dist/cli/chunks/{chunk-FJJLNCSL.js → chunk-XEMVYJ2Z.js} +3 -3
  129. package/dist/cli/chunks/{chunk-EW5TQQBR.js → chunk-Y36AJ462.js} +2 -2
  130. package/dist/cli/chunks/{chunk-VLQYU7ZQ.js → chunk-YH7BAX7S.js} +1 -1
  131. package/dist/cli/chunks/{chunk-BB3KUX6C.js → chunk-YS5WV3CJ.js} +1 -1
  132. package/dist/cli/chunks/{chunk-6BRUQTC7.js → chunk-YVG4D6P3.js} +1 -1
  133. package/dist/cli/chunks/{chunk-JLX35EPX.js → chunk-YVPPR33H.js} +2 -2
  134. package/dist/cli/chunks/{chunk-IV74GAZN.js → chunk-ZUTYZIWQ.js} +2 -2
  135. package/dist/cli/chunks/{ci-FTZE4PD3.js → ci-GU2HBK5E.js} +2 -2
  136. package/dist/cli/chunks/{ci-output-C3ORCIHU.js → ci-output-FGZTTY3R.js} +2 -2
  137. package/dist/cli/chunks/{circuit-breaker-GS5OTOJZ.js → circuit-breaker-6UNLOLMW.js} +2 -2
  138. package/dist/cli/chunks/{claude-flow-setup-RWOFP5L2.js → claude-flow-setup-SCOCIDBC.js} +2 -2
  139. package/dist/cli/chunks/client-XU3ZUFMH.js +2 -0
  140. package/dist/cli/chunks/{cline-installer-D7RGRAUH.js → cline-installer-G6PQERGI.js} +2 -2
  141. package/dist/cli/chunks/{code-HBDMMYHY.js → code-RNKTYBI4.js} +2 -2
  142. package/dist/cli/chunks/{code-index-extractor-B2KUPAEH.js → code-index-extractor-A6KAUQOU.js} +2 -2
  143. package/dist/cli/chunks/{codex-installer-MPXV4AOD.js → codex-installer-ABWDMKEX.js} +2 -2
  144. package/dist/cli/chunks/{completions-QJS6QOZQ.js → completions-TB4E6O46.js} +2 -2
  145. package/dist/cli/chunks/{complexity-analyzer-YQQXWZIL.js → complexity-analyzer-XS37O7OR.js} +2 -2
  146. package/dist/cli/chunks/{continuedev-installer-Z6PBKYMB.js → continuedev-installer-WDY6O2SR.js} +2 -2
  147. package/dist/cli/chunks/{copilot-installer-RWVD44CV.js → copilot-installer-SDJ3GYLU.js} +2 -2
  148. package/dist/cli/chunks/{cost-tracker-DFPBFYWL.js → cost-tracker-MWEXRK7F.js} +2 -2
  149. package/dist/cli/chunks/{coverage-DYST26FK.js → coverage-Y3KDB56G.js} +3 -3
  150. package/dist/cli/chunks/cross-domain-router-KKYQWQE7.js +2 -0
  151. package/dist/cli/chunks/{cursor-installer-LL6UWKTZ.js → cursor-installer-4U7XENLX.js} +2 -2
  152. package/dist/cli/chunks/{daemon-6PIHFZNR.js → daemon-D6R3BPBJ.js} +3 -3
  153. package/dist/cli/chunks/{dag-attention-scheduler-WS3HJW4F.js → dag-attention-scheduler-EMVUX6ES.js} +2 -2
  154. package/dist/cli/chunks/{detect-J4OITSUD.js → detect-QIJPCTZO.js} +2 -2
  155. package/dist/cli/chunks/{dist-node-QSLD5K6K.js → dist-node-4ZYBZKOB.js} +2 -2
  156. package/dist/cli/chunks/{domain-handler-BD53QZ4Q.js → domain-handler-X6CTXJQF.js} +2 -2
  157. package/dist/cli/chunks/{domain-transfer-VZBWINQL.js → domain-transfer-HK4ER37F.js} +2 -2
  158. package/dist/cli/chunks/dream-FBYASIID.js +2 -0
  159. package/dist/cli/chunks/{embed-and-insert-pattern-5UAFXNDX.js → embed-and-insert-pattern-XKTD5DQ3.js} +2 -2
  160. package/dist/cli/chunks/{eval-GBKU6VTD.js → eval-WEEB3CHY.js} +2 -2
  161. package/dist/cli/chunks/{fast-paths-MYZ6GITZ.js → fast-paths-M2ENEKQX.js} +2 -2
  162. package/dist/cli/chunks/{feature-flags-6ALWBTHS.js → feature-flags-3WIZC67K.js} +2 -2
  163. package/dist/cli/chunks/{feature-flags-2WVV66AO.js → feature-flags-CZQXGFGX.js} +2 -2
  164. package/dist/cli/chunks/{file-discovery-FOYCPGD6.js → file-discovery-ERTPM3C4.js} +2 -2
  165. package/dist/cli/chunks/{fleet-JROEDHAT.js → fleet-WBEPTBQR.js} +3 -3
  166. package/dist/cli/chunks/{gnn-wrapper-KAXTFFEE.js → gnn-wrapper-GVRS33BK.js} +2 -2
  167. package/dist/cli/chunks/{heartbeat-handler-PG24CBMQ.js → heartbeat-handler-JQ6NSC6T.js} +4 -4
  168. package/dist/cli/chunks/{heartbeat-scheduler-LSS3RD6E.js → heartbeat-scheduler-7XHIE6IV.js} +2 -2
  169. package/dist/cli/chunks/hnsw-adapter-L7QOLNKP.js +2 -0
  170. package/dist/cli/chunks/hnsw-index-O2YO7WVU.js +2 -0
  171. package/dist/cli/chunks/{hnsw-legacy-bridge-HYH4AJAO.js → hnsw-legacy-bridge-TYO6GZ6Z.js} +2 -2
  172. package/dist/cli/chunks/hnswlib-node-UHEP6UZZ.js +2 -0
  173. package/dist/cli/chunks/{hooks-RDZSAFQG.js → hooks-2GU7LGNL.js} +58 -47
  174. package/dist/cli/chunks/{hybrid-router-HNPS6EFL.js → hybrid-router-Z5V4E5SJ.js} +2 -2
  175. package/dist/cli/chunks/{hypergraph-engine-JUFXRXCC.js → hypergraph-engine-F435AM7S.js} +2 -2
  176. package/dist/cli/chunks/{hypergraph-handler-YFRF53TF.js → hypergraph-handler-DQMYDUQY.js} +3 -3
  177. package/dist/cli/chunks/impact-analyzer-37TDXM6V.js +2 -0
  178. package/dist/cli/chunks/{init-handler-P4W5F57S.js → init-handler-Y4NPRT2W.js} +6 -6
  179. package/dist/cli/chunks/init-wizard-ONNAHU4H.js +2 -0
  180. package/dist/cli/chunks/kernel-3S7RJ7PT.js +2 -0
  181. package/dist/cli/chunks/{kilocode-installer-5VWY4DMH.js → kilocode-installer-EUTWNH4I.js} +2 -2
  182. package/dist/cli/chunks/{kiro-installer-PZC3BQII.js → kiro-installer-I3ECJ37F.js} +2 -2
  183. package/dist/cli/chunks/knowledge-graph-GNJMYFT2.js +2 -0
  184. package/dist/cli/chunks/{learning-4OH4ZG25.js → learning-5FW7N6DA.js} +3 -3
  185. package/dist/cli/chunks/{llm-router-LZBR6SZQ.js → llm-router-ZRYFNNPU.js} +4 -4
  186. package/dist/cli/chunks/{load-SPWP6VB3.js → load-7BF33NMJ.js} +2 -2
  187. package/dist/cli/chunks/load-test-ZHTSLJMB.js +2 -0
  188. package/dist/cli/chunks/{mcp-QYPQMM7L.js → mcp-7K6P7FMG.js} +2 -2
  189. package/dist/cli/chunks/{memory-54ILJMWQ.js → memory-O2DCN3GS.js} +5 -5
  190. package/dist/cli/chunks/memory-backend-LN6NWT4F.js +2 -0
  191. package/dist/cli/chunks/{memory-handlers-YK7H5UCX.js → memory-handlers-WA63DMQ4.js} +2 -2
  192. package/dist/cli/chunks/{multi-model-executor-XAOAVPPI.js → multi-model-executor-SJXBFOK5.js} +2 -2
  193. package/dist/cli/chunks/{opencode-installer-CNS4XMUF.js → opencode-installer-PE7ZV6SV.js} +2 -2
  194. package/dist/cli/chunks/{orchestrator-SSEMSKUI.js → orchestrator-N4GT5IGY.js} +5 -5
  195. package/dist/cli/chunks/{pipeline-DS3AENTB.js → pipeline-DUTGGNO6.js} +2 -2
  196. package/dist/cli/chunks/{platform-BL6LH5NF.js → platform-EGUD7X2R.js} +2 -2
  197. package/dist/cli/chunks/{plugin-FNXPEQ2C.js → plugin-6ZS3HK43.js} +2 -2
  198. package/dist/cli/chunks/{prime-radiant-advanced-wasm-E6S6BGNA.js → prime-radiant-advanced-wasm-B5S4RUJS.js} +2 -2
  199. package/dist/cli/chunks/protocol-executor-ED36SYE4.js +2 -0
  200. package/dist/cli/chunks/{protocol-handler-D4WIUU3W.js → protocol-handler-Z3QDY7O6.js} +2 -2
  201. package/dist/cli/chunks/{prove-OLB3PKW6.js → prove-TQHP2XVD.js} +2 -2
  202. package/dist/cli/chunks/{provider-manager-GKTQ75DT.js → provider-manager-2JFXKYMZ.js} +3 -3
  203. package/dist/cli/chunks/qe-reasoning-bank-AC5ZWDAZ.js +2 -0
  204. package/dist/cli/chunks/{quality-ZYJVYTUL.js → quality-NXDHVPAS.js} +2 -2
  205. package/dist/cli/chunks/queen-coordinator-IZ4RQGKV.js +2 -0
  206. package/dist/cli/chunks/{real-embeddings-SKJRHLCS.js → real-embeddings-P2LYDBVF.js} +2 -2
  207. package/dist/cli/chunks/{roocode-installer-WZGKOLWE.js → roocode-installer-YSRXO4W4.js} +2 -2
  208. package/dist/cli/chunks/router-DZVPCD7E.js +2 -0
  209. package/dist/cli/chunks/routing-feedback-3LUE56G4.js +2 -0
  210. package/dist/cli/chunks/{routing-handler-4GIMINCI.js → routing-handler-HVDQQF34.js} +2 -2
  211. package/dist/cli/chunks/{ruvector-commands-YZONXZ2W.js → ruvector-commands-5NJ5FQ3E.js} +2 -2
  212. package/dist/cli/chunks/{rvf-dual-writer-WSS5GF54.js → rvf-dual-writer-GZ2HIIKX.js} +2 -2
  213. package/dist/cli/chunks/{rvf-migration-adapter-WS4HHVEU.js → rvf-migration-adapter-QKEYGJFL.js} +2 -2
  214. package/dist/cli/chunks/{rvf-migration-coordinator-6BY5GI47.js → rvf-migration-coordinator-5RBME46Y.js} +2 -2
  215. package/dist/cli/chunks/rvf-native-adapter-UTX4WYSI.js +2 -0
  216. package/dist/cli/chunks/safe-db-PEJN42TX.js +2 -0
  217. package/dist/cli/chunks/schedule-UULIQP2J.js +2 -0
  218. package/dist/cli/chunks/scheduler-T57XAXKF.js +2 -0
  219. package/dist/cli/chunks/{security-HCNOL2K3.js → security-KB4TOOFJ.js} +3 -3
  220. package/dist/cli/chunks/shared-rvf-adapter-UZVFV2RJ.js +2 -0
  221. package/dist/cli/chunks/{shared-rvf-dual-writer-QRNLSDS7.js → shared-rvf-dual-writer-UMDFMGVS.js} +2 -2
  222. package/dist/cli/chunks/sqlite-persistence-W7E26KF3.js +2 -0
  223. package/dist/cli/chunks/{status-handler-QXZ442MY.js → status-handler-T53CO6SX.js} +2 -2
  224. package/dist/cli/chunks/{structural-health-OFYZ3Z4A.js → structural-health-AVS2GE7S.js} +2 -2
  225. package/dist/cli/chunks/{sync-J4BG65NF.js → sync-Q3UHMELK.js} +2 -2
  226. package/dist/cli/chunks/{task-handler-UBSFCKK3.js → task-handler-UAJWNRMS.js} +2 -2
  227. package/dist/cli/chunks/task-handlers-HYSHMTJN.js +9 -0
  228. package/dist/cli/chunks/{test-WTNAHJHH.js → test-GMXM664Y.js} +4 -4
  229. package/dist/cli/chunks/{test-scheduling-QREBYRGW.js → test-scheduling-PYU4NLDU.js} +3 -3
  230. package/dist/cli/chunks/{token-bootstrap-HE5H77OL.js → token-bootstrap-5SIETJI6.js} +2 -2
  231. package/dist/cli/chunks/{token-usage-V5B6K3JL.js → token-usage-3H4KEKTT.js} +2 -2
  232. package/dist/cli/chunks/{hnswlib-node-WTTST5LC.js → transformers-ZFPUASV4.js} +2 -2
  233. package/dist/cli/chunks/{tree-sitter-wasm-parser-WP2SF2M5.js → tree-sitter-wasm-parser-X72YXRIP.js} +2 -2
  234. package/dist/cli/chunks/{types-7ZBTAO5Z.js → types-CB2HAVZ6.js} +2 -2
  235. package/dist/cli/chunks/unified-memory-SAIRUPOI.js +2 -0
  236. package/dist/cli/chunks/unified-memory-hnsw-NQALAER6.js +2 -0
  237. package/dist/cli/chunks/unified-persistence-XNGQFWFS.js +2 -0
  238. package/dist/cli/chunks/{upgrade-WIFAJDBG.js → upgrade-BWAZTJKE.js} +2 -2
  239. package/dist/cli/chunks/{validate-W63V36GA.js → validate-3OVVTWN6.js} +2 -2
  240. package/dist/cli/chunks/{validate-swarm-CK5BM3YY.js → validate-swarm-WJVG4OUQ.js} +2 -2
  241. package/dist/cli/chunks/{vibium-MJCCO36E.js → vibium-IIU2F5HC.js} +2 -2
  242. package/dist/cli/chunks/visual-security-CE37LMFR.js +2 -0
  243. package/dist/cli/chunks/{web-tree-sitter-ESERXLPK.js → web-tree-sitter-RO4TKGTV.js} +2 -2
  244. package/dist/cli/chunks/{windsurf-installer-FDWQ5BWI.js → windsurf-installer-7N5CZTJS.js} +2 -2
  245. package/dist/cli/chunks/{witness-chain-L5KSYE2S.js → witness-chain-B4CHDDS5.js} +2 -2
  246. package/dist/cli/chunks/witness-chain-L2KM336B.js +2 -0
  247. package/dist/cli/chunks/{workflow-34GYJDFW.js → workflow-FKJKW36Z.js} +4 -4
  248. package/dist/cli/chunks/workflow-orchestrator-BE5PCEBO.js +2 -0
  249. package/dist/cli/chunks/{wrappers-VGKEBQLW.js → wrappers-HU3SB4FT.js} +2 -2
  250. package/dist/cli/commands/hooks-handlers/hooks-dream-learning.js +54 -0
  251. package/dist/cli/commands/init.js +3 -1
  252. package/dist/coordination/consensus/providers/claude-provider.js +1 -1
  253. package/dist/domains/code-intelligence/coordinator.js +20 -0
  254. package/dist/integrations/agentic-flow/reasoning-bank/experience-replay.js +82 -0
  255. package/dist/integrations/embeddings/index/HNSWIndex.js +16 -6
  256. package/dist/integrations/ruvector/hypergraph-engine.d.ts +45 -0
  257. package/dist/integrations/ruvector/hypergraph-engine.js +102 -0
  258. package/dist/integrations/ruvector/shared-rvf-adapter.js +110 -2
  259. package/dist/learning/dream/dream-engine.js +8 -0
  260. package/dist/learning/pattern-store.js +38 -1
  261. package/dist/mcp/bundle.js +361 -344
  262. package/dist/mcp/entry.js +15 -0
  263. package/dist/mcp/handlers/core-handlers.js +2 -2
  264. package/dist/mcp/handlers/task-handlers.js +45 -0
  265. package/dist/mcp/handlers/trajectory-judge.d.ts +13 -0
  266. package/dist/mcp/handlers/trajectory-judge.js +100 -0
  267. package/dist/shared/llm/providers/claude.js +1 -1
  268. package/package.json +2 -2
  269. package/scripts/preinstall.cjs +54 -0
  270. package/dist/cli/chunks/adapter-5NI3IO42.js +0 -2
  271. package/dist/cli/chunks/aqe-learning-engine-JOUK5HMO.js +0 -2
  272. package/dist/cli/chunks/base-DCAB7AHK.js +0 -2
  273. package/dist/cli/chunks/browser-workflow-A4UV73SZ.js +0 -2
  274. package/dist/cli/chunks/chunk-2WM4NYM5.js +0 -2
  275. package/dist/cli/chunks/chunk-D2EHD2KF.js +0 -2
  276. package/dist/cli/chunks/chunk-VPDZTMMB.js +0 -24
  277. package/dist/cli/chunks/chunk-Z2E5DTKX.js +0 -2
  278. package/dist/cli/chunks/client-UTNF2C5K.js +0 -2
  279. package/dist/cli/chunks/cross-domain-router-FCM34JOR.js +0 -2
  280. package/dist/cli/chunks/dream-6KCS7EWS.js +0 -2
  281. package/dist/cli/chunks/hnsw-adapter-PG6O67CQ.js +0 -2
  282. package/dist/cli/chunks/hnsw-index-AHYZHLNZ.js +0 -2
  283. package/dist/cli/chunks/impact-analyzer-USAJVJY5.js +0 -2
  284. package/dist/cli/chunks/init-wizard-GL7LAZID.js +0 -2
  285. package/dist/cli/chunks/kernel-2YAIESTR.js +0 -2
  286. package/dist/cli/chunks/knowledge-graph-QSIYZRAG.js +0 -2
  287. package/dist/cli/chunks/load-test-UEHSHLVN.js +0 -2
  288. package/dist/cli/chunks/memory-backend-4NE4ADPG.js +0 -2
  289. package/dist/cli/chunks/protocol-executor-YI4HNXND.js +0 -2
  290. package/dist/cli/chunks/qe-reasoning-bank-ANBAXQXC.js +0 -2
  291. package/dist/cli/chunks/queen-coordinator-MYYUSWVX.js +0 -2
  292. package/dist/cli/chunks/router-RYCLZ7A4.js +0 -2
  293. package/dist/cli/chunks/routing-feedback-5KSRG2UI.js +0 -2
  294. package/dist/cli/chunks/rvf-native-adapter-NEIOLJRF.js +0 -2
  295. package/dist/cli/chunks/safe-db-3JQP4EPU.js +0 -2
  296. package/dist/cli/chunks/schedule-2QKCL64E.js +0 -2
  297. package/dist/cli/chunks/scheduler-FMOP45FC.js +0 -2
  298. package/dist/cli/chunks/shared-rvf-adapter-BMFIVWMJ.js +0 -2
  299. package/dist/cli/chunks/sqlite-persistence-I5RYLFOE.js +0 -2
  300. package/dist/cli/chunks/task-handlers-JFUT2FQ7.js +0 -2
  301. package/dist/cli/chunks/transformers-HIVMQP4O.js +0 -2
  302. package/dist/cli/chunks/unified-memory-2ETCY22B.js +0 -2
  303. package/dist/cli/chunks/unified-memory-hnsw-OALJW537.js +0 -2
  304. package/dist/cli/chunks/unified-persistence-SQMP7A3O.js +0 -2
  305. package/dist/cli/chunks/visual-security-JUJPF2QO.js +0 -2
  306. package/dist/cli/chunks/witness-chain-QJVKAAZT.js +0 -2
  307. package/dist/cli/chunks/workflow-orchestrator-WXB2RVVW.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.19");process.exit(0)}
2
- import{b as dl,c as ml}from"./chunk-2SIQ742L.js";import{a as pl}from"./chunk-FT3MAIRW.js";import{a as hl}from"./chunk-IG2RCBHJ.js";import{d as Tl}from"./chunk-FNVA7U7X.js";import{a as D,b as $r,c as Ee,d as Yi,e as Xi,f as Zi,g as tt,h as Ma,i as Ge}from"./chunk-MMVSIESL.js";import{a as fl,c as yl}from"./chunk-JYHZK44T.js";import{a as Fa,b as en,c as La,d as Nr,e as $a,f as Oa,g as Vr,h as Na,i as tn}from"./chunk-GJ5FON37.js";import{a as al}from"./chunk-M6EP724N.js";import{a as bl,b as wl,e as Cl}from"./chunk-G2V4GMPR.js";import{o as Sl,s as Rl}from"./chunk-GL742O2V.js";import{a as ll}from"./chunk-JLX35EPX.js";import{e as sn,l as an,q as Gm}from"./chunk-SRKBR4DU.js";import{a as gl,j as Ie}from"./chunk-37DTXQ6P.js";import{c as _r}from"./chunk-I3JRRFVT.js";import{g as vl}from"./chunk-NXO7CT5K.js";import{a as Br}from"./chunk-SLDYG7LC.js";import{a as x,b as Or,c as Ct,d as St,e as zr,f as De,g as Rt}from"./chunk-FPVXXQVX.js";import{c as nn}from"./chunk-R5IL3XD5.js";import{b as _a}from"./chunk-DAPBSAVT.js";import{f as qm}from"./chunk-OEQCZBBM.js";import{c as Ji,d as ul}from"./chunk-EZZJ5XD6.js";import{f as cl,o as Yt}from"./chunk-TXCOK5DC.js";import{a as M}from"./chunk-Z2E5DTKX.js";import{c as R}from"./chunk-5KGFDNYI.js";import{b as Va,d as rn}from"./chunk-U2WMCNNR.js";import{b as E,d as H}from"./chunk-5R2DUR3A.js";import{a as be,b as f,c as p}from"./chunk-N2PLNYEV.js";import{a as T,b as y,c as A}from"./chunk-5MGRZ4YD.js";import{i as v}from"./chunk-MIQAFOFO.js";import{a as Da}from"./chunk-2XATUQIG.js";import{a as L,b as le,d as se}from"./chunk-SKNHAGYP.js";import{a as ol,c as Lr,d as ka,e as Ia}from"./chunk-WZUQT2BE.js";import{a as et,b as vt,c as Qi,d as Ki}from"./chunk-IV74GAZN.js";import{S as qe,b as bt,n as wt}from"./chunk-W3IO4FQ5.js";import{a as Pa,c as Be,e as Kt,g as Jt}from"./chunk-WULMXLNN.js";var Il={};Kt(Il,{ALL_SUPPORTED_LANGUAGES:()=>Ym,ALL_TEST_FRAMEWORKS:()=>mn,DEFAULT_FRAMEWORKS:()=>Ga,FRAMEWORK_ALIASES:()=>Pl,FRAMEWORK_TO_LANGUAGE:()=>Jm,LANGUAGE_FILE_EXTENSIONS:()=>kl,getLanguageFromExtension:()=>rt,resolveFrameworkAlias:()=>pn});function pn(u){let t=u.toLowerCase().trim();return mn.includes(t)?t:Pl[t]}function rt(u){return kl[u.startsWith(".")?u:`.${u}`]}var Ga,Pl,Jm,kl,mn,Ym,Zt=Be(()=>{"use strict";Ga={typescript:"vitest",javascript:"jest",python:"pytest",java:"junit5",csharp:"xunit",go:"go-test",rust:"rust-test",swift:"swift-testing",kotlin:"kotlin-junit",dart:"flutter-test"},Pl={junit:"junit5","junit-5":"junit5","junit-4":"junit5",nunit:"nunit","x-unit":"xunit",xunit:"xunit",gotest:"go-test",go_test:"go-test",rusttest:"rust-test",rust_test:"rust-test",swift_testing:"swift-testing",swifttesting:"swift-testing",kotlin_junit:"kotlin-junit",kotlinjunit:"kotlin-junit",flutter_test:"flutter-test",fluttertest:"flutter-test",jest_rn:"jest-rn","jest-react-native":"jest-rn","react-native":"jest-rn"},Jm={jest:"javascript",vitest:"typescript",mocha:"javascript",pytest:"python","node-test":"javascript",junit5:"java",testng:"java",xunit:"csharp",nunit:"csharp","go-test":"go","rust-test":"rust","swift-testing":"swift",xctest:"swift","kotlin-junit":"kotlin","flutter-test":"dart","jest-rn":"javascript",playwright:"typescript",cypress:"javascript"},kl={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".java":"java",".cs":"csharp",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".dart":"dart"},mn=["jest","vitest","mocha","pytest","node-test","junit5","testng","xunit","nunit","go-test","rust-test","swift-testing","xctest","kotlin-junit","flutter-test","jest-rn","playwright","cypress"],Ym=["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]});function Ja(u,t={}){let{additionalContext:e,sourceCode:r,includeEvidence:i=!0,includeRemediation:n=!0,maxLength:s=8e3}=t,a=[];a.push(`# Security Finding Verification Request
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.21");process.exit(0)}
2
+ import{b as dl,c as ml}from"./chunk-VGAG5TG7.js";import{a as pl}from"./chunk-5PZG4WUA.js";import{a as hl}from"./chunk-FZ2SYLSK.js";import{d as Tl}from"./chunk-WY3H7VHF.js";import{a as D,b as $r,c as Ee,d as Yi,e as Xi,f as Zi,g as tt,h as Ma,i as Ge}from"./chunk-UOLIGPDW.js";import{a as fl,c as yl}from"./chunk-56DGV2Q3.js";import{a as Fa,b as en,c as La,d as Nr,e as $a,f as Oa,g as Vr,h as Na,i as tn}from"./chunk-P4Q5TMDH.js";import{a as al}from"./chunk-KRXJ7LFP.js";import{a as bl,b as wl,e as Cl}from"./chunk-T5Z5LL5Y.js";import{o as Sl,s as Rl}from"./chunk-SIW4N4NE.js";import{a as ll}from"./chunk-YVPPR33H.js";import{e as sn,l as an,q as Gm}from"./chunk-V5AVC4D4.js";import{a as gl,j as Ie}from"./chunk-SMAC5IX4.js";import{c as _r}from"./chunk-GB6ATLR3.js";import{g as vl}from"./chunk-TCNJ5NGT.js";import{a as Br}from"./chunk-TMKJXKY2.js";import{a as x,b as Or,c as Ct,d as St,e as zr,f as De,g as Rt}from"./chunk-ROC2SSV3.js";import{c as nn}from"./chunk-NGT3VL66.js";import{b as _a}from"./chunk-NKOGDRZE.js";import{f as qm}from"./chunk-E7J32PW2.js";import{c as Ji,d as ul}from"./chunk-WI5HBS3C.js";import{f as cl,o as Yt}from"./chunk-5FNEOJSD.js";import{a as M}from"./chunk-OHR5ILR3.js";import{c as R}from"./chunk-MYZ43VKA.js";import{b as Va,d as rn}from"./chunk-DBW745QA.js";import{b as E,d as H}from"./chunk-PEOTZFNZ.js";import{a as be,b as f,c as p}from"./chunk-OK5JHHXK.js";import{a as T,b as y,c as A}from"./chunk-SMBQERK7.js";import{i as v}from"./chunk-GDZ6XQRI.js";import{a as Da}from"./chunk-KDOA7YHW.js";import{a as L,b as le,d as se}from"./chunk-5EYQP3V3.js";import{a as ol,c as Lr,d as ka,e as Ia}from"./chunk-63PHZGO2.js";import{a as et,b as vt,c as Qi,d as Ki}from"./chunk-ZUTYZIWQ.js";import{S as qe,b as bt,n as wt}from"./chunk-NV6AUEIH.js";import{a as Pa,c as Be,e as Kt,g as Jt}from"./chunk-4ZUXTOUG.js";var Il={};Kt(Il,{ALL_SUPPORTED_LANGUAGES:()=>Ym,ALL_TEST_FRAMEWORKS:()=>mn,DEFAULT_FRAMEWORKS:()=>Ga,FRAMEWORK_ALIASES:()=>Pl,FRAMEWORK_TO_LANGUAGE:()=>Jm,LANGUAGE_FILE_EXTENSIONS:()=>kl,getLanguageFromExtension:()=>rt,resolveFrameworkAlias:()=>pn});function pn(u){let t=u.toLowerCase().trim();return mn.includes(t)?t:Pl[t]}function rt(u){return kl[u.startsWith(".")?u:`.${u}`]}var Ga,Pl,Jm,kl,mn,Ym,Zt=Be(()=>{"use strict";Ga={typescript:"vitest",javascript:"jest",python:"pytest",java:"junit5",csharp:"xunit",go:"go-test",rust:"rust-test",swift:"swift-testing",kotlin:"kotlin-junit",dart:"flutter-test"},Pl={junit:"junit5","junit-5":"junit5","junit-4":"junit5",nunit:"nunit","x-unit":"xunit",xunit:"xunit",gotest:"go-test",go_test:"go-test",rusttest:"rust-test",rust_test:"rust-test",swift_testing:"swift-testing",swifttesting:"swift-testing",kotlin_junit:"kotlin-junit",kotlinjunit:"kotlin-junit",flutter_test:"flutter-test",fluttertest:"flutter-test",jest_rn:"jest-rn","jest-react-native":"jest-rn","react-native":"jest-rn"},Jm={jest:"javascript",vitest:"typescript",mocha:"javascript",pytest:"python","node-test":"javascript",junit5:"java",testng:"java",xunit:"csharp",nunit:"csharp","go-test":"go","rust-test":"rust","swift-testing":"swift",xctest:"swift","kotlin-junit":"kotlin","flutter-test":"dart","jest-rn":"javascript",playwright:"typescript",cypress:"javascript"},kl={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".py":"python",".java":"java",".cs":"csharp",".go":"go",".rs":"rust",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".dart":"dart"},mn=["jest","vitest","mocha","pytest","node-test","junit5","testng","xunit","nunit","go-test","rust-test","swift-testing","xctest","kotlin-junit","flutter-test","jest-rn","playwright","cypress"],Ym=["typescript","javascript","python","java","csharp","go","rust","swift","kotlin","dart"]});function Ja(u,t={}){let{additionalContext:e,sourceCode:r,includeEvidence:i=!0,includeRemediation:n=!0,maxLength:s=8e3}=t,a=[];a.push(`# Security Finding Verification Request
3
3
 
4
4
  You are a security expert tasked with verifying whether the following security finding is valid or a false positive.
5
5
 
@@ -69,7 +69,7 @@ ${Ka(u.content,500)}
69
69
  `)}function Ka(u,t){return u.length<=t?u:u.substring(0,t-3)+"..."}function Ya(u){let t={assessment:"inconclusive",confidence:.5,reasoning:"",suggestions:[],parseSuccess:!1,rawResponse:u};try{let e=u.match(/ASSESSMENT:\s*(CONFIRMED|REJECTED|INCONCLUSIVE|NEEDS_CONTEXT|PARTIAL)/i);e&&(t.assessment=Rp(e[1].toUpperCase()));let r=u.match(/CONFIDENCE:\s*(\d+(?:\.\d+)?)\s*%?/i);r&&(t.confidence=Math.min(1,parseFloat(r[1])/100));let i=u.match(/SEVERITY:\s*(original|critical|high|medium|low|info)/i);i&&i[1].toLowerCase()!=="original"&&(t.suggestedSeverity=i[1].toLowerCase());let n=u.toUpperCase().indexOf("REASONING:"),s=u.toUpperCase().indexOf("SUGGESTIONS:");if(n!==-1){let a=u.indexOf(`
70
70
  `,n),o=s!==-1?s:u.length;a!==-1&&a<o&&(t.reasoning=u.slice(a+1,o).trim())}if(t.reasoning||(t.reasoning=u),s!==-1){let a=u.indexOf(`
71
71
  `,s);a!==-1&&(t.suggestions=u.slice(a+1).split(`
72
- `).map(o=>o.replace(/^[-*]\s*/,"").trim()).filter(o=>o.length>0))}t.parseSuccess=e!==null}catch{t.reasoning=u,t.parseSuccess=!1}return t}function Rp(u){return{CONFIRMED:"confirmed",REJECTED:"rejected",INCONCLUSIVE:"inconclusive",NEEDS_CONTEXT:"needs-context",PARTIAL:"partial"}[u]||"inconclusive"}function Xa(u){let{modelId:t,modelVersion:e,parsedResponse:r,executionTime:i,tokenUsage:n,cost:s}=u,a=r.assessment==="confirmed"||r.assessment==="partial";return{modelId:t,modelVersion:e,agrees:a,assessment:r.assessment,confidence:r.confidence,reasoning:r.reasoning,suggestedSeverity:r.suggestedSeverity,suggestions:r.suggestions.length>0?r.suggestions:void 0,executionTime:i,tokenUsage:n,cost:s,votedAt:new Date}}function si(u){let t=new ni;return u&&u.forEach(e=>t.register(e)),t}var we,ni,Me=Be(()=>{"use strict";A();se();we=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 t=await this.performHealthCheck();return this.healthCache={result:t,timestamp:Date.now()},t}catch(t){let e={healthy:!1,error:T(t)};return this.healthCache={result:e,timestamp:Date.now()},e}}getCostPerToken(){return{...this.costPerToken}}getSupportedModels(){return[...this.supportedModels]}async dispose(){this.disposed=!0,this.healthCache=null}invalidateHealthCache(){this.healthCache=null}};ni=class{providers=new Map;register(t){if(this.providers.has(t.id))throw new Error(`Provider with ID '${t.id}' is already registered`);this.providers.set(t.id,t)}unregister(t){return this.providers.delete(t)}get(t){return this.providers.get(t)}has(t){return this.providers.has(t)}getAll(){return Array.from(this.providers.values())}getIds(){return Array.from(this.providers.keys())}async getAvailable(){return(await Promise.all(this.getAll().map(async e=>({provider:e,available:await e.isAvailable()})))).filter(e=>e.available).map(e=>e.provider)}getByType(t){return this.getAll().filter(e=>e.type===t)}clear(){this.providers.clear()}async dispose(){await Promise.all(this.getAll().map(t=>t.dispose())),this.clear()}}});var Rn,jl=Be(()=>{"use strict";Rn=class{latched=new Map;disabled=process.env.AQE_PROMPT_CACHE_LATCH==="false";latch(t,e){return this.disabled?(this.latched.set(t,e),!0):this.latched.has(t)?!1:(this.latched.set(t,e),!0)}get(t){return this.latched.get(t)}has(t){return this.latched.has(t)}reset(t){this.latched.delete(t)}resetAll(){this.latched.clear()}getSnapshot(){return Object.fromEntries(this.latched)}get size(){return this.latched.size}}});var Ul={};Kt(Ul,{ClaudeModelProvider:()=>rr,createClaudeProvider:()=>Za});function Za(u){return new rr(u)}var rr,eo=Be(()=>{"use strict";A();Me();jl();rr=class extends we{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 Rn;constructor(t={}){super();let e=t.apiKey||process.env.ANTHROPIC_API_KEY||"";if(!e)throw new Error("Claude API key is required. Provide via config.apiKey or ANTHROPIC_API_KEY environment variable.");this.apiKey=e,this.baseUrl=t.baseUrl||"https://api.anthropic.com",this.config={apiKey:e,defaultModel:t.defaultModel||"claude-sonnet-4-6",baseUrl:this.baseUrl,defaultTimeout:t.defaultTimeout||3e4,maxRetries:t.maxRetries??3,retryDelayMs:t.retryDelayMs||1e3,enableLogging:t.enableLogging||!1},this.updateCostForModel(this.config.defaultModel)}async complete(t,e){if(this.disposed)throw new Error("Provider has been disposed");let r=e?.model||this.config.defaultModel,i=e?.maxTokens||4096,n=e?.temperature??.7,s=e?.timeout||this.config.defaultTimeout,a=e?.systemPrompt||this.getDefaultSystemPrompt();this.cacheLatch.has("model")&&this.cacheLatch.get("model")!==r&&this.cacheLatch.reset("model"),this.cacheLatch.has("max_tokens")&&this.cacheLatch.get("max_tokens")!==i&&this.cacheLatch.reset("max_tokens"),this.cacheLatch.has("system")&&this.cacheLatch.get("system")!==a&&this.cacheLatch.reset("system"),this.cacheLatch.latch("model",r),this.cacheLatch.latch("max_tokens",i),this.cacheLatch.latch("system",a);let o=this.cacheLatch.get("model"),c=this.cacheLatch.get("max_tokens"),l=this.cacheLatch.get("system"),d={model:o,max_tokens:c,temperature:n,system:l,messages:[{role:"user",content:t}]};this.config.enableLogging&&console.log(`[Claude] Sending request to ${o}`);let m=null;for(let g=0;g<=this.config.maxRetries;g++)try{let h=await this.makeRequest(d,s);return this.config.enableLogging&&console.log(`[Claude] Received response (${h.usage.input_tokens} in, ${h.usage.output_tokens} out)`),h.content.filter(w=>w.type==="text").map(w=>w.text).join(`
72
+ `).map(o=>o.replace(/^[-*]\s*/,"").trim()).filter(o=>o.length>0))}t.parseSuccess=e!==null}catch{t.reasoning=u,t.parseSuccess=!1}return t}function Rp(u){return{CONFIRMED:"confirmed",REJECTED:"rejected",INCONCLUSIVE:"inconclusive",NEEDS_CONTEXT:"needs-context",PARTIAL:"partial"}[u]||"inconclusive"}function Xa(u){let{modelId:t,modelVersion:e,parsedResponse:r,executionTime:i,tokenUsage:n,cost:s}=u,a=r.assessment==="confirmed"||r.assessment==="partial";return{modelId:t,modelVersion:e,agrees:a,assessment:r.assessment,confidence:r.confidence,reasoning:r.reasoning,suggestedSeverity:r.suggestedSeverity,suggestions:r.suggestions.length>0?r.suggestions:void 0,executionTime:i,tokenUsage:n,cost:s,votedAt:new Date}}function si(u){let t=new ni;return u&&u.forEach(e=>t.register(e)),t}var we,ni,Me=Be(()=>{"use strict";A();se();we=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 t=await this.performHealthCheck();return this.healthCache={result:t,timestamp:Date.now()},t}catch(t){let e={healthy:!1,error:T(t)};return this.healthCache={result:e,timestamp:Date.now()},e}}getCostPerToken(){return{...this.costPerToken}}getSupportedModels(){return[...this.supportedModels]}async dispose(){this.disposed=!0,this.healthCache=null}invalidateHealthCache(){this.healthCache=null}};ni=class{providers=new Map;register(t){if(this.providers.has(t.id))throw new Error(`Provider with ID '${t.id}' is already registered`);this.providers.set(t.id,t)}unregister(t){return this.providers.delete(t)}get(t){return this.providers.get(t)}has(t){return this.providers.has(t)}getAll(){return Array.from(this.providers.values())}getIds(){return Array.from(this.providers.keys())}async getAvailable(){return(await Promise.all(this.getAll().map(async e=>({provider:e,available:await e.isAvailable()})))).filter(e=>e.available).map(e=>e.provider)}getByType(t){return this.getAll().filter(e=>e.type===t)}clear(){this.providers.clear()}async dispose(){await Promise.all(this.getAll().map(t=>t.dispose())),this.clear()}}});var Rn,jl=Be(()=>{"use strict";Rn=class{latched=new Map;disabled=process.env.AQE_PROMPT_CACHE_LATCH==="false";latch(t,e){return this.disabled?(this.latched.set(t,e),!0):this.latched.has(t)?!1:(this.latched.set(t,e),!0)}get(t){return this.latched.get(t)}has(t){return this.latched.has(t)}reset(t){this.latched.delete(t)}resetAll(){this.latched.clear()}getSnapshot(){return Object.fromEntries(this.latched)}get size(){return this.latched.size}}});var Ul={};Kt(Ul,{ClaudeModelProvider:()=>rr,createClaudeProvider:()=>Za});function Za(u){return new rr(u)}var rr,eo=Be(()=>{"use strict";A();Me();jl();rr=class extends we{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 Rn;constructor(t={}){super();let e=t.apiKey||process.env.ANTHROPIC_API_KEY||"";if(!e)throw new Error("Claude API key is required. Provide via config.apiKey or ANTHROPIC_API_KEY environment variable.");this.apiKey=e,this.baseUrl=t.baseUrl||process.env.ANTHROPIC_BASE_URL||"https://api.anthropic.com",this.config={apiKey:e,defaultModel:t.defaultModel||"claude-sonnet-4-6",baseUrl:this.baseUrl,defaultTimeout:t.defaultTimeout||3e4,maxRetries:t.maxRetries??3,retryDelayMs:t.retryDelayMs||1e3,enableLogging:t.enableLogging||!1},this.updateCostForModel(this.config.defaultModel)}async complete(t,e){if(this.disposed)throw new Error("Provider has been disposed");let r=e?.model||this.config.defaultModel,i=e?.maxTokens||4096,n=e?.temperature??.7,s=e?.timeout||this.config.defaultTimeout,a=e?.systemPrompt||this.getDefaultSystemPrompt();this.cacheLatch.has("model")&&this.cacheLatch.get("model")!==r&&this.cacheLatch.reset("model"),this.cacheLatch.has("max_tokens")&&this.cacheLatch.get("max_tokens")!==i&&this.cacheLatch.reset("max_tokens"),this.cacheLatch.has("system")&&this.cacheLatch.get("system")!==a&&this.cacheLatch.reset("system"),this.cacheLatch.latch("model",r),this.cacheLatch.latch("max_tokens",i),this.cacheLatch.latch("system",a);let o=this.cacheLatch.get("model"),c=this.cacheLatch.get("max_tokens"),l=this.cacheLatch.get("system"),d={model:o,max_tokens:c,temperature:n,system:l,messages:[{role:"user",content:t}]};this.config.enableLogging&&console.log(`[Claude] Sending request to ${o}`);let m=null;for(let g=0;g<=this.config.maxRetries;g++)try{let h=await this.makeRequest(d,s);return this.config.enableLogging&&console.log(`[Claude] Received response (${h.usage.input_tokens} in, ${h.usage.output_tokens} out)`),h.content.filter(w=>w.type==="text").map(w=>w.text).join(`
73
73
  `)}catch(h){if(m=y(h),this.isNonRetryableError(h))throw m;if(g<this.config.maxRetries){let b=this.config.retryDelayMs*Math.pow(2,g);this.config.enableLogging&&console.log(`[Claude] Retry ${g+1}/${this.config.maxRetries} after ${b}ms`),await this.sleep(b)}}throw new Error(`Claude completion failed after ${this.config.maxRetries+1} attempts: ${m?.message}`)}async makeRequest(t,e){let r=new AbortController,i=setTimeout(()=>r.abort(),e);try{let n=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(t),signal:r.signal});if(!n.ok){let s=await n.json();throw new Error(`Claude API error (${n.status}): ${s.error.message}`)}return await n.json()}finally{clearTimeout(i)}}async performHealthCheck(){let t=Date.now();try{return await this.complete("Hello",{maxTokens:10,timeout:5e3}),{healthy:!0,latencyMs:Date.now()-t,availableModels:this.supportedModels}}catch(e){return{healthy:!1,error:T(e),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 Jv}from"crypto";Ia();var za={LOOP_WARNING:"loop.warning",LOOP_DETECTED:"loop.detected"},on=class{subscriptions=new Map;subscriptionsByEventType=new Map;subscriptionsByChannel=new Map;wildcardSubscriptions=new Set;eventHistory;maxHistorySize=ka.MAX_HISTORY_SIZE;subscriptionCounter=0;middlewares=[];constructor(t=ka.MAX_HISTORY_SIZE){this.maxHistorySize=t,this.eventHistory=new al(t)}registerMiddleware(t){this.middlewares.push(t),this.middlewares.sort((e,r)=>e.priority-r.priority)}removeMiddleware(t){let e=this.middlewares.findIndex(r=>r.name===t);return e>=0?(this.middlewares.splice(e,1),!0):!1}getMiddlewares(){return this.middlewares}async publish(t){let e=t;for(let o of this.middlewares)if(o.onEmit&&e&&(e=await o.onEmit(e),!e))return;this.eventHistory.push(e);let r=new Set,i=this.subscriptionsByEventType.get(e.type);if(i)for(let o of i)r.add(o);let n=this.subscriptionsByChannel.get(e.source);if(n)for(let o of n)r.add(o);for(let o of this.wildcardSubscriptions)r.add(o);let s=[];for(let o of r){let c=this.subscriptions.get(o);!c||!c.active||c.channel&&c.channel!==e.source||c.eventType!=="*"&&c.eventType!==e.type||s.push(c)}let a=e;for(let o of this.middlewares)if(o.onReceive&&a&&(a=await o.onReceive(a),!a))return;await Promise.allSettled(s.map(o=>o.handler(a)))}subscribe(t,e){let r=`sub_${++this.subscriptionCounter}`,i={id:r,eventType:t,handler:e,active:!0};return this.subscriptions.set(r,i),t==="*"?this.wildcardSubscriptions.add(r):(this.subscriptionsByEventType.has(t)||this.subscriptionsByEventType.set(t,new Set),this.subscriptionsByEventType.get(t).add(r)),{unsubscribe:()=>{i.active=!1,this.subscriptions.delete(r),t==="*"?this.wildcardSubscriptions.delete(r):this.subscriptionsByEventType.get(t)?.delete(r)},get active(){return i.active}}}subscribeToChannel(t,e){let r=`sub_${++this.subscriptionCounter}`,i={id:r,eventType:"*",channel:t,handler:e,active:!0};return this.subscriptions.set(r,i),this.subscriptionsByChannel.has(t)||this.subscriptionsByChannel.set(t,new Set),this.subscriptionsByChannel.get(t).add(r),{unsubscribe:()=>{i.active=!1,this.subscriptions.delete(r),this.subscriptionsByChannel.get(t)?.delete(r)},get active(){return i.active}}}async getHistory(t){let e=this.eventHistory.toArray();return t&&(t.eventTypes?.length&&(e=e.filter(r=>t.eventTypes.includes(r.type))),t.sources?.length&&(e=e.filter(r=>t.sources.includes(r.source))),t.fromTimestamp&&(e=e.filter(r=>r.timestamp>=t.fromTimestamp)),t.toTimestamp&&(e=e.filter(r=>r.timestamp<=t.toTimestamp)),t.correlationId&&(e=e.filter(r=>r.correlationId===t.correlationId)),t.limit&&(e=e.slice(-t.limit))),e}async dispose(){this.subscriptions.clear(),this.subscriptionsByEventType.clear(),this.subscriptionsByChannel.clear(),this.wildcardSubscriptions.clear(),this.eventHistory.clear(),this.middlewares=[]}};Ia();var cn=class{agents=new Map;maxAgents;memoryBranch=null;constructor(t=Lr.MAX_CONCURRENT_AGENTS){this.maxAgents=t}setMemoryBranch(t){this.memoryBranch=t}async spawn(t){if(!this.canSpawn())return p(new Error(`Cannot spawn agent: maximum concurrent agents (${this.maxAgents}) reached. Active: ${this.getActiveCount()}`));let e=t.config??{};if(t.progressiveContext?.strategy==="predictive"||process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED==="true")try{let s=e.taskDescription||t.name||"",a=e.availableFiles||[];if(s&&a.length>0){let c=new Ba(t.progressiveContext).predictFilesForTask(s,a);e={...e,availableFiles:c,contextFiles:c,initialFiles:c,progressiveContextApplied:!0}}}catch{}let i=v(),n={id:i,name:t.name,domain:t.domain,type:t.type,status:"running",capabilities:t.capabilities,config:e,startedAt:new Date};if(this.agents.set(i,n),this.memoryBranch)try{let s=this.memoryBranch.createBranch(i);n.config={...n.config,_memoryBranchPath:s.childPath,_memoryBranchRecordIngest:a=>{this.memoryBranch?.recordIngest(i,a)}}}catch(s){console.warn(`[AgentCoordinator] Memory branch creation failed for ${i}:`,s)}return f(i)}getStatus(t){return this.agents.get(t)?.status}listAgents(t){let e=Array.from(this.agents.values());return t&&(t.domain&&(e=e.filter(r=>r.domain===t.domain)),t.status&&(e=e.filter(r=>r.status===t.status)),t.type&&(e=e.filter(r=>r.type===t.type))),e.map(r=>({id:r.id,name:r.name,domain:r.domain,type:r.type,status:r.status,startedAt:r.startedAt}))}async stop(t){let e=this.agents.get(t);return e?e.status!=="running"?p(new Error(`Agent ${t} is not running (status: ${e.status})`)):(e.status="completed",e.completedAt=new Date,f(void 0)):p(new Error(`Agent not found: ${t}`))}getActiveCount(){return Array.from(this.agents.values()).filter(t=>t.status==="running"||t.status==="queued").length}canSpawn(){return this.getActiveCount()<this.maxAgents}async dispose(){let t=Array.from(this.agents.values()).filter(e=>e.status==="running");await Promise.all(t.map(e=>this.stop(e.id))),this.agents.clear()}markCompleted(t){let e=this.agents.get(t);e&&e.status==="running"&&(e.status="completed",e.completedAt=new Date,this.handleBranchOnComplete(t,"merge"))}markFailed(t){let e=this.agents.get(t);e&&e.status==="running"&&(e.status="failed",e.completedAt=new Date,this.handleBranchOnComplete(t,"discard"))}handleBranchOnComplete(t,e){if(!this.memoryBranch)return;let r=this.memoryBranch.getBranch(t);if(r)try{e==="merge"?this.memoryBranch.mergeBranch(r).catch(i=>{console.warn(`[AgentCoordinator] Branch merge failed for ${t}:`,i)}):this.memoryBranch.discardBranch(r)}catch(i){console.warn(`[AgentCoordinator] Branch ${e} failed for ${t}:`,i)}}cleanup(t=Lr.DEFAULT_AGENT_TTL_MS){let e=Date.now(),r=0;for(let[i,n]of this.agents.entries())(n.status==="completed"||n.status==="failed")&&n.completedAt&&e-n.completedAt.getTime()>t&&(this.agents.delete(i),r++);return r}},Hm={strategy:"full",maxInitialFiles:10,predictionThreshold:.7,trackFileRequests:!0},Ba=class{config;fileRequests=[];preloadedFiles=new Set;constructor(t){this.config={...Hm,...t}}isEnabled(){return process.env.AQE_PROGRESSIVE_CONTEXT_ENABLED==="true"}predictFilesForTask(t,e){if(!this.isEnabled()||this.config.strategy==="full")return[...e];if(!t||t.trim().length===0)return e.slice(0,this.config.maxInitialFiles);if(e.length===0)return[];let r=this.extractKeywords(t);if(r.length===0)return e.slice(0,this.config.maxInitialFiles);let i=e.map(s=>({filePath:s,score:this.scoreFile(s,r)}));i.sort((s,a)=>a.score-s.score);let n=i.slice(0,this.config.maxInitialFiles).map(s=>s.filePath);return this.preloadedFiles=new Set(n),n}recordFileRequest(t){this.config.trackFileRequests&&this.fileRequests.push(t)}getPredictionAccuracy(){let t=this.preloadedFiles.size,e=this.fileRequests.filter(s=>s.wasPreloaded).length,r=new Set(this.fileRequests.map(s=>s.filePath)),i=[...r].filter(s=>this.preloadedFiles.has(s)).length,n=r.size>0?i/r.size:0;return{predicted:t,actuallyUsed:e,hitRate:n}}getFileRequestHistory(t){return t?this.fileRequests.filter(e=>e.agentId===t):[...this.fileRequests]}extractKeywords(t){let e=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","to","of","in","for","on","with","at","by","from","as","into","through","during","before","after","and","but","or","nor","not","so","yet","both","either","neither","each","every","all","any","few","more","most","other","some","such","no","only","same","than","too","very","just","because","if","when","while","that","this","these","those","it","its","they","them","their","we","our","you","your","he","she","his","her","i","me","my"]),r=t.toLowerCase().split(/[\s\-_./\\,;:!?()[\]{}'"]+/).filter(i=>i.length>1&&!e.has(i));return[...new Set(r)]}scoreFile(t,e){let r=t.toLowerCase(),i=r.split(/[\\/.]/).filter(s=>s.length>0),n=0;for(let s of e)if(i.includes(s))n+=2;else if(r.includes(s))n+=1;else for(let a of i)if(a.startsWith(s)||s.startsWith(a)){n+=.5;break}return e.length>0?n/(e.length*2):0}};M();var Wm=R.create("plugin-loader"),qr=class{constructor(t,e,r=!0){this.eventBus=t;this.memory=e}eventBus;memory;plugins=new Map;factories=new Map;loading=new Map;registerFactory(t,e){this.factories.set(t,e)}async load(t){let e=this.plugins.get(t);if(e)return e;let r=this.loading.get(t);if(r)return r;let i=this.factories.get(t);if(!i){let s=Array.from(this.factories.keys());throw new Error(`No factory registered for domain: ${t}
115
115
  This usually means the domain is not enabled in your config.
116
116
  Registered domains: ${s.join(", ")}
117
- Fix: Add '${t}' to domains.enabled in .agentic-qe/config.yaml, or run 'aqe init --auto-migrate' to enable all domains.`)}let n=this.loadPlugin(t,i);this.loading.set(t,n);try{let s=await n;return this.plugins.set(t,s),s}finally{this.loading.delete(t)}}async loadPlugin(t,e){let r=await e(this.eventBus,this.memory);for(let i of r.dependencies)this.isLoaded(i)||await this.load(i);return await r.initialize(),r}async unload(t){let e=this.plugins.get(t);if(e){for(let[r,i]of this.plugins.entries())if(i.dependencies.includes(t))throw new Error(`Cannot unload ${t}: domain ${r} depends on it`);await e.dispose(),this.plugins.delete(t)}}isLoaded(t){return this.plugins.has(t)}getLoaded(){return Array.from(this.plugins.keys())}async loadAll(){let t=Array.from(this.factories.keys()),e=this.topologicalSort(t);for(let r of e)await this.load(r)}topologicalSort(t){let e=[],r=new Set,i=new Set,n=s=>{if(r.has(s))return;if(i.has(s))throw new Error(`Circular dependency detected involving: ${s}`);i.add(s);let o=this.plugins.get(s)?.dependencies??[];for(let c of o)t.includes(c)&&n(c);i.delete(s),r.add(s),e.push(s)};for(let s of t)n(s);return e}getPlugin(t){return this.plugins.get(t)}async disposeAll(){let t=[...this.getLoaded()].reverse();for(let e of t)try{await this.unload(e)}catch(r){Wm.debug("Plugin unload failed, force removing",{domain:e,error:r instanceof Error?r.message:String(r)}),this.plugins.delete(e)}}};Ki();M();var qa=R.create("anti-drift-middleware"),jm={maxIdenticalCalls:3,windowMs:3e4,steeringMessage:"Loop detected: the same tool call has been repeated multiple times. Consider an alternative approach or different parameters.",enableFleetLearning:!1};function Al(u){let t=2166136261;for(let e=0;e<u.length;e++)t^=u.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}var ln=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(t){this.config={...jm,...t}}trackCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return{isLoop:!1,callCount:1,signature:this.createSignature(e,r),action:"allow"};let i=this.createSignature(e,r);this.totalCallsTracked++,this.callHistory.has(t)||this.callHistory.set(t,[]);let n=this.callHistory.get(t);n.push(i);let s=Date.now()-this.config.windowMs,a=n.findIndex(c=>c.timestamp>=s);a>0?n.splice(0,a):a===-1&&(n.length=0,n.push(i));let o=n.filter(c=>c.hash===i.hash).length;return o>=this.config.maxIdenticalCalls?(this.loopsDetected++,{isLoop:!0,callCount:o,signature:i,action:"steer",steeringMessage:this.config.steeringMessage}):o===this.config.maxIdenticalCalls-1?{isLoop:!1,callCount:o,signature:i,action:"warn"}:{isLoop:!1,callCount:o,signature:i,action:"allow"}}getMetrics(){return{totalCallsTracked:this.totalCallsTracked,loopsDetected:this.loopsDetected}}clear(){this.callHistory.clear(),this.totalCallsTracked=0,this.loopsDetected=0}createSignature(t,e){let r=JSON.stringify(e??""),i=Al(r),n=`${t}:${r}`;return{hash:Al(n),toolName:t,argsFingerprint:i,timestamp:Date.now()}}},xl={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},Um={thresholds:xl,agentId:"unknown",maxHistorySize:200,fallbackDimension:64};function Qm(u,t){let e=new Float64Array(t),r=2166136261,i=16777619;for(let a=0;a<u.length;a++){let o=u.charCodeAt(a);r^=o,r=Math.imul(r,16777619),i^=o,i=Math.imul(i,2166136261);let c=(r>>>0)%t;e[c]+=(i>>>0)/4294967295*2-1}let n=0;for(let a=0;a<t;a++)n+=e[a]*e[a];n=Math.sqrt(n);let s=new Array(t);for(let a=0;a<t;a++)s[a]=n===0?0:e[a]/n;return s}var El=!1,Xt=!1,un=null;async function Km(){if(El)return Xt;El=!0;try{let u=await import("./real-embeddings-SKJRHLCS.js");if(typeof u.isTransformerAvailable=="function"&&u.isTransformerAvailable())un=u.computeRealEmbedding,Xt=!0;else try{await u.computeRealEmbedding("probe"),un=u.computeRealEmbedding,Xt=!0}catch(t){qa.debug("Transformer probe embedding failed",{error:t instanceof Error?t.message:String(t)}),Xt=!1}}catch(u){qa.debug("Transformer module import failed",{error:u instanceof Error?u.message:String(u)}),Xt=!1}return Xt}var dn=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;constructor(t){this.config={...Um,...t,thresholds:{...xl,...t?.thresholds}}}async onEmit(t){let e=JSON.stringify(t.payload),r=await this.embed(e),i=this.resolveCategory(t.type),n=this.config.thresholds[i]??this.config.thresholds.default,s={embedding:r,driftThreshold:n,sourceAgentId:this.config.agentId,hopCount:0,emittedAt:Date.now()};return{...t,semanticFingerprint:s}}async onReceive(t){let e=t.semanticFingerprint;if(!e)return t;let r=JSON.stringify(t.payload),i=await this.embed(r),n=et(i,e.embedding),a=1-n>e.driftThreshold;this.totalChecked++,this.similaritySum+=n;let o={drifted:a,cosineSimilarity:n,threshold:e.driftThreshold,eventType:t.type,hopCount:e.hopCount+1,checkedAt:Date.now()};if(this.history.push(o),this.history.length>this.config.maxHistorySize&&this.history.shift(),a)return this.driftCount++,await this.emitDriftEvent(t,o),null;let c={...e,hopCount:e.hopCount+1};return{...t,semanticFingerprint:c}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0}}validateConfig(){for(let[t,e]of Object.entries(this.config.thresholds))if(typeof e!="number"||e<0||e>1)return p(new Error(`Invalid threshold for "${t}": must be between 0 and 1, got ${e}`));return this.config.maxHistorySize<=0?p(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?p(new Error("fallbackDimension must be positive")):f(void 0)}async embed(t){return await Km()&&un?un(t):Qm(t,this.config.fallbackDimension)}resolveCategory(t){let e=t.toLowerCase();for(let r of Object.keys(this.config.thresholds))if(r!=="default"&&e.includes(r))return r;return"default"}async emitDriftEvent(t,e){if(!this.config.onDriftDetected)return;let r={id:`drift-${t.id}-${Date.now()}`,type:"SemanticDriftDetected",timestamp:new Date,source:t.source,correlationId:t.correlationId,payload:{originalEventId:t.id,originalEventType:t.type,cosineSimilarity:e.cosineSimilarity,threshold:e.threshold,hopCount:e.hopCount,agentId:this.config.agentId}};try{await this.config.onDriftDetected(r)}catch(i){qa.debug("onDriftDetected callback failed",{error:i instanceof Error?i.message:String(i)})}}};Ia();Yt();import*as Qt from"path";import*as xa from"fs";A();var W=class{constructor(t,e){this.eventBus=t;this.memory=e}eventBus;memory;_initialized=!1;_health={status:"idle",agents:{total:0,active:0,idle:0,failed:0},errors:[]};_minCutBridge;_consensusConfig;isReady(){return this._initialized}getHealth(){return{...this._health}}async initialize(){this._initialized||(await this.onInitialize(),this.subscribeToEvents(),this._initialized=!0)}async dispose(){await this.onDispose(),this._initialized=!1}async handleEvent(t){await this.onEvent(t)}async onInitialize(){}async onDispose(){}async onEvent(t){}subscribeToEvents(){}async publishEvent(t,e){let r={id:crypto.randomUUID(),type:t,timestamp:new Date,source:this.name,payload:e};await this.eventBus.publish(r)}updateHealth(t){this._health={...this._health,...t}}setMinCutBridge(t){this._minCutBridge=t,this.onMinCutBridgeSet(t)}getMinCutBridge(){return this._minCutBridge}setConsensusConfig(t){this._consensusConfig=t,this.onConsensusConfigSet(t)}getConsensusConfig(){return this._consensusConfig}setIntegrationConfig(t){t.minCutBridge&&this.setMinCutBridge(t.minCutBridge),t.consensusConfig&&this.setConsensusConfig(t.consensusConfig)}hasMinCutIntegration(){return this._minCutBridge!==void 0}hasConsensusEnabled(){return this._consensusConfig?.enabled===!0}onMinCutBridgeSet(t){}onConsensusConfigSet(t){}getTaskHandlers(){return new Map}canHandleTask(t){return this.getTaskHandlers().has(t)}async executeTask(t,e){let i=this.getTaskHandlers().get(t.taskType);return i?(this.runTaskAsync(t,i,e),f(void 0)):p(new Error(`Domain ${this.name} has no handler for task type: ${t.taskType}`))}async runTaskAsync(t,e,r){let i=Date.now();try{let n=await e(t.payload),s=Date.now()-i,a={taskId:t.taskId,success:n.success,data:n.success?n.value:void 0,error:n.success?void 0:n.error?.message,duration:s};if(await r(a),n.success)this.updateHealth({lastActivity:new Date,agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),idle:this._health.agents.idle+1}});else{let o=n.error?.message??"Unknown error";this.updateHealth({lastActivity:new Date,errors:[...this._health.errors.slice(-9),o],agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),failed:this._health.agents.failed+1}})}}catch(n){let s=Date.now()-i,a=T(n);await r({taskId:t.taskId,success:!1,error:a,duration:s}),this.updateHealth({lastActivity:new Date,errors:[...this._health.errors.slice(-9),a],agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),failed:this._health.agents.failed+1}})}}};M();A();M();import*as Gl from"fs";import*as ri from"path";Zt();import{randomBytes as Xm,randomInt as it,randomUUID as Zm}from"node:crypto";function Dl(u){return Xm(u).toString("hex")}var I={uuid:()=>Zm(),email:()=>`user_${Dl(3)}@example.com`,fullName:()=>{let u=["Alice","Bob","Carol","Dave","Eve","Frank"],t=["Smith","Jones","Lee","Garcia","Chen","Novak"];return`${u[it(u.length)]} ${t[it(t.length)]}`},url:()=>`https://example.com/${Dl(4)}`,recentDate:()=>new Date(Date.now()-it(7*864e5)).toISOString(),phone:()=>`+1${String(it(2e9,9999999999))}`,streetAddress:()=>`${it(1,9999)} Main St`,word:()=>{let u=["alpha","bravo","charlie","delta","echo","foxtrot","golf","hotel"];return u[it(u.length)]},int:(u=1,t=100)=>{if(u>t){let e=u;u=t,t=e}return it(u,t+1)},float:(u=0,t=100,e=2)=>{if(u>t){let i=u;u=t,t=i}if(u===t)return u;let r=u+it(0,1000001)/1e6*(t-u);return Number(r.toFixed(e))}};var J=class u{static NAME_VALUE_TABLE=[["id",()=>`'${I.uuid()}'`],["email",()=>`'${I.email()}'`],["name",()=>`'${I.fullName()}'`],["url",()=>`'${I.url()}'`],["date",()=>`new Date('${I.recentDate()}')`],["phone",()=>`'${I.phone()}'`],["address",()=>`'${I.streetAddress()}'`]];static TYPE_VALUE_TABLE=[["string",()=>`'${I.word()}'`],["number",()=>String(I.int(1,100))],["boolean",()=>"true"],["[]",()=>"[]"],["array",()=>"[]"],["object",()=>"{}"],["{",()=>"{}"],["function",()=>"() => {}"],["promise",()=>"Promise.resolve()"],["date",()=>"new Date()"]];generateTestValue(t){if(t.defaultValue)return t.defaultValue;let e=t.type?.toLowerCase()||"unknown",r=t.name.toLowerCase();for(let[i,n]of u.NAME_VALUE_TABLE)if(r.includes(i))return n();for(let[i,n]of u.TYPE_VALUE_TABLE)if(e.includes(i))return n();return`{} /* TODO: provide ${t.name}: ${t.type||"unknown"} */`}generateTestCasesForFunction(t){let e=[],r=t.parameters.map(c=>this.generateTestValue(c)).join(", "),i=t.isAsync?`await ${t.name}(${r})`:`${t.name}(${r})`,n=t.returnType==="void"||t.returnType==="Promise<void>",s="expect(result).toBeDefined();";if(!n){if(/^(is|has|can)[A-Z]/.test(t.name))s="expect(typeof result).toBe('boolean');";else if(/^(get|fetch|find)[A-Z]/.test(t.name))s="expect(result).not.toBeUndefined();";else if(/^(create|build|make)[A-Z]/.test(t.name))s="expect(result).toBeTruthy();";else if(t.returnType){let c=t.returnType.toLowerCase().replace(/promise<(.+)>/,"$1");c.includes("{")?s="expect(typeof result).toBe('object');":c==="boolean"?s="expect(typeof result).toBe('boolean');":c==="number"?s="expect(typeof result).toBe('number');":c==="string"?s="expect(typeof result).toBe('string');":c.includes("[]")||c.includes("array")?s="expect(Array.isArray(result)).toBe(true);":c.includes("boolean")?s="expect(typeof result).toBe('boolean');":c.includes("number")?s="expect(typeof result).toBe('number');":c.includes("string")&&(s="expect(typeof result).toBe('string');")}}e.push({description:"should handle valid input correctly",type:"happy-path",action:n?`${i};`:`const result = ${i};`,assertion:n?"// void function \u2014 no return value to assert":s});let a=t.body||"",o=/\bthrow\b/.test(a)||/\bvalidat/i.test(a);for(let c of t.parameters){if(!c.optional){let l=t.parameters.map(d=>d.name===c.name?"undefined":this.generateTestValue(d)).join(", ");if(o)e.push({description:`should handle undefined ${c.name}`,type:"error-handling",action:t.isAsync?`const action = async () => await ${t.name}(${l});`:`const action = () => ${t.name}(${l});`,assertion:"expect(action).toThrow();"});else{let d=t.isAsync?`await ${t.name}(${l})`:`${t.name}(${l})`;e.push({description:`should handle undefined ${c.name}`,type:"edge-case",action:t.isAsync?`let threw = false;
117
+ Fix: Add '${t}' to domains.enabled in .agentic-qe/config.yaml, or run 'aqe init --auto-migrate' to enable all domains.`)}let n=this.loadPlugin(t,i);this.loading.set(t,n);try{let s=await n;return this.plugins.set(t,s),s}finally{this.loading.delete(t)}}async loadPlugin(t,e){let r=await e(this.eventBus,this.memory);for(let i of r.dependencies)this.isLoaded(i)||await this.load(i);return await r.initialize(),r}async unload(t){let e=this.plugins.get(t);if(e){for(let[r,i]of this.plugins.entries())if(i.dependencies.includes(t))throw new Error(`Cannot unload ${t}: domain ${r} depends on it`);await e.dispose(),this.plugins.delete(t)}}isLoaded(t){return this.plugins.has(t)}getLoaded(){return Array.from(this.plugins.keys())}async loadAll(){let t=Array.from(this.factories.keys()),e=this.topologicalSort(t);for(let r of e)await this.load(r)}topologicalSort(t){let e=[],r=new Set,i=new Set,n=s=>{if(r.has(s))return;if(i.has(s))throw new Error(`Circular dependency detected involving: ${s}`);i.add(s);let o=this.plugins.get(s)?.dependencies??[];for(let c of o)t.includes(c)&&n(c);i.delete(s),r.add(s),e.push(s)};for(let s of t)n(s);return e}getPlugin(t){return this.plugins.get(t)}async disposeAll(){let t=[...this.getLoaded()].reverse();for(let e of t)try{await this.unload(e)}catch(r){Wm.debug("Plugin unload failed, force removing",{domain:e,error:r instanceof Error?r.message:String(r)}),this.plugins.delete(e)}}};Ki();M();var qa=R.create("anti-drift-middleware"),jm={maxIdenticalCalls:3,windowMs:3e4,steeringMessage:"Loop detected: the same tool call has been repeated multiple times. Consider an alternative approach or different parameters.",enableFleetLearning:!1};function Al(u){let t=2166136261;for(let e=0;e<u.length;e++)t^=u.charCodeAt(e),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}var ln=class{config;callHistory=new Map;totalCallsTracked=0;loopsDetected=0;constructor(t){this.config={...jm,...t}}trackCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return{isLoop:!1,callCount:1,signature:this.createSignature(e,r),action:"allow"};let i=this.createSignature(e,r);this.totalCallsTracked++,this.callHistory.has(t)||this.callHistory.set(t,[]);let n=this.callHistory.get(t);n.push(i);let s=Date.now()-this.config.windowMs,a=n.findIndex(c=>c.timestamp>=s);a>0?n.splice(0,a):a===-1&&(n.length=0,n.push(i));let o=n.filter(c=>c.hash===i.hash).length;return o>=this.config.maxIdenticalCalls?(this.loopsDetected++,{isLoop:!0,callCount:o,signature:i,action:"steer",steeringMessage:this.config.steeringMessage}):o===this.config.maxIdenticalCalls-1?{isLoop:!1,callCount:o,signature:i,action:"warn"}:{isLoop:!1,callCount:o,signature:i,action:"allow"}}getMetrics(){return{totalCallsTracked:this.totalCallsTracked,loopsDetected:this.loopsDetected}}clear(){this.callHistory.clear(),this.totalCallsTracked=0,this.loopsDetected=0}createSignature(t,e){let r=JSON.stringify(e??""),i=Al(r),n=`${t}:${r}`;return{hash:Al(n),toolName:t,argsFingerprint:i,timestamp:Date.now()}}},xl={"quality-gate":.05,coverage:.1,"test-generation":.15,learning:.2,default:.12},Um={thresholds:xl,agentId:"unknown",maxHistorySize:200,fallbackDimension:64};function Qm(u,t){let e=new Float64Array(t),r=2166136261,i=16777619;for(let a=0;a<u.length;a++){let o=u.charCodeAt(a);r^=o,r=Math.imul(r,16777619),i^=o,i=Math.imul(i,2166136261);let c=(r>>>0)%t;e[c]+=(i>>>0)/4294967295*2-1}let n=0;for(let a=0;a<t;a++)n+=e[a]*e[a];n=Math.sqrt(n);let s=new Array(t);for(let a=0;a<t;a++)s[a]=n===0?0:e[a]/n;return s}var El=!1,Xt=!1,un=null;async function Km(){if(El)return Xt;El=!0;try{let u=await import("./real-embeddings-P2LYDBVF.js");if(typeof u.isTransformerAvailable=="function"&&u.isTransformerAvailable())un=u.computeRealEmbedding,Xt=!0;else try{await u.computeRealEmbedding("probe"),un=u.computeRealEmbedding,Xt=!0}catch(t){qa.debug("Transformer probe embedding failed",{error:t instanceof Error?t.message:String(t)}),Xt=!1}}catch(u){qa.debug("Transformer module import failed",{error:u instanceof Error?u.message:String(u)}),Xt=!1}return Xt}var dn=class{name="semantic-anti-drift";priority=10;config;history=[];totalChecked=0;driftCount=0;similaritySum=0;constructor(t){this.config={...Um,...t,thresholds:{...xl,...t?.thresholds}}}async onEmit(t){let e=JSON.stringify(t.payload),r=await this.embed(e),i=this.resolveCategory(t.type),n=this.config.thresholds[i]??this.config.thresholds.default,s={embedding:r,driftThreshold:n,sourceAgentId:this.config.agentId,hopCount:0,emittedAt:Date.now()};return{...t,semanticFingerprint:s}}async onReceive(t){let e=t.semanticFingerprint;if(!e)return t;let r=JSON.stringify(t.payload),i=await this.embed(r),n=et(i,e.embedding),a=1-n>e.driftThreshold;this.totalChecked++,this.similaritySum+=n;let o={drifted:a,cosineSimilarity:n,threshold:e.driftThreshold,eventType:t.type,hopCount:e.hopCount+1,checkedAt:Date.now()};if(this.history.push(o),this.history.length>this.config.maxHistorySize&&this.history.shift(),a)return this.driftCount++,await this.emitDriftEvent(t,o),null;let c={...e,hopCount:e.hopCount+1};return{...t,semanticFingerprint:c}}getDriftHistory(){return this.history}getStats(){return{totalChecked:this.totalChecked,driftCount:this.driftCount,averageSimilarity:this.totalChecked>0?this.similaritySum/this.totalChecked:0}}validateConfig(){for(let[t,e]of Object.entries(this.config.thresholds))if(typeof e!="number"||e<0||e>1)return p(new Error(`Invalid threshold for "${t}": must be between 0 and 1, got ${e}`));return this.config.maxHistorySize<=0?p(new Error("maxHistorySize must be positive")):this.config.fallbackDimension<=0?p(new Error("fallbackDimension must be positive")):f(void 0)}async embed(t){return await Km()&&un?un(t):Qm(t,this.config.fallbackDimension)}resolveCategory(t){let e=t.toLowerCase();for(let r of Object.keys(this.config.thresholds))if(r!=="default"&&e.includes(r))return r;return"default"}async emitDriftEvent(t,e){if(!this.config.onDriftDetected)return;let r={id:`drift-${t.id}-${Date.now()}`,type:"SemanticDriftDetected",timestamp:new Date,source:t.source,correlationId:t.correlationId,payload:{originalEventId:t.id,originalEventType:t.type,cosineSimilarity:e.cosineSimilarity,threshold:e.threshold,hopCount:e.hopCount,agentId:this.config.agentId}};try{await this.config.onDriftDetected(r)}catch(i){qa.debug("onDriftDetected callback failed",{error:i instanceof Error?i.message:String(i)})}}};Ia();Yt();import*as Qt from"path";import*as xa from"fs";A();var W=class{constructor(t,e){this.eventBus=t;this.memory=e}eventBus;memory;_initialized=!1;_health={status:"idle",agents:{total:0,active:0,idle:0,failed:0},errors:[]};_minCutBridge;_consensusConfig;isReady(){return this._initialized}getHealth(){return{...this._health}}async initialize(){this._initialized||(await this.onInitialize(),this.subscribeToEvents(),this._initialized=!0)}async dispose(){await this.onDispose(),this._initialized=!1}async handleEvent(t){await this.onEvent(t)}async onInitialize(){}async onDispose(){}async onEvent(t){}subscribeToEvents(){}async publishEvent(t,e){let r={id:crypto.randomUUID(),type:t,timestamp:new Date,source:this.name,payload:e};await this.eventBus.publish(r)}updateHealth(t){this._health={...this._health,...t}}setMinCutBridge(t){this._minCutBridge=t,this.onMinCutBridgeSet(t)}getMinCutBridge(){return this._minCutBridge}setConsensusConfig(t){this._consensusConfig=t,this.onConsensusConfigSet(t)}getConsensusConfig(){return this._consensusConfig}setIntegrationConfig(t){t.minCutBridge&&this.setMinCutBridge(t.minCutBridge),t.consensusConfig&&this.setConsensusConfig(t.consensusConfig)}hasMinCutIntegration(){return this._minCutBridge!==void 0}hasConsensusEnabled(){return this._consensusConfig?.enabled===!0}onMinCutBridgeSet(t){}onConsensusConfigSet(t){}getTaskHandlers(){return new Map}canHandleTask(t){return this.getTaskHandlers().has(t)}async executeTask(t,e){let i=this.getTaskHandlers().get(t.taskType);return i?(this.runTaskAsync(t,i,e),f(void 0)):p(new Error(`Domain ${this.name} has no handler for task type: ${t.taskType}`))}async runTaskAsync(t,e,r){let i=Date.now();try{let n=await e(t.payload),s=Date.now()-i,a={taskId:t.taskId,success:n.success,data:n.success?n.value:void 0,error:n.success?void 0:n.error?.message,duration:s};if(await r(a),n.success)this.updateHealth({lastActivity:new Date,agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),idle:this._health.agents.idle+1}});else{let o=n.error?.message??"Unknown error";this.updateHealth({lastActivity:new Date,errors:[...this._health.errors.slice(-9),o],agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),failed:this._health.agents.failed+1}})}}catch(n){let s=Date.now()-i,a=T(n);await r({taskId:t.taskId,success:!1,error:a,duration:s}),this.updateHealth({lastActivity:new Date,errors:[...this._health.errors.slice(-9),a],agents:{...this._health.agents,active:Math.max(0,this._health.agents.active-1),failed:this._health.agents.failed+1}})}}};M();A();M();import*as Gl from"fs";import*as ri from"path";Zt();import{randomBytes as Xm,randomInt as it,randomUUID as Zm}from"node:crypto";function Dl(u){return Xm(u).toString("hex")}var I={uuid:()=>Zm(),email:()=>`user_${Dl(3)}@example.com`,fullName:()=>{let u=["Alice","Bob","Carol","Dave","Eve","Frank"],t=["Smith","Jones","Lee","Garcia","Chen","Novak"];return`${u[it(u.length)]} ${t[it(t.length)]}`},url:()=>`https://example.com/${Dl(4)}`,recentDate:()=>new Date(Date.now()-it(7*864e5)).toISOString(),phone:()=>`+1${String(it(2e9,9999999999))}`,streetAddress:()=>`${it(1,9999)} Main St`,word:()=>{let u=["alpha","bravo","charlie","delta","echo","foxtrot","golf","hotel"];return u[it(u.length)]},int:(u=1,t=100)=>{if(u>t){let e=u;u=t,t=e}return it(u,t+1)},float:(u=0,t=100,e=2)=>{if(u>t){let i=u;u=t,t=i}if(u===t)return u;let r=u+it(0,1000001)/1e6*(t-u);return Number(r.toFixed(e))}};var J=class u{static NAME_VALUE_TABLE=[["id",()=>`'${I.uuid()}'`],["email",()=>`'${I.email()}'`],["name",()=>`'${I.fullName()}'`],["url",()=>`'${I.url()}'`],["date",()=>`new Date('${I.recentDate()}')`],["phone",()=>`'${I.phone()}'`],["address",()=>`'${I.streetAddress()}'`]];static TYPE_VALUE_TABLE=[["string",()=>`'${I.word()}'`],["number",()=>String(I.int(1,100))],["boolean",()=>"true"],["[]",()=>"[]"],["array",()=>"[]"],["object",()=>"{}"],["{",()=>"{}"],["function",()=>"() => {}"],["promise",()=>"Promise.resolve()"],["date",()=>"new Date()"]];generateTestValue(t){if(t.defaultValue)return t.defaultValue;let e=t.type?.toLowerCase()||"unknown",r=t.name.toLowerCase();for(let[i,n]of u.NAME_VALUE_TABLE)if(r.includes(i))return n();for(let[i,n]of u.TYPE_VALUE_TABLE)if(e.includes(i))return n();return`{} /* TODO: provide ${t.name}: ${t.type||"unknown"} */`}generateTestCasesForFunction(t){let e=[],r=t.parameters.map(c=>this.generateTestValue(c)).join(", "),i=t.isAsync?`await ${t.name}(${r})`:`${t.name}(${r})`,n=t.returnType==="void"||t.returnType==="Promise<void>",s="expect(result).toBeDefined();";if(!n){if(/^(is|has|can)[A-Z]/.test(t.name))s="expect(typeof result).toBe('boolean');";else if(/^(get|fetch|find)[A-Z]/.test(t.name))s="expect(result).not.toBeUndefined();";else if(/^(create|build|make)[A-Z]/.test(t.name))s="expect(result).toBeTruthy();";else if(t.returnType){let c=t.returnType.toLowerCase().replace(/promise<(.+)>/,"$1");c.includes("{")?s="expect(typeof result).toBe('object');":c==="boolean"?s="expect(typeof result).toBe('boolean');":c==="number"?s="expect(typeof result).toBe('number');":c==="string"?s="expect(typeof result).toBe('string');":c.includes("[]")||c.includes("array")?s="expect(Array.isArray(result)).toBe(true);":c.includes("boolean")?s="expect(typeof result).toBe('boolean');":c.includes("number")?s="expect(typeof result).toBe('number');":c.includes("string")&&(s="expect(typeof result).toBe('string');")}}e.push({description:"should handle valid input correctly",type:"happy-path",action:n?`${i};`:`const result = ${i};`,assertion:n?"// void function \u2014 no return value to assert":s});let a=t.body||"",o=/\bthrow\b/.test(a)||/\bvalidat/i.test(a);for(let c of t.parameters){if(!c.optional){let l=t.parameters.map(d=>d.name===c.name?"undefined":this.generateTestValue(d)).join(", ");if(o)e.push({description:`should handle undefined ${c.name}`,type:"error-handling",action:t.isAsync?`const action = async () => await ${t.name}(${l});`:`const action = () => ${t.name}(${l});`,assertion:"expect(action).toThrow();"});else{let d=t.isAsync?`await ${t.name}(${l})`:`${t.name}(${l})`;e.push({description:`should handle undefined ${c.name}`,type:"edge-case",action:t.isAsync?`let threw = false;
118
118
  try {
119
119
  await ${t.name}(${l});
120
120
  } catch (e) {
@@ -2052,7 +2052,7 @@ ${t}
2052
2052
  Return a JSON array of test suggestions, each with: { "name": "test name", "description": "what to test", "type": "unit|integration|edge" }`},{role:"user",content:`Analyze this ${r} code and suggest test cases:
2053
2053
  \`\`\`${this.getCodeFenceLanguage(r)}
2054
2054
  ${t}
2055
- \`\`\``}],model:i,maxTokens:1024,temperature:.5});if(n.content)try{let s=n.content.match(/\[[\s\S]*\]/);if(s)return E(s[0]).map(o=>o.name)}catch{}return[]}catch{return ja.warn("LLM suggestion generation failed:"),[]}}async generateTests(t){try{let e=Vl({sourceFiles:t.sourceFiles,language:t.language,framework:t.framework,projectRoot:t.projectRoot}),r=t.framework||e?.framework||"vitest",i=t.language||e?.language,{sourceFiles:n,testType:s,coverageTarget:a=this.config.coverageTargetDefault,patterns:o=[]}=t;if(n.length===0)return p(new Error("No source files provided"));let c=[],l=[];for(let m of n){let g=await this.generateTestsForFile(m,s,r,o,i,t);g.success&&(c.push(...g.value.tests),l.push(...g.value.patternsUsed))}if(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true")for(let m of c)vp(m.id)&&(m.holdout=!0);let d=this.estimateCoverage(c,a);return await this.storeGenerationMetadata(c,l),f({tests:c,coverageEstimate:d,patternsUsed:Array.from(new Set(l))})}catch(e){return p(y(e))}}async generateForCoverageGap(t,e,r){try{if(e.length===0)return f([]);let i=[],n=this.groupConsecutiveLines(e),s=this.generatorFactory.supports(r)?r:this.config.defaultFramework;for(let a of n){let o=await this.generateTestForLines(t,a,s);o&&i.push(o)}return f(i)}catch(i){return p(y(i))}}async generateTDDTests(t){try{let e=await this.tddGenerator.generateTDDTests(t);return f(e)}catch(e){return p(y(e))}}async generatePropertyTests(t){try{let e=await this.propertyTestGenerator.generatePropertyTests(t);return f(e)}catch(e){return p(y(e))}}async generateTestData(t){try{let e=await this.testDataGenerator.generateTestData(t);return f(e)}catch(e){return p(y(e))}}async generateTestsForFile(t,e,r,i,n,s){let a=this.getTestFilePath(t,r),o=[],c=await this.findApplicablePatterns(t,i);o.push(...c.map(P=>P.name));let l=null,d="";try{d=Gl.readFileSync(t,"utf-8"),l=await this.analyzeSourceCode(d,t)}catch{}let m,g;this.memory&&d&&await this.hasKGVectors()&&(m=await this.queryKGDependencies(t,d),g=await this.queryKGSimilarCode(d));let h=this.generatorFactory.create(r),b=this.extractModuleName(t),w=s?.importPathOverrides?.[t]??this.getImportPath(t),C={moduleName:b,importPath:w,testType:e,patterns:c,analysis:l??void 0,dependencies:m,similarCode:g},S=h.generateTests(C);this.isLLMEnhancementAvailable()&&d&&(S=await this.enhanceTestWithLLM(S,d,l,C));let k={id:v(),name:`${b} tests`,sourceFile:t,testFile:a,testCode:S,type:e,assertions:this.countAssertions(S),language:n,framework:r,llmEnhanced:this.isLLMEnhancementAvailable()};if(s?.compileValidation&&n)try{let P=await zl.validate(S,n,s.projectRoot);k.compilationValidated=P.compiles,P.compiles||(k.compilationErrors=P.errors.map(O=>O.message))}catch{}return this.qualityGate&&(k.qualityGateResult=this.qualityGate.validate(S,t,d||void 0)),f({tests:[k],patternsUsed:o})}async generateTestForLines(t,e,r){if(e.length===0)return null;let i=v(),n=this.getTestFilePath(t,r),s=this.extractModuleName(t),a=this.getImportPath(t),c=this.generatorFactory.create(r).generateCoverageTests(s,a,e);return{id:i,name:`Coverage test for lines ${e[0]}-${e[e.length-1]}`,sourceFile:t,testFile:n,testCode:c,type:"unit",assertions:this.countAssertions(c)}}async analyzeSourceCode(t,e){let r=ri.extname(e),i=rt(r);if(i&&i!=="typescript"&&i!=="javascript"){let c=await Or.parseFile(t,e,i);if(c)return nt.convertParsedFile(c)}let n=x.createSourceFile(ri.basename(e),t,x.ScriptTarget.Latest,!0,x.ScriptKind.TS),s=[],a=[],o=c=>{if(x.isFunctionDeclaration(c)&&c.name)s.push(this.extractFunctionInfo(c,n));else if(x.isVariableStatement(c)){for(let l of c.declarationList.declarations)if(x.isVariableDeclaration(l)&&l.initializer&&(x.isArrowFunction(l.initializer)||x.isFunctionExpression(l.initializer))){let d=l.name.getText(n);s.push(this.extractArrowFunctionInfo(d,l.initializer,n,c))}}else x.isClassDeclaration(c)&&c.name&&a.push(this.extractClassInfo(c,n));x.forEachChild(c,o)};return x.forEachChild(n,o),{functions:s,classes:a}}extractFunctionInfo(t,e){let r=t.name?.getText(e)||"anonymous",i=this.extractParameters(t.parameters,e),n=t.type?.getText(e),s=t.modifiers?.some(l=>l.kind===x.SyntaxKind.AsyncKeyword)??!1,a=t.modifiers?.some(l=>l.kind===x.SyntaxKind.ExportKeyword)??!1,{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:c}=e.getLineAndCharacterOfPosition(t.getEnd());return{name:r,parameters:i,returnType:n,isAsync:s,isExported:a,complexity:this.calculateComplexity(t),startLine:o+1,endLine:c+1,body:t.body?.getText(e)}}extractArrowFunctionInfo(t,e,r,i){let n=this.extractParameters(e.parameters,r),s=e.type?.getText(r),a=e.modifiers?.some(d=>d.kind===x.SyntaxKind.AsyncKeyword)??!1,o=x.isVariableStatement(i)&&(i.modifiers?.some(d=>d.kind===x.SyntaxKind.ExportKeyword)??!1),{line:c}=r.getLineAndCharacterOfPosition(e.getStart(r)),{line:l}=r.getLineAndCharacterOfPosition(e.getEnd());return{name:t,parameters:n,returnType:s,isAsync:a,isExported:o,complexity:this.calculateComplexity(e),startLine:c+1,endLine:l+1,body:e.body?.getText(r)}}extractClassInfo(t,e){let r=t.name?.getText(e)||"AnonymousClass",i=[],n=[],s=!1,a,o=t.modifiers?.some(c=>c.kind===x.SyntaxKind.ExportKeyword)??!1;for(let c of t.members)if(x.isMethodDeclaration(c)){let l=c.name.getText(e),d=this.extractParameters(c.parameters,e),m=c.type?.getText(e),g=c.modifiers?.some(w=>w.kind===x.SyntaxKind.AsyncKeyword)??!1,{line:h}=e.getLineAndCharacterOfPosition(c.getStart(e)),{line:b}=e.getLineAndCharacterOfPosition(c.getEnd());i.push({name:l,parameters:d,returnType:m,isAsync:g,isExported:!1,complexity:this.calculateComplexity(c),startLine:h+1,endLine:b+1,body:c.body?.getText(e)})}else if(x.isConstructorDeclaration(c))s=!0,a=this.extractParameters(c.parameters,e);else if(x.isPropertyDeclaration(c)){let l=c.name.getText(e),d=c.type?.getText(e),m=c.modifiers?.some(h=>h.kind===x.SyntaxKind.PrivateKeyword)??!1,g=c.modifiers?.some(h=>h.kind===x.SyntaxKind.ReadonlyKeyword)??!1;n.push({name:l,type:d,isPrivate:m,isReadonly:g})}return{name:r,methods:i,properties:n,isExported:o,hasConstructor:s,constructorParams:a}}extractParameters(t,e){let r=0,i=0;return t.map(n=>{let s=n.name.getText(e),a=n.type?.getText(e);return x.isObjectBindingPattern(n.name)?(r++,s=r>1?`options${r}`:"options",a||(a=`{ ${n.name.elements.map(c=>`${c.name.getText(e)}: unknown`).join(", ")} }`)):x.isArrayBindingPattern(n.name)&&(i++,s=i>1?`items${i}`:"items",a||(a="unknown[]")),{name:s,type:a,optional:n.questionToken!==void 0,defaultValue:n.initializer?.getText(e)}})}calculateComplexity(t){let e=1,r=i=>{switch(i.kind){case x.SyntaxKind.IfStatement:case x.SyntaxKind.ForStatement:case x.SyntaxKind.ForInStatement:case x.SyntaxKind.ForOfStatement:case x.SyntaxKind.WhileStatement:case x.SyntaxKind.DoStatement:case x.SyntaxKind.CaseClause:case x.SyntaxKind.CatchClause:case x.SyntaxKind.ConditionalExpression:e++;break;case x.SyntaxKind.BinaryExpression:{let n=i;(n.operatorToken.kind===x.SyntaxKind.AmpersandAmpersandToken||n.operatorToken.kind===x.SyntaxKind.BarBarToken)&&e++;break}}x.forEachChild(i,r)};return x.forEachChild(t,r),e}async hasKGVectors(){try{let t=new Array(384).fill(0);return t[0]=1,(await this.memory.vectorSearch(t,1)).length>0}catch{return!1}}async queryKGDependencies(t,e){try{let r=[],i=[],n=[],s=[],a=e.matchAll(/(?:import|from)\s+['"]([^'"]+)['"]/g);for(let m of a)r.push(m[1]);if(t.endsWith(".py")){let m=e.matchAll(/(?:^|\n)\s*(?:from\s+(\S+)\s+import|import\s+(\S+))/g);for(let g of m){let h=g[1]||g[2];h&&/^[a-zA-Z_][\w.]*$/.test(h)&&r.push(h)}}let l=t.replace(/\\/g,"/").split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/,"")||"",d=await this.memory.search(`code-intelligence:kg:node:*${l}*`,50);for(let m of d){if(!m.includes(l))continue;let g=m.split(":"),h=g[g.length-2],b=g[g.length-1];h==="function"&&n.push(b)}return r.length===0&&i.length===0&&n.length===0&&s.length===0?void 0:{imports:r,importedBy:i,callees:n,callers:s}}catch{return}}async queryKGSimilarCode(t){try{let e=this.generatePseudoEmbedding(t),r=await this.memory.vectorSearch(e,5);if(r.length===0)return;let i=[];for(let n of r){if(n.score<.1)continue;let s=n.metadata,a=s?.file||n.key,o=s?.name||s?.type||n.key.split(":").pop()||"";i.push({file:a,snippet:o,score:n.score})}return i.length>0?{snippets:i}:void 0}catch{return}}generatePseudoEmbedding(t){let r=new Array(384).fill(0),i=t.split(/[^a-zA-Z0-9_$]+/).filter(s=>s.length>1);for(let s=0;s<i.length;s++){let a=i[s];for(let o=0;o<a.length&&o<r.length;o++)r[(s+o)%384]+=a.charCodeAt(o)/1e3}let n=Math.sqrt(r.reduce((s,a)=>s+a*a,0));if(n>0)for(let s=0;s<384;s++)r[s]/=n;return r}getCodeFenceLanguage(t){try{let{FRAMEWORK_TO_LANGUAGE:e}=(Zt(),Jt(Il)),r=e?.[t];if(r){let i=ql(r);if(i)return i.codeFenceLanguage}}catch{}return"typescript"}convertParsedToCodeAnalysis(t){return nt.convertParsedFile(t)}async findApplicablePatterns(t,e){let r=[];try{let{getUnifiedMemory:i}=await import("./unified-memory-2ETCY22B.js"),n=i().getDatabase();for(let o of e){let c=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2055
+ \`\`\``}],model:i,maxTokens:1024,temperature:.5});if(n.content)try{let s=n.content.match(/\[[\s\S]*\]/);if(s)return E(s[0]).map(o=>o.name)}catch{}return[]}catch{return ja.warn("LLM suggestion generation failed:"),[]}}async generateTests(t){try{let e=Vl({sourceFiles:t.sourceFiles,language:t.language,framework:t.framework,projectRoot:t.projectRoot}),r=t.framework||e?.framework||"vitest",i=t.language||e?.language,{sourceFiles:n,testType:s,coverageTarget:a=this.config.coverageTargetDefault,patterns:o=[]}=t;if(n.length===0)return p(new Error("No source files provided"));let c=[],l=[];for(let m of n){let g=await this.generateTestsForFile(m,s,r,o,i,t);g.success&&(c.push(...g.value.tests),l.push(...g.value.patternsUsed))}if(process.env.AQE_HOLDOUT_TESTING_ENABLED==="true")for(let m of c)vp(m.id)&&(m.holdout=!0);let d=this.estimateCoverage(c,a);return await this.storeGenerationMetadata(c,l),f({tests:c,coverageEstimate:d,patternsUsed:Array.from(new Set(l))})}catch(e){return p(y(e))}}async generateForCoverageGap(t,e,r){try{if(e.length===0)return f([]);let i=[],n=this.groupConsecutiveLines(e),s=this.generatorFactory.supports(r)?r:this.config.defaultFramework;for(let a of n){let o=await this.generateTestForLines(t,a,s);o&&i.push(o)}return f(i)}catch(i){return p(y(i))}}async generateTDDTests(t){try{let e=await this.tddGenerator.generateTDDTests(t);return f(e)}catch(e){return p(y(e))}}async generatePropertyTests(t){try{let e=await this.propertyTestGenerator.generatePropertyTests(t);return f(e)}catch(e){return p(y(e))}}async generateTestData(t){try{let e=await this.testDataGenerator.generateTestData(t);return f(e)}catch(e){return p(y(e))}}async generateTestsForFile(t,e,r,i,n,s){let a=this.getTestFilePath(t,r),o=[],c=await this.findApplicablePatterns(t,i);o.push(...c.map(P=>P.name));let l=null,d="";try{d=Gl.readFileSync(t,"utf-8"),l=await this.analyzeSourceCode(d,t)}catch{}let m,g;this.memory&&d&&await this.hasKGVectors()&&(m=await this.queryKGDependencies(t,d),g=await this.queryKGSimilarCode(d));let h=this.generatorFactory.create(r),b=this.extractModuleName(t),w=s?.importPathOverrides?.[t]??this.getImportPath(t),C={moduleName:b,importPath:w,testType:e,patterns:c,analysis:l??void 0,dependencies:m,similarCode:g},S=h.generateTests(C);this.isLLMEnhancementAvailable()&&d&&(S=await this.enhanceTestWithLLM(S,d,l,C));let k={id:v(),name:`${b} tests`,sourceFile:t,testFile:a,testCode:S,type:e,assertions:this.countAssertions(S),language:n,framework:r,llmEnhanced:this.isLLMEnhancementAvailable()};if(s?.compileValidation&&n)try{let P=await zl.validate(S,n,s.projectRoot);k.compilationValidated=P.compiles,P.compiles||(k.compilationErrors=P.errors.map(O=>O.message))}catch{}return this.qualityGate&&(k.qualityGateResult=this.qualityGate.validate(S,t,d||void 0)),f({tests:[k],patternsUsed:o})}async generateTestForLines(t,e,r){if(e.length===0)return null;let i=v(),n=this.getTestFilePath(t,r),s=this.extractModuleName(t),a=this.getImportPath(t),c=this.generatorFactory.create(r).generateCoverageTests(s,a,e);return{id:i,name:`Coverage test for lines ${e[0]}-${e[e.length-1]}`,sourceFile:t,testFile:n,testCode:c,type:"unit",assertions:this.countAssertions(c)}}async analyzeSourceCode(t,e){let r=ri.extname(e),i=rt(r);if(i&&i!=="typescript"&&i!=="javascript"){let c=await Or.parseFile(t,e,i);if(c)return nt.convertParsedFile(c)}let n=x.createSourceFile(ri.basename(e),t,x.ScriptTarget.Latest,!0,x.ScriptKind.TS),s=[],a=[],o=c=>{if(x.isFunctionDeclaration(c)&&c.name)s.push(this.extractFunctionInfo(c,n));else if(x.isVariableStatement(c)){for(let l of c.declarationList.declarations)if(x.isVariableDeclaration(l)&&l.initializer&&(x.isArrowFunction(l.initializer)||x.isFunctionExpression(l.initializer))){let d=l.name.getText(n);s.push(this.extractArrowFunctionInfo(d,l.initializer,n,c))}}else x.isClassDeclaration(c)&&c.name&&a.push(this.extractClassInfo(c,n));x.forEachChild(c,o)};return x.forEachChild(n,o),{functions:s,classes:a}}extractFunctionInfo(t,e){let r=t.name?.getText(e)||"anonymous",i=this.extractParameters(t.parameters,e),n=t.type?.getText(e),s=t.modifiers?.some(l=>l.kind===x.SyntaxKind.AsyncKeyword)??!1,a=t.modifiers?.some(l=>l.kind===x.SyntaxKind.ExportKeyword)??!1,{line:o}=e.getLineAndCharacterOfPosition(t.getStart(e)),{line:c}=e.getLineAndCharacterOfPosition(t.getEnd());return{name:r,parameters:i,returnType:n,isAsync:s,isExported:a,complexity:this.calculateComplexity(t),startLine:o+1,endLine:c+1,body:t.body?.getText(e)}}extractArrowFunctionInfo(t,e,r,i){let n=this.extractParameters(e.parameters,r),s=e.type?.getText(r),a=e.modifiers?.some(d=>d.kind===x.SyntaxKind.AsyncKeyword)??!1,o=x.isVariableStatement(i)&&(i.modifiers?.some(d=>d.kind===x.SyntaxKind.ExportKeyword)??!1),{line:c}=r.getLineAndCharacterOfPosition(e.getStart(r)),{line:l}=r.getLineAndCharacterOfPosition(e.getEnd());return{name:t,parameters:n,returnType:s,isAsync:a,isExported:o,complexity:this.calculateComplexity(e),startLine:c+1,endLine:l+1,body:e.body?.getText(r)}}extractClassInfo(t,e){let r=t.name?.getText(e)||"AnonymousClass",i=[],n=[],s=!1,a,o=t.modifiers?.some(c=>c.kind===x.SyntaxKind.ExportKeyword)??!1;for(let c of t.members)if(x.isMethodDeclaration(c)){let l=c.name.getText(e),d=this.extractParameters(c.parameters,e),m=c.type?.getText(e),g=c.modifiers?.some(w=>w.kind===x.SyntaxKind.AsyncKeyword)??!1,{line:h}=e.getLineAndCharacterOfPosition(c.getStart(e)),{line:b}=e.getLineAndCharacterOfPosition(c.getEnd());i.push({name:l,parameters:d,returnType:m,isAsync:g,isExported:!1,complexity:this.calculateComplexity(c),startLine:h+1,endLine:b+1,body:c.body?.getText(e)})}else if(x.isConstructorDeclaration(c))s=!0,a=this.extractParameters(c.parameters,e);else if(x.isPropertyDeclaration(c)){let l=c.name.getText(e),d=c.type?.getText(e),m=c.modifiers?.some(h=>h.kind===x.SyntaxKind.PrivateKeyword)??!1,g=c.modifiers?.some(h=>h.kind===x.SyntaxKind.ReadonlyKeyword)??!1;n.push({name:l,type:d,isPrivate:m,isReadonly:g})}return{name:r,methods:i,properties:n,isExported:o,hasConstructor:s,constructorParams:a}}extractParameters(t,e){let r=0,i=0;return t.map(n=>{let s=n.name.getText(e),a=n.type?.getText(e);return x.isObjectBindingPattern(n.name)?(r++,s=r>1?`options${r}`:"options",a||(a=`{ ${n.name.elements.map(c=>`${c.name.getText(e)}: unknown`).join(", ")} }`)):x.isArrayBindingPattern(n.name)&&(i++,s=i>1?`items${i}`:"items",a||(a="unknown[]")),{name:s,type:a,optional:n.questionToken!==void 0,defaultValue:n.initializer?.getText(e)}})}calculateComplexity(t){let e=1,r=i=>{switch(i.kind){case x.SyntaxKind.IfStatement:case x.SyntaxKind.ForStatement:case x.SyntaxKind.ForInStatement:case x.SyntaxKind.ForOfStatement:case x.SyntaxKind.WhileStatement:case x.SyntaxKind.DoStatement:case x.SyntaxKind.CaseClause:case x.SyntaxKind.CatchClause:case x.SyntaxKind.ConditionalExpression:e++;break;case x.SyntaxKind.BinaryExpression:{let n=i;(n.operatorToken.kind===x.SyntaxKind.AmpersandAmpersandToken||n.operatorToken.kind===x.SyntaxKind.BarBarToken)&&e++;break}}x.forEachChild(i,r)};return x.forEachChild(t,r),e}async hasKGVectors(){try{let t=new Array(384).fill(0);return t[0]=1,(await this.memory.vectorSearch(t,1)).length>0}catch{return!1}}async queryKGDependencies(t,e){try{let r=[],i=[],n=[],s=[],a=e.matchAll(/(?:import|from)\s+['"]([^'"]+)['"]/g);for(let m of a)r.push(m[1]);if(t.endsWith(".py")){let m=e.matchAll(/(?:^|\n)\s*(?:from\s+(\S+)\s+import|import\s+(\S+))/g);for(let g of m){let h=g[1]||g[2];h&&/^[a-zA-Z_][\w.]*$/.test(h)&&r.push(h)}}let l=t.replace(/\\/g,"/").split("/").pop()?.replace(/\.(ts|js|tsx|jsx|py)$/,"")||"",d=await this.memory.search(`code-intelligence:kg:node:*${l}*`,50);for(let m of d){if(!m.includes(l))continue;let g=m.split(":"),h=g[g.length-2],b=g[g.length-1];h==="function"&&n.push(b)}return r.length===0&&i.length===0&&n.length===0&&s.length===0?void 0:{imports:r,importedBy:i,callees:n,callers:s}}catch{return}}async queryKGSimilarCode(t){try{let e=this.generatePseudoEmbedding(t),r=await this.memory.vectorSearch(e,5);if(r.length===0)return;let i=[];for(let n of r){if(n.score<.1)continue;let s=n.metadata,a=s?.file||n.key,o=s?.name||s?.type||n.key.split(":").pop()||"";i.push({file:a,snippet:o,score:n.score})}return i.length>0?{snippets:i}:void 0}catch{return}}generatePseudoEmbedding(t){let r=new Array(384).fill(0),i=t.split(/[^a-zA-Z0-9_$]+/).filter(s=>s.length>1);for(let s=0;s<i.length;s++){let a=i[s];for(let o=0;o<a.length&&o<r.length;o++)r[(s+o)%384]+=a.charCodeAt(o)/1e3}let n=Math.sqrt(r.reduce((s,a)=>s+a*a,0));if(n>0)for(let s=0;s<384;s++)r[s]/=n;return r}getCodeFenceLanguage(t){try{let{FRAMEWORK_TO_LANGUAGE:e}=(Zt(),Jt(Il)),r=e?.[t];if(r){let i=ql(r);if(i)return i.codeFenceLanguage}}catch{}return"typescript"}convertParsedToCodeAnalysis(t){return nt.convertParsedFile(t)}async findApplicablePatterns(t,e){let r=[];try{let{getUnifiedMemory:i}=await import("./unified-memory-SAIRUPOI.js"),n=i().getDatabase();for(let o of e){let c=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2056
2056
  FROM qe_patterns WHERE id = ? OR name = ? LIMIT 1`).get(o,o);c&&r.push({id:c.id,name:c.name,structure:c.pattern_type,examples:c.usage_count,applicability:c.quality_score})}let s=t.split(".").pop()||"",a=n.prepare(`SELECT id, name, description, pattern_type, usage_count, quality_score
2057
2057
  FROM qe_patterns
2058
2058
  WHERE qe_domain = 'test-generation'
@@ -2142,7 +2142,7 @@ Individual assessments:`),t.forEach(s=>{let a=this.countsAsAgreement(s)?"\u2713
2142
2142
  created_at TEXT DEFAULT (datetime('now')),
2143
2143
  updated_at TEXT DEFAULT (datetime('now'))
2144
2144
  );
2145
- `,Ro={loadOnInit:!0,autoSaveInterval:0,maxPatternsToLoad:1e4,enableCrossProcessSharing:!0},In=class{baseEngine;config;persistence=null;db=null;prepared=new Map;initialized=!1;initPromise=null;pendingSaves=new Map;saveTimer=null;serverClient=null;constructor(t){this.config={...Ro,...t},this.baseEngine=new gl(t),this.serverClient=t.serverClient??null}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{this.persistence=Ji(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureSchema(),this.prepareStatements(),this.config.loadOnInit&&await this.loadPatterns();let{isSONAThreeLoopEnabled:t}=await import("./feature-flags-6ALWBTHS.js");if(t()){this.baseEngine.initThreeLoopEngine(),this.baseEngine.setFisherPersistence((r,i,n,s,a)=>{this.saveFisherMatrix(r,i,n,s,a)},this.config.domain);let e=this._loadFisherMatrixUnsafe(this.config.domain);if(e){let r=this.baseEngine.getThreeLoopEngine();r&&(r.restoreFisher({fisherDiagonal:e.fisherDiagonal,optimalParams:e.optimalParams,baseWeights:e.baseWeights,requestCount:e.requestCount}),kn.info("Three-loop engine restored Fisher state from SQLite",{domain:this.config.domain,requestCount:e.requestCount,taskBoundaries:e.taskBoundaries}))}kn.info("Three-loop engine initialized with Fisher persistence",{domain:this.config.domain})}this.initialized=!0,console.log(`[PersistentSONAEngine] Initialized: domain=${this.config.domain}`)}catch(t){throw this.initPromise=null,new Error(`Failed to initialize PersistentSONAEngine: ${T(t)}`)}}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sona_patterns'").get()||(console.log("[PersistentSONAEngine] Creating sona_patterns table"),this.db.exec(su)),this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sona_fisher_matrices'").get()||(console.log("[PersistentSONAEngine] Creating sona_fisher_matrices table"),this.db.exec(au))}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("getById",this.db.prepare("SELECT * FROM sona_patterns WHERE id = ?")),this.prepared.set("getByDomain",this.db.prepare(`
2145
+ `,Ro={loadOnInit:!0,autoSaveInterval:0,maxPatternsToLoad:1e4,enableCrossProcessSharing:!0},In=class{baseEngine;config;persistence=null;db=null;prepared=new Map;initialized=!1;initPromise=null;pendingSaves=new Map;saveTimer=null;serverClient=null;constructor(t){this.config={...Ro,...t},this.baseEngine=new gl(t),this.serverClient=t.serverClient??null}async initialize(){if(!this.initialized)return this.initPromise||(this.initPromise=this._doInitialize()),this.initPromise}async _doInitialize(){if(!this.initialized)try{this.persistence=Ji(),this.persistence.isInitialized()||await this.persistence.initialize(),this.db=this.persistence.getDatabase(),this.ensureSchema(),this.prepareStatements(),this.config.loadOnInit&&await this.loadPatterns();let{isSONAThreeLoopEnabled:t}=await import("./feature-flags-3WIZC67K.js");if(t()){this.baseEngine.initThreeLoopEngine(),this.baseEngine.setFisherPersistence((r,i,n,s,a)=>{this.saveFisherMatrix(r,i,n,s,a)},this.config.domain);let e=this._loadFisherMatrixUnsafe(this.config.domain);if(e){let r=this.baseEngine.getThreeLoopEngine();r&&(r.restoreFisher({fisherDiagonal:e.fisherDiagonal,optimalParams:e.optimalParams,baseWeights:e.baseWeights,requestCount:e.requestCount}),kn.info("Three-loop engine restored Fisher state from SQLite",{domain:this.config.domain,requestCount:e.requestCount,taskBoundaries:e.taskBoundaries}))}kn.info("Three-loop engine initialized with Fisher persistence",{domain:this.config.domain})}this.initialized=!0,console.log(`[PersistentSONAEngine] Initialized: domain=${this.config.domain}`)}catch(t){throw this.initPromise=null,new Error(`Failed to initialize PersistentSONAEngine: ${T(t)}`)}}ensureSchema(){if(!this.db)throw new Error("Database not initialized");this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sona_patterns'").get()||(console.log("[PersistentSONAEngine] Creating sona_patterns table"),this.db.exec(su)),this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sona_fisher_matrices'").get()||(console.log("[PersistentSONAEngine] Creating sona_fisher_matrices table"),this.db.exec(au))}prepareStatements(){if(!this.db)throw new Error("Database not initialized");this.prepared.set("getById",this.db.prepare("SELECT * FROM sona_patterns WHERE id = ?")),this.prepared.set("getByDomain",this.db.prepare(`
2146
2146
  SELECT * FROM sona_patterns
2147
2147
  WHERE domain = ?
2148
2148
  ORDER BY confidence DESC, updated_at DESC
@@ -2298,9 +2298,9 @@ expect(result).toBeDefined();`,effort:"medium"}),e.push({action:"Add error bound
2298
2298
  clearCache();
2299
2299
  });`,effort:"medium"}),e.push({action:"Remove inter-test dependencies",description:"Each test should set up its own required state",effort:"high"});break;case"unknown":e.push({action:"Add detailed logging",description:"Log test state at key points to identify patterns",effort:"low"}),e.push({action:"Run in isolation",description:"Execute test alone to determine if it is a test interaction issue",effort:"low"});break}return e}determinePriority(t){return t.confidence>.8&&t.pattern!=="unknown"?"high":t.confidence>.5?"medium":"low"}hasDurationSpikes(t){let e=t.map(n=>n.duration),r=this.average(e),i=this.standardDeviation(e);return e.some(n=>n>r+2*i)}average(t){return t.length===0?0:t.reduce((e,r)=>e+r,0)/t.length}standardDeviation(t){let e=this.average(t),r=t.map(i=>(i-e)**2);return Math.sqrt(this.average(r))}async storeReport(t){let e=v();await this.memory.set(`flaky-report:${e}`,t,{namespace:"test-execution",persist:!0})}};M();import{spawn as Yp}from"node:child_process";import{existsSync as Bn,readFileSync as Xp}from"node:fs";A();H();se();var Zp={simulateForTesting:!1,simulatedRetrySuccessRate:ar.DEFAULT_FLAKY_PASS_RATE,enableJitter:!1,maxJitterPercent:ar.RETRY_PASS_RATE_VARIATION,testRunner:"auto",testTimeout:je.DEFAULT_TEST_TIMEOUT_MS,npxPath:"npx"},eg=R.create("test-execution/retry-handler"),qn=class{constructor(t,e={}){this.memory=t;this.config={...Zp,...e}}memory;retryHistory=new Map;retryPolicies=new Map;runStats=new Map;config;defaultPolicy={maxRetries:3,backoff:"exponential",baseDelay:1e3,maxDelay:3e4,retryOn:[],noRetryOn:[{type:"error_pattern",pattern:"SyntaxError"},{type:"error_pattern",pattern:"TypeError"}]};async shouldRetry(t,e,r){let i=await this.getRetryPolicy(t);if(e>=i.maxRetries)return!1;for(let n of i.noRetryOn)if(this.matchesCondition(n,r))return!1;return i.retryOn.length>0?i.retryOn.some(s=>this.matchesCondition(s,r)):!0}async executeWithRetry(t){let{runId:e,failedTests:r,maxRetries:i,backoff:n,baseDelay:s=1e3,maxDelay:a=3e4,onRetry:o}=t;try{let c={runId:e,totalRetries:0,successful:0,failed:0,flakyDetected:[],startTime:Date.now()},l=[],d=[],m=[];for(let h of r){let b=await this.retryTest(h,i,n,s,a,o);c.totalRetries+=b.attempts,b.passed?(l.push(h.testId),c.successful++,b.attempts>0&&m.push(h.testId)):(d.push(h.testId),c.failed++),await this.recordRetry(h.testId,b)}c.flakyDetected=m,c.endTime=Date.now(),this.runStats.set(e,c),await this.memory.set(`retry-stats:${e}`,c,{namespace:"test-execution",persist:!0});let g={originalFailed:r.length,retried:c.totalRetries,nowPassing:l.length,stillFailing:d.length,flakyDetected:m};return f(g)}catch(c){return p(y(c))}}async getRetryStats(t){try{if(t){let r=this.runStats.get(t);if(!r){let i=await this.memory.get(`retry-stats:${t}`);return i?f(this.convertToRetryStatistics([i])):p(new Error(`No retry stats found for run: ${t}`))}return f(this.convertToRetryStatistics([r]))}let e=Array.from(this.runStats.values());return f(this.convertToRetryStatistics(e))}catch(e){return p(y(e))}}async setRetryPolicy(t,e){this.retryPolicies.set(t,e),await this.memory.set(`retry-policy:${t}`,e,{namespace:"test-execution",persist:!0})}async getRetryPolicy(t){let e=this.retryPolicies.get(t);if(e)return e;let r=await this.memory.get(`retry-policy:${t}`);return r?(this.retryPolicies.set(t,r),r):this.defaultPolicy}matchesCondition(t,e){switch(t.type){case"error_pattern":return e.includes(t.pattern)||new RegExp(t.pattern,"i").test(e);case"exit_code":return e.includes(`exit code ${t.code}`);case"flakiness_score":return!1;case"custom":return!1;default:return!1}}async retryTest(t,e,r,i,n,s){let a=0,o=t.error;for(;a<e&&await this.shouldRetry(t.testId,a,o);){let l=this.calculateDelay(a,r,i,n);await this.sleep(l),s&&s(t.testId,a+1),a++;let d=await this.executeTest(t);if(d.passed)return{testId:t.testId,passed:!0,attempts:a,finalError:void 0};o=d.error??o}return{testId:t.testId,passed:!1,attempts:a,finalError:o}}async executeTest(t){if(this.config.simulateForTesting){let e=L()<this.config.simulatedRetrySuccessRate;return{passed:e,error:e?void 0:t.error}}return this.executeRealTest(t)}async executeRealTest(t){let e=t.file,r=t.testName,i=this.config.cwd??process.cwd();if(!Bn(e))throw new Error(`Test file not found: ${e}. Cannot retry non-existent test file.`);let n=await this.detectTestRunner(i);if(!n)throw new Error(`No test runner detected or configured. Install vitest, jest, or mocha, or configure testRunner in RetryHandlerConfig. Cannot execute retry for: ${e}`);let{command:s,args:a}=this.buildTestCommand(n,e,r);return this.spawnTestProcess(s,a,i)}async detectTestRunner(t){if(this.config.testRunner!=="auto")return this.config.testRunner;let e=["vitest.config.ts","vitest.config.js","vitest.config.mts","vitest.config.mjs","vite.config.ts","vite.config.js"];for(let i of e)if(Bn(`${t}/${i}`))return"vitest";let r=["jest.config.ts","jest.config.js","jest.config.json","jest.config.mjs"];for(let i of r)if(Bn(`${t}/${i}`))return"jest";try{let i=`${t}/package.json`;if(Bn(i)){let n=Xp(i,"utf-8"),s=E(n),a=s?.scripts?.test??"";if(a.includes("vitest"))return"vitest";if(a.includes("jest"))return"jest";if(a.includes("mocha"))return"mocha";let o=s?.devDependencies??{};if("vitest"in o)return"vitest";if("jest"in o)return"jest";if("mocha"in o)return"mocha"}}catch{eg.debug("package.json read failed:")}return null}buildTestCommand(t,e,r){let i=this.config.npxPath;switch(t){case"vitest":let n=["vitest","run","--reporter=json",e];return r&&n.push("-t",r),{command:i,args:n};case"jest":let s=["jest","--json","--testPathPattern",e];return r&&s.push("-t",r),{command:i,args:s};case"mocha":let a=["mocha","--reporter","json",e];return r&&a.push("--grep",r),{command:i,args:a};default:throw new Error(`Unsupported test runner: ${t}`)}}spawnTestProcess(t,e,r){return new Promise((i,n)=>{let s=this.config.testTimeout,a="",o="",c=!1,l=Yp(t,e,{cwd:r,env:{...process.env,FORCE_COLOR:"0",CI:"true"}}),d=setTimeout(()=>{c=!0,l.kill("SIGTERM"),setTimeout(()=>l.kill("SIGKILL"),1e3)},s);l.stdout?.on("data",m=>{a+=m.toString()}),l.stderr?.on("data",m=>{o+=m.toString()}),l.on("close",m=>{if(clearTimeout(d),c){n(new Error(`Test execution timed out after ${s}ms for command: ${t} ${e.join(" ")}`));return}let g=this.parseTestResult(m,a,o);i(g)}),l.on("error",m=>{clearTimeout(d),n(new Error(`Failed to spawn test process: ${m.message}. Command: ${t} ${e.join(" ")}. Ensure the test runner is installed and accessible.`))})})}parseTestResult(t,e,r){if(t===0)return{passed:!0};try{let n=e.match(/\{[\s\S]*"testResults"[\s\S]*\}/);if(n){let o=E(n[0]);return o.success===!0||o.numFailedTests===0?{passed:!0}:{passed:!1,error:o.testResults?.[0]?.assertionResults?.find(l=>l.status==="failed")?.failureMessages?.join(`
2300
2300
  `)??`Test failed with exit code ${t}`}}let s=e.match(/\{[\s\S]*"numFailedTests"[\s\S]*\}/);if(s){let o=E(s[0]);return o.success===!0||o.numFailedTests===0?{passed:!0}:{passed:!1,error:o.testResults?.[0]?.assertionResults?.find(l=>l.status==="failed")?.failureMessages?.join(`
2301
- `)??`Test failed with exit code ${t}`}}let a=e.match(/\{[\s\S]*"stats"[\s\S]*"failures"[\s\S]*\}/);if(a){let o=E(a[0]);return o.stats?.failures===0?{passed:!0}:{passed:!1,error:o.failures?.[0]?.err?.message??`Test failed with exit code ${t}`}}}catch{}return{passed:!1,error:(r||e||`Test failed with exit code ${t}`).substring(0,1e3)}}calculateDelay(t,e,r,i){let n;switch(e){case"constant":n=r;break;case"linear":n=r*(t+1);break;case"exponential":n=r*Math.pow(2,t);break;default:n=r}if(this.config.enableJitter){let s=n*this.config.maxJitterPercent*L();n+=s}return Math.min(n,i)}sleep(t){return new Promise(e=>setTimeout(e,t))}async recordRetry(t,e){let r=this.retryHistory.get(t)??[];r.push({testId:e.testId,attempts:e.attempts,passed:e.passed,error:e.finalError,timestamp:new Date}),r.length>50&&r.shift(),this.retryHistory.set(t,r),await this.memory.set(`retry-history:${t}`,r,{namespace:"test-execution",persist:!0})}convertToRetryStatistics(t){let e=new Map,r=0,i=0,n=0,s=0,a=0;for(let d of t)r+=d.totalRetries,i+=d.successful,n+=d.failed,s+=d.totalRetries,d.successful>0&&(a+=d.successful);let o=i+n,c=o>0?r/o:0,l=a>0?s/a:0;return{totalRetries:r,successfulRetries:i,failedRetries:n,averageAttemptsToPass:l,retryRate:c,testStats:e}}};A();var It={NAVIGATE:"navigate",CLICK:"click",TYPE:"type",WAIT:"wait",ASSERT:"assert",SCREENSHOT:"screenshot",A11Y_CHECK:"a11y-check"};function Gn(u){return u.type===It.NAVIGATE}function Hn(u){return u.type===It.CLICK}function Wn(u){return u.type===It.TYPE}function jn(u){return u.type===It.WAIT}function Un(u){return u.type===It.ASSERT}function Qn(u){return u.type===It.SCREENSHOT}function Kn(u){return u.type===It.A11Y_CHECK}function Jn(u){let t=Math.min(1,u.failureRate??0),e=Math.min(1,u.flakinessScore??0),r=u.complexity??.5,i=1-(u.coverage??0)/100,n=u.businessCriticality??.5,a=Math.max(0,1-(u.estimatedDuration??0)/6e4),o=10080*60*1e3,c=Math.max(0,1-(u.timeSinceModification??0)/o),l=Math.min(1,(u.dependencyCount??0)/10);return{failureProbability:t,flakiness:e,complexity:r,coverageGap:i,criticality:n,speed:a,age:c,dependencyComplexity:l}}function fu(u){return[u.failureProbability,u.flakiness,u.complexity,u.coverageGap,u.criticality,u.speed,u.age,u.dependencyComplexity]}function Po(u){return{critical:100,high:75,standard:50,low:25,defer:0}[u]}function ko(u){return{critical:"p0",high:"p1",standard:"p2",low:"p3",defer:"p3"}[u]}function Io(u,t){let e=t.failedEarly?.5:0,r=u.availableTime>0?Math.max(0,1-t.executionTime/u.availableTime)*.3:0,i=t.coverageImproved?.2:0,n=t.flakyDetected?.1:0,s=e+r+i+n;return{earlyDetection:e,timeEfficiency:r,coverageGain:i,flakinessReduction:n,total:s}}function Yn(u,t){let e=Jn(t);return{id:u,features:fu(e),testId:u,testType:t.testType??"unit",priority:t.priority??t.assignedPriority??"p2",complexity:t.complexity??.5,domain:t.domain??"test-execution",dependencies:t.dependencies??[],estimatedDuration:t.estimatedDuration??5e3,coverage:t.coverage??0,failureHistory:t.failureHistory??[],filePath:t.filePath,testName:t.testName,failureRate:t.failureRate??0,flakinessScore:t.flakinessScore??0,executionCount:t.executionCount??0,timeSinceModification:t.timeSinceModification??0,businessCriticality:t.businessCriticality??.5,dependencyCount:t.dependencyCount??0,assignedPriority:t.assignedPriority??t.priority??"p2",timestamp:new Date,metadata:{...t,features:e}}}var wg={enableDT:!0,minTrajectoriesForDT:5,enableHeuristicFallback:!0,minConfidence:.4,enableAutoTraining:!0,trainingInterval:10,contextLength:10,embeddingDim:384},Xn=class{constructor(t,e={}){this.memory=t;this.config={...wg,...e},this.decisionTransformer=new sr({contextLength:this.config.contextLength,embeddingDim:this.config.embeddingDim})}memory;decisionTransformer;config;executionHistory=new Map;executionsSinceLastTraining=0;async initialize(){await this.loadHistory(),await this.loadModel()}async prioritize(t,e){try{let r=t.map(d=>Yn(d.testId,d)),i=await Promise.all(r.map(d=>this.getPrediction(d))),n=t.map((d,m)=>{let g=i[m],h=g.action.value??"standard";return{testId:d.testId,filePath:d.filePath,testName:d.testName,priority:h,score:Po(h),confidence:g.confidence,reasoning:g.reasoning??"No reasoning provided"}});n.sort((d,m)=>m.score-d.score);let s=this.decisionTransformer.getInfo(),a={trained:s.stats.episode>0,trajectoryCount:this.countTrajectories(),averageReturn:s.stats.averageReward},o=a.trained&&a.trajectoryCount>=this.config.minTrajectoriesForDT?"dt-prediction":this.config.enableHeuristicFallback?"heuristic":"dt-prediction",c=n.reduce((d,m)=>d+m.score,0),l=n.reduce((d,m)=>d+m.confidence,0)/n.length;return f({tests:n,totalScore:c,averageConfidence:l,method:o,learningStatus:a})}catch(r){return p(y(r))}}async recordExecution(t,e,r){let i={testId:t,timestamp:new Date,passed:e.passed,duration:e.duration,priority:ko(e.priority),failureReason:e.passed?void 0:"Test failed"},n=this.executionHistory.get(t)??[];n.push(i),n.length>100&&n.shift(),this.executionHistory.set(t,n),await this.persistHistory();let s=this.createExperience(t,e,r);await this.decisionTransformer.train(s),this.executionsSinceLastTraining++,this.config.enableAutoTraining&&this.executionsSinceLastTraining>=this.config.trainingInterval&&(await this.trainBatch(),this.executionsSinceLastTraining=0)}getStats(){let t=this.executionHistory.size,e=Array.from(this.executionHistory.values()).reduce((r,i)=>r+i.length,0);return{totalTests:t,totalExecutions:e,trajectoryCount:this.countTrajectories(),dtStats:this.decisionTransformer.getStats()}}async exportModel(){return this.decisionTransformer.exportModel()}async importModel(t){await this.decisionTransformer.importModel(t)}async getPrediction(t){try{let e=await this.decisionTransformer.predict(t);return this.config.enableHeuristicFallback&&e.confidence<this.config.minConfidence?this.getHeuristicPrediction(t):{action:e.action,confidence:e.confidence,reasoning:e.reasoning}}catch{return this.getHeuristicPrediction(t)}}getHeuristicPrediction(t){let e=Jn(t),r=0;r+=e.failureProbability*30,r+=e.flakiness*15,r+=e.complexity*10,r+=e.coverageGap*20,r+=e.criticality*15,r+=e.speed*5,r+=e.age*5;let i;return r>60?i="critical":r>45?i="high":r>30?i="standard":r>15?i="low":i="defer",{action:{type:"prioritize",value:i},confidence:.6,reasoning:`Heuristic: score ${r.toFixed(1)} (failure: ${e.failureProbability.toFixed(2)}, flaky: ${e.flakiness.toFixed(2)}, coverage gap: ${e.coverageGap.toFixed(2)})`}}createExperience(t,e,r){let i=this.executionHistory.get(t)??[],n=i[i.length-1],s=Yn(t,{filePath:"",testName:t,failureHistory:i.map(l=>l.passed?1:0),executionCount:i.length,flakinessScore:this.calculateFlakinessScore(i),estimatedDuration:e.duration}),a={type:"prioritize",value:e.priority},o=Io(r,{failedEarly:e.failedEarly??!e.passed,executionTime:e.duration,coverageImproved:e.coverageImproved??!1,flakyDetected:e.flakyDetected??!1}),c={...s};return{state:s,action:a,reward:o.total,nextState:c,done:!0,timestamp:new Date}}calculateFlakinessScore(t){if(t.length<3)return 0;let e=t.slice(-10),r=e.filter(a=>!a.passed).length,i=0;for(let a=1;a<e.length;a++)e[a].passed!==e[a-1].passed&&i++;let n=r/e.length,s=i/Math.max(1,e.length-1);return n*.5+s*.5}async trainBatch(){let t=[];for(let[e,r]of this.executionHistory.entries())for(let i of r){let n={runId:`historical-${e}-${i.timestamp.getTime()}`,totalTests:1,availableTime:6e4,workers:1,mode:"sequential",phase:"regression"},s=this.createExperience(e,{passed:i.passed,duration:i.duration,priority:this.priorityFromEnum(i.priority),failedEarly:!i.passed},n);t.push(s)}t.length>0&&(await this.decisionTransformer.trainBatch(t),await this.saveModel())}priorityFromEnum(t){return{p0:"critical",p1:"high",p2:"standard",p3:"low",p4:"defer"}[t]??"standard"}countTrajectories(){return this.decisionTransformer.getStats().episode}async loadHistory(){try{let t=await this.memory.get("test-prioritizer:history");t&&(this.executionHistory=new Map(Object.entries(t)))}catch{}}async persistHistory(){let t=Object.fromEntries(this.executionHistory);await this.memory.set("test-prioritizer:history",t,{namespace:"test-execution",persist:!0})}async loadModel(){try{let t=await this.memory.get("test-prioritizer:model");t&&await this.decisionTransformer.importModel(t)}catch{}}async saveModel(){let t=await this.decisionTransformer.exportModel();await this.memory.set("test-prioritizer:model",t,{namespace:"test-execution",persist:!0})}};var Do={defaultStepTimeout:On.DEFAULT_STEP_TIMEOUT_MS,defaultRetries:2,retryDelay:On.RETRY_DELAY_MS,screenshotOnFailure:!0,stopOnFirstFailure:!1,pollingInterval:On.POLLING_INTERVAL_MS,maxParallelWorkers:4,verbose:!1,preferAgentBrowser:!0,browserClientType:"auto"},xe=class extends Error{constructor(e,r,i,n){super(e);this.code=r;this.stepId=i;this.cause=n;this.name="E2ERunnerError"}code;stepId;cause},Dt=class extends xe{constructor(t,e,r){super(`Step "${t}" timed out after ${e}ms`,"STEP_TIMEOUT",t,r),this.name="StepTimeoutError"}},Ue=class extends xe{constructor(e,r,i,n,s){super(e,"ASSERTION_FAILED",r,s);this.expected=i;this.actual=n;this.name="AssertionError"}expected;actual};M();var F=class u extends Error{constructor(e,r,i,n){super(e);this.code=r;this.tool=i;this.cause=n;this.name="BrowserError",Object.setPrototypeOf(this,u.prototype)}code;tool;cause},ee=class u extends F{constructor(t,e,r){super(e||"Browser tool is unavailable","BROWSER_UNAVAILABLE",t,r),this.name="BrowserUnavailableError",Object.setPrototypeOf(this,u.prototype)}},ct=class u extends F{constructor(t,e,r){super(`${e} timed out`,"BROWSER_TIMEOUT",t,r),this.name="BrowserTimeoutError",Object.setPrototypeOf(this,u.prototype)}},Mt=class u extends F{constructor(t,e,r){let i=typeof e=="string"?e:JSON.stringify(e);super(`Element not found: ${i}`,"ELEMENT_NOT_FOUND",t,r),this.name="BrowserElementNotFoundError",Object.setPrototypeOf(this,u.prototype)}};H();A();import{spawnSync as Mo,spawn as Cg}from"child_process";var lt=class{config;browserLaunched=!1;constructor(t={}){let e=t.sessionName??"default";if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error(`Invalid sessionName "${e}": must match /^[a-zA-Z0-9_-]+$/`);this.config={sessionName:e,timeout:t.timeout??3e4,headed:t.headed??!1,debug:t.debug??!1}}execute(t,e=[]){let i=["agent-browser",...this.buildArgs(t,e)];this.config.debug&&console.log(`[agent-browser] Executing: npx ${i.join(" ")}`);try{let n=Mo("npx",i,{encoding:"utf-8",timeout:this.config.timeout,maxBuffer:10485760,shell:!1});if(n.error)return{success:!1,error:n.error.message};if(n.status!==0)return{success:!1,error:n.stderr?.trim()||`Exit code: ${n.status}`};let s=n.stdout?.trim()??"";try{return{success:!0,data:E(s)}}catch{return{success:!0,data:s}}}catch(n){return{success:!1,error:T(n)}}}async executeAsync(t,e=[]){return new Promise(r=>{let i=this.buildArgs(t,e);this.config.debug&&console.log(`[agent-browser] Executing async: npx agent-browser ${i.join(" ")}`);let n=Cg("npx",["agent-browser",...i],{timeout:this.config.timeout}),s="",a="";n.stdout?.on("data",o=>{s+=o.toString()}),n.stderr?.on("data",o=>{a+=o.toString()}),n.on("close",o=>{if(o===0)try{let c=E(s.trim());r({success:!0,data:c})}catch{r({success:!0,data:s.trim()})}else r({success:!1,error:a||`Exit code: ${o}`})}),n.on("error",o=>{r({success:!1,error:o.message})})})}open(t){let e=[t];this.config.headed&&e.push("--headed");let r=this.execute("open",e);return r.success&&(this.browserLaunched=!0),r}close(){let t=this.execute("close");return t.success&&(this.browserLaunched=!1),t}terminateDaemon(){try{this.close();let t=this.config.sessionName;try{Mo("pkill",["-f",`agent-browser.*--session[= ]${t}`],{timeout:5e3,stdio:"ignore",shell:!1})}catch(e){console.debug("[CommandExecutor] pkill error:",e instanceof Error?e.message:e)}return this.browserLaunched=!1,{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Failed to terminate daemon"}}}snapshot(t){let e=["--json"];return t?.interactive&&e.push("-i"),t?.compact&&e.push("-c"),t?.depth&&e.push("-d",String(t.depth)),this.execute("snapshot",e)}click(t){return this.execute("click",[t])}fill(t,e){return this.execute("fill",[t,e])}type(t,e){return this.execute("type",[t,e])}getText(t){return this.execute("get",["text",t,"--json"])}isVisible(t){let e=this.execute("is",["visible",t,"--json"]);return e.success&&e.data?{success:!0,data:e.data.success}:{success:!1,error:e.error}}screenshot(t,e){let r=[];return t&&r.push(t),e&&r.push("--full"),t||r.push("--json"),this.execute("screenshot",r)}waitForElement(t,e){let r=[t];return e?this.execute("wait",r):this.execute("wait",r)}waitForText(t){return this.execute("wait",["--text",t])}waitForUrl(t){let e=t.includes("*")?t:`**${t}**`;return this.execute("wait",["--url",e])}waitForNetworkIdle(){return this.execute("wait",["--load","networkidle"])}setDevice(t){return this.execute("set",["device",t])}setViewport(t,e){return this.execute("set",["viewport",String(t),String(e)])}mockRoute(t,e){let r=JSON.stringify(e);return this.execute("network",["route",t,"--body",r])}abortRoute(t){return this.execute("network",["route",t,"--abort"])}clearRoutes(){return this.execute("network",["unroute"])}saveState(t){return this.execute("state",["save",t])}loadState(t){return this.execute("state",["load",t])}startTrace(){return this.execute("trace",["start"])}stopTrace(t){let e=this.execute("trace",["stop",t]);return e.success?{success:!0,data:t}:{success:!1,error:e.error}}eval(t){return this.execute("eval",[t,"--json"])}getSessionName(){return this.config.sessionName}isBrowserLaunched(){return this.browserLaunched}buildArgs(t,e){let r=[];return this.config.sessionName!=="default"&&r.push("--session",this.config.sessionName),r.push(t,...e),r}};function yu(){try{let u=Mo("npx",["agent-browser"],{encoding:"utf-8",timeout:1e4,shell:!1}),t=(u.stdout??"")+(u.stderr??"");return t.includes("agent-browser")&&t.includes("Usage:")}catch{return!1}}H();var vu=new Set(["button","link","textbox","checkbox","radio","combobox","listbox","menuitem","menuitemcheckbox","menuitemradio","option","searchbox","slider","spinbutton","switch","tab","treeitem"]);var Lo=class{parse(t){let e=t.split(`
2301
+ `)??`Test failed with exit code ${t}`}}let a=e.match(/\{[\s\S]*"stats"[\s\S]*"failures"[\s\S]*\}/);if(a){let o=E(a[0]);return o.stats?.failures===0?{passed:!0}:{passed:!1,error:o.failures?.[0]?.err?.message??`Test failed with exit code ${t}`}}}catch{}return{passed:!1,error:(r||e||`Test failed with exit code ${t}`).substring(0,1e3)}}calculateDelay(t,e,r,i){let n;switch(e){case"constant":n=r;break;case"linear":n=r*(t+1);break;case"exponential":n=r*Math.pow(2,t);break;default:n=r}if(this.config.enableJitter){let s=n*this.config.maxJitterPercent*L();n+=s}return Math.min(n,i)}sleep(t){return new Promise(e=>setTimeout(e,t))}async recordRetry(t,e){let r=this.retryHistory.get(t)??[];r.push({testId:e.testId,attempts:e.attempts,passed:e.passed,error:e.finalError,timestamp:new Date}),r.length>50&&r.shift(),this.retryHistory.set(t,r),await this.memory.set(`retry-history:${t}`,r,{namespace:"test-execution",persist:!0})}convertToRetryStatistics(t){let e=new Map,r=0,i=0,n=0,s=0,a=0;for(let d of t)r+=d.totalRetries,i+=d.successful,n+=d.failed,s+=d.totalRetries,d.successful>0&&(a+=d.successful);let o=i+n,c=o>0?r/o:0,l=a>0?s/a:0;return{totalRetries:r,successfulRetries:i,failedRetries:n,averageAttemptsToPass:l,retryRate:c,testStats:e}}};A();var It={NAVIGATE:"navigate",CLICK:"click",TYPE:"type",WAIT:"wait",ASSERT:"assert",SCREENSHOT:"screenshot",A11Y_CHECK:"a11y-check"};function Gn(u){return u.type===It.NAVIGATE}function Hn(u){return u.type===It.CLICK}function Wn(u){return u.type===It.TYPE}function jn(u){return u.type===It.WAIT}function Un(u){return u.type===It.ASSERT}function Qn(u){return u.type===It.SCREENSHOT}function Kn(u){return u.type===It.A11Y_CHECK}function Jn(u){let t=Math.min(1,u.failureRate??0),e=Math.min(1,u.flakinessScore??0),r=u.complexity??.5,i=1-(u.coverage??0)/100,n=u.businessCriticality??.5,a=Math.max(0,1-(u.estimatedDuration??0)/6e4),o=10080*60*1e3,c=Math.max(0,1-(u.timeSinceModification??0)/o),l=Math.min(1,(u.dependencyCount??0)/10);return{failureProbability:t,flakiness:e,complexity:r,coverageGap:i,criticality:n,speed:a,age:c,dependencyComplexity:l}}function fu(u){return[u.failureProbability,u.flakiness,u.complexity,u.coverageGap,u.criticality,u.speed,u.age,u.dependencyComplexity]}function Po(u){return{critical:100,high:75,standard:50,low:25,defer:0}[u]}function ko(u){return{critical:"p0",high:"p1",standard:"p2",low:"p3",defer:"p3"}[u]}function Io(u,t){let e=t.failedEarly?.5:0,r=u.availableTime>0?Math.max(0,1-t.executionTime/u.availableTime)*.3:0,i=t.coverageImproved?.2:0,n=t.flakyDetected?.1:0,s=e+r+i+n;return{earlyDetection:e,timeEfficiency:r,coverageGain:i,flakinessReduction:n,total:s}}function Yn(u,t){let e=Jn(t);return{id:u,features:fu(e),testId:u,testType:t.testType??"unit",priority:t.priority??t.assignedPriority??"p2",complexity:t.complexity??.5,domain:t.domain??"test-execution",dependencies:t.dependencies??[],estimatedDuration:t.estimatedDuration??5e3,coverage:t.coverage??0,failureHistory:t.failureHistory??[],filePath:t.filePath,testName:t.testName,failureRate:t.failureRate??0,flakinessScore:t.flakinessScore??0,executionCount:t.executionCount??0,timeSinceModification:t.timeSinceModification??0,businessCriticality:t.businessCriticality??.5,dependencyCount:t.dependencyCount??0,assignedPriority:t.assignedPriority??t.priority??"p2",timestamp:new Date,metadata:{...t,features:e}}}var wg={enableDT:!0,minTrajectoriesForDT:5,enableHeuristicFallback:!0,minConfidence:.4,enableAutoTraining:!0,trainingInterval:10,contextLength:10,embeddingDim:384},Xn=class{constructor(t,e={}){this.memory=t;this.config={...wg,...e},this.decisionTransformer=new sr({contextLength:this.config.contextLength,embeddingDim:this.config.embeddingDim})}memory;decisionTransformer;config;executionHistory=new Map;executionsSinceLastTraining=0;async initialize(){await this.loadHistory(),await this.loadModel()}async prioritize(t,e){try{let r=t.map(d=>Yn(d.testId,d)),i=await Promise.all(r.map(d=>this.getPrediction(d))),n=t.map((d,m)=>{let g=i[m],h=g.action.value??"standard";return{testId:d.testId,filePath:d.filePath,testName:d.testName,priority:h,score:Po(h),confidence:g.confidence,reasoning:g.reasoning??"No reasoning provided"}});n.sort((d,m)=>m.score-d.score);let s=this.decisionTransformer.getInfo(),a={trained:s.stats.episode>0,trajectoryCount:this.countTrajectories(),averageReturn:s.stats.averageReward},o=a.trained&&a.trajectoryCount>=this.config.minTrajectoriesForDT?"dt-prediction":this.config.enableHeuristicFallback?"heuristic":"dt-prediction",c=n.reduce((d,m)=>d+m.score,0),l=n.reduce((d,m)=>d+m.confidence,0)/n.length;return f({tests:n,totalScore:c,averageConfidence:l,method:o,learningStatus:a})}catch(r){return p(y(r))}}async recordExecution(t,e,r){let i={testId:t,timestamp:new Date,passed:e.passed,duration:e.duration,priority:ko(e.priority),failureReason:e.passed?void 0:"Test failed"},n=this.executionHistory.get(t)??[];n.push(i),n.length>100&&n.shift(),this.executionHistory.set(t,n),await this.persistHistory();let s=this.createExperience(t,e,r);await this.decisionTransformer.train(s),this.executionsSinceLastTraining++,this.config.enableAutoTraining&&this.executionsSinceLastTraining>=this.config.trainingInterval&&(await this.trainBatch(),this.executionsSinceLastTraining=0)}getStats(){let t=this.executionHistory.size,e=Array.from(this.executionHistory.values()).reduce((r,i)=>r+i.length,0);return{totalTests:t,totalExecutions:e,trajectoryCount:this.countTrajectories(),dtStats:this.decisionTransformer.getStats()}}async exportModel(){return this.decisionTransformer.exportModel()}async importModel(t){await this.decisionTransformer.importModel(t)}async getPrediction(t){try{let e=await this.decisionTransformer.predict(t);return this.config.enableHeuristicFallback&&e.confidence<this.config.minConfidence?this.getHeuristicPrediction(t):{action:e.action,confidence:e.confidence,reasoning:e.reasoning}}catch{return this.getHeuristicPrediction(t)}}getHeuristicPrediction(t){let e=Jn(t),r=0;r+=e.failureProbability*30,r+=e.flakiness*15,r+=e.complexity*10,r+=e.coverageGap*20,r+=e.criticality*15,r+=e.speed*5,r+=e.age*5;let i;return r>60?i="critical":r>45?i="high":r>30?i="standard":r>15?i="low":i="defer",{action:{type:"prioritize",value:i},confidence:.6,reasoning:`Heuristic: score ${r.toFixed(1)} (failure: ${e.failureProbability.toFixed(2)}, flaky: ${e.flakiness.toFixed(2)}, coverage gap: ${e.coverageGap.toFixed(2)})`}}createExperience(t,e,r){let i=this.executionHistory.get(t)??[],n=i[i.length-1],s=Yn(t,{filePath:"",testName:t,failureHistory:i.map(l=>l.passed?1:0),executionCount:i.length,flakinessScore:this.calculateFlakinessScore(i),estimatedDuration:e.duration}),a={type:"prioritize",value:e.priority},o=Io(r,{failedEarly:e.failedEarly??!e.passed,executionTime:e.duration,coverageImproved:e.coverageImproved??!1,flakyDetected:e.flakyDetected??!1}),c={...s};return{state:s,action:a,reward:o.total,nextState:c,done:!0,timestamp:new Date}}calculateFlakinessScore(t){if(t.length<3)return 0;let e=t.slice(-10),r=e.filter(a=>!a.passed).length,i=0;for(let a=1;a<e.length;a++)e[a].passed!==e[a-1].passed&&i++;let n=r/e.length,s=i/Math.max(1,e.length-1);return n*.5+s*.5}async trainBatch(){let t=[];for(let[e,r]of this.executionHistory.entries())for(let i of r){let n={runId:`historical-${e}-${i.timestamp.getTime()}`,totalTests:1,availableTime:6e4,workers:1,mode:"sequential",phase:"regression"},s=this.createExperience(e,{passed:i.passed,duration:i.duration,priority:this.priorityFromEnum(i.priority),failedEarly:!i.passed},n);t.push(s)}t.length>0&&(await this.decisionTransformer.trainBatch(t),await this.saveModel())}priorityFromEnum(t){return{p0:"critical",p1:"high",p2:"standard",p3:"low",p4:"defer"}[t]??"standard"}countTrajectories(){return this.decisionTransformer.getStats().episode}async loadHistory(){try{let t=await this.memory.get("test-prioritizer:history");t&&(this.executionHistory=new Map(Object.entries(t)))}catch{}}async persistHistory(){let t=Object.fromEntries(this.executionHistory);await this.memory.set("test-prioritizer:history",t,{namespace:"test-execution",persist:!0})}async loadModel(){try{let t=await this.memory.get("test-prioritizer:model");t&&await this.decisionTransformer.importModel(t)}catch{}}async saveModel(){let t=await this.decisionTransformer.exportModel();await this.memory.set("test-prioritizer:model",t,{namespace:"test-execution",persist:!0})}};var Do={defaultStepTimeout:On.DEFAULT_STEP_TIMEOUT_MS,defaultRetries:2,retryDelay:On.RETRY_DELAY_MS,screenshotOnFailure:!0,stopOnFirstFailure:!1,pollingInterval:On.POLLING_INTERVAL_MS,maxParallelWorkers:4,verbose:!1,preferAgentBrowser:!0,browserClientType:"auto"},xe=class extends Error{constructor(e,r,i,n){super(e);this.code=r;this.stepId=i;this.cause=n;this.name="E2ERunnerError"}code;stepId;cause},Dt=class extends xe{constructor(t,e,r){super(`Step "${t}" timed out after ${e}ms`,"STEP_TIMEOUT",t,r),this.name="StepTimeoutError"}},Ue=class extends xe{constructor(e,r,i,n,s){super(e,"ASSERTION_FAILED",r,s);this.expected=i;this.actual=n;this.name="AssertionError"}expected;actual};M();var F=class u extends Error{constructor(e,r,i,n){super(e);this.code=r;this.tool=i;this.cause=n;this.name="BrowserError",Object.setPrototypeOf(this,u.prototype)}code;tool;cause},te=class u extends F{constructor(t,e,r){super(e||"Browser tool is unavailable","BROWSER_UNAVAILABLE",t,r),this.name="BrowserUnavailableError",Object.setPrototypeOf(this,u.prototype)}},ct=class u extends F{constructor(t,e,r){super(`${e} timed out`,"BROWSER_TIMEOUT",t,r),this.name="BrowserTimeoutError",Object.setPrototypeOf(this,u.prototype)}},Mt=class u extends F{constructor(t,e,r){let i=typeof e=="string"?e:JSON.stringify(e);super(`Element not found: ${i}`,"ELEMENT_NOT_FOUND",t,r),this.name="BrowserElementNotFoundError",Object.setPrototypeOf(this,u.prototype)}};H();A();import{spawnSync as Mo,spawn as Cg}from"child_process";var lt=class{config;browserLaunched=!1;constructor(t={}){let e=t.sessionName??"default";if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error(`Invalid sessionName "${e}": must match /^[a-zA-Z0-9_-]+$/`);this.config={sessionName:e,timeout:t.timeout??3e4,headed:t.headed??!1,debug:t.debug??!1}}execute(t,e=[]){let i=["agent-browser",...this.buildArgs(t,e)];this.config.debug&&console.log(`[agent-browser] Executing: npx ${i.join(" ")}`);try{let n=Mo("npx",i,{encoding:"utf-8",timeout:this.config.timeout,maxBuffer:10485760,shell:!1});if(n.error)return{success:!1,error:n.error.message};if(n.status!==0)return{success:!1,error:n.stderr?.trim()||`Exit code: ${n.status}`};let s=n.stdout?.trim()??"";try{return{success:!0,data:E(s)}}catch{return{success:!0,data:s}}}catch(n){return{success:!1,error:T(n)}}}async executeAsync(t,e=[]){return new Promise(r=>{let i=this.buildArgs(t,e);this.config.debug&&console.log(`[agent-browser] Executing async: npx agent-browser ${i.join(" ")}`);let n=Cg("npx",["agent-browser",...i],{timeout:this.config.timeout}),s="",a="";n.stdout?.on("data",o=>{s+=o.toString()}),n.stderr?.on("data",o=>{a+=o.toString()}),n.on("close",o=>{if(o===0)try{let c=E(s.trim());r({success:!0,data:c})}catch{r({success:!0,data:s.trim()})}else r({success:!1,error:a||`Exit code: ${o}`})}),n.on("error",o=>{r({success:!1,error:o.message})})})}open(t){let e=[t];this.config.headed&&e.push("--headed");let r=this.execute("open",e);return r.success&&(this.browserLaunched=!0),r}close(){let t=this.execute("close");return t.success&&(this.browserLaunched=!1),t}terminateDaemon(){try{this.close();let t=this.config.sessionName;try{Mo("pkill",["-f",`agent-browser.*--session[= ]${t}`],{timeout:5e3,stdio:"ignore",shell:!1})}catch(e){console.debug("[CommandExecutor] pkill error:",e instanceof Error?e.message:e)}return this.browserLaunched=!1,{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Failed to terminate daemon"}}}snapshot(t){let e=["--json"];return t?.interactive&&e.push("-i"),t?.compact&&e.push("-c"),t?.depth&&e.push("-d",String(t.depth)),this.execute("snapshot",e)}click(t){return this.execute("click",[t])}fill(t,e){return this.execute("fill",[t,e])}type(t,e){return this.execute("type",[t,e])}getText(t){return this.execute("get",["text",t,"--json"])}isVisible(t){let e=this.execute("is",["visible",t,"--json"]);return e.success&&e.data?{success:!0,data:e.data.success}:{success:!1,error:e.error}}screenshot(t,e){let r=[];return t&&r.push(t),e&&r.push("--full"),t||r.push("--json"),this.execute("screenshot",r)}waitForElement(t,e){let r=[t];return e?this.execute("wait",r):this.execute("wait",r)}waitForText(t){return this.execute("wait",["--text",t])}waitForUrl(t){let e=t.includes("*")?t:`**${t}**`;return this.execute("wait",["--url",e])}waitForNetworkIdle(){return this.execute("wait",["--load","networkidle"])}setDevice(t){return this.execute("set",["device",t])}setViewport(t,e){return this.execute("set",["viewport",String(t),String(e)])}mockRoute(t,e){let r=JSON.stringify(e);return this.execute("network",["route",t,"--body",r])}abortRoute(t){return this.execute("network",["route",t,"--abort"])}clearRoutes(){return this.execute("network",["unroute"])}saveState(t){return this.execute("state",["save",t])}loadState(t){return this.execute("state",["load",t])}startTrace(){return this.execute("trace",["start"])}stopTrace(t){let e=this.execute("trace",["stop",t]);return e.success?{success:!0,data:t}:{success:!1,error:e.error}}eval(t){return this.execute("eval",[t,"--json"])}getSessionName(){return this.config.sessionName}isBrowserLaunched(){return this.browserLaunched}buildArgs(t,e){let r=[];return this.config.sessionName!=="default"&&r.push("--session",this.config.sessionName),r.push(t,...e),r}};function yu(){try{let u=Mo("npx",["agent-browser"],{encoding:"utf-8",timeout:1e4,shell:!1}),t=(u.stdout??"")+(u.stderr??"");return t.includes("agent-browser")&&t.includes("Usage:")}catch{return!1}}H();var vu=new Set(["button","link","textbox","checkbox","radio","combobox","listbox","menuitem","menuitemcheckbox","menuitemradio","option","searchbox","slider","spinbutton","switch","tab","treeitem"]);var Lo=class{parse(t){let e=t.split(`
2302
2302
  `),r=[],i=new Map,n=0;for(let a of e){let o=this.parseLine(a);o&&(r.push(o),i.set(o.ref,o),o.depth>n&&(n=o.depth))}this.buildRelationships(r);let s=r.filter(a=>vu.has(a.role.toLowerCase()));return{rawTree:t,elements:r,interactiveElements:s,refMap:i,stats:{totalElements:r.length,interactiveCount:s.length,maxDepth:n},parsedAt:new Date}}parseJson(t){let e=typeof t=="string"?E(t):t;if(e.success&&e.data){let r=e.data.snapshot||e.data,i=e.data.refs||{};return this.parseWithRefs(r,i)}if(typeof e=="string")return this.parse(e);throw new Error("Invalid snapshot JSON format")}parseWithRefs(t,e){let r=[],i=new Map,n=0;for(let[o,c]of Object.entries(e)){let l={ref:o,refWithAt:`@${o}`,role:c.role,name:c.name,attributes:{},depth:0,children:[]};r.push(l),i.set(o,l)}let s=this.parse(t);for(let o of s.elements){let c=i.get(o.ref);c&&(c.text=o.text,c.depth=o.depth,c.level=o.level,o.depth>n&&(n=o.depth))}let a=r.filter(o=>vu.has(o.role.toLowerCase()));return{rawTree:t,elements:r,interactiveElements:a,refMap:i,stats:{totalElements:r.length,interactiveCount:a.length,maxDepth:n},parsedAt:new Date}}parseLine(t){if(!t.trim())return null;let e=this.getIndentLevel(t),r=t.match(/^(\s*-\s*)(\w+)(?:\s+"([^"]*)")?(.*)$/);if(!r)return null;let[,,i,n,s]=r,a=s?.match(/\[ref=(\w+)\]/);if(!a)return null;let o=a[1],c=s?.match(/\[level=(\d+)\]/),l=c?parseInt(c[1],10):void 0,d=s?.match(/\[nth=(\d+)\]/),m=d?parseInt(d[1],10):void 0,g=t.match(/:\s*(.+)$/),h=g?g[1].trim():void 0,b={};return l&&(b.level=String(l)),m!==void 0&&(b.nth=String(m)),{ref:o,refWithAt:`@${o}`,role:i.toLowerCase(),name:n,text:h,level:l,attributes:b,depth:e,children:[]}}getIndentLevel(t){let e=t.match(/^(\s*)/);return e?Math.floor(e[1].length/2):0}buildRelationships(t){let e=[];for(let r of t){for(;e.length>0&&e[e.length-1].depth>=r.depth;)e.pop();if(e.length>0){let i=e[e.length-1];r.parent=i.ref,i.children.push(r.ref)}e.push(r)}}findByRef(t,e){let r=e.startsWith("@")?e.slice(1):e;return t.refMap.get(r)||null}findByRole(t,e){return t.elements.filter(r=>r.role.toLowerCase()===e.toLowerCase())}findByName(t,e,r=!1){return t.elements.filter(i=>i.name?r?i.name===e:i.name.toLowerCase().includes(e.toLowerCase()):!1)}findByText(t,e,r=!1){return t.elements.filter(i=>{let n=i.text||i.name||"";return r?n===e:n.toLowerCase().includes(e.toLowerCase())})}findInteractive(t,e){for(let r of t.interactiveElements)if(!(e.role&&r.role.toLowerCase()!==e.role.toLowerCase())&&!(e.name&&r.name!==e.name)&&!(e.text&&!(r.text||r.name||"").toLowerCase().includes(e.text.toLowerCase())))return r;return null}refToCssSelector(t,e){let r=this.findByRef(t,e);if(!r)return null;let i=r.role,n=r.name;return{button:n?`button:has-text("${n}")`:"button",link:n?`a:has-text("${n}")`:"a",textbox:n?`input[placeholder="${n}"], input[aria-label="${n}"]`:'input[type="text"]',heading:n?`h1:has-text("${n}"), h2:has-text("${n}"), h3:has-text("${n}")`:"h1, h2, h3",checkbox:n?`input[type="checkbox"][aria-label="${n}"]`:'input[type="checkbox"]'}[i]||`[role="${i}"]`}},Fo=null;function bu(){return Fo||(Fo=new Lo),Fo}A();import{execSync as Sg}from"child_process";var Zn=class{constructor(t){this.defaultConfig=t}defaultConfig;sessions=new Map;activeSession=null;sessionCounter=0;async createSession(t){let e=t?.name??this.generateSessionName();if(this.sessions.has(e))throw new Error(`Session "${e}" already exists`);let r=new lt({sessionName:e,headed:t?.headed??this.defaultConfig?.headed??!1,timeout:t?.timeout??this.defaultConfig?.timeout??3e4}),i={name:e,createdAt:new Date,lastActivity:new Date,status:"idle",executor:r};return this.sessions.set(e,i),t?.initialUrl&&r.open(t.initialUrl).success&&(i.currentUrl=t.initialUrl,i.status="active"),this.activeSession||(this.activeSession=e),i}async getOrCreateSession(t,e){let r=this.sessions.get(t);return r||this.createSession({...e,name:t})}getSession(t){return this.sessions.get(t)}getActiveSession(){if(this.activeSession)return this.sessions.get(this.activeSession)}switchSession(t){if(!this.sessions.has(t))throw new Error(`Session "${t}" not found`);this.activeSession=t}listSessions(){return Array.from(this.sessions.values())}listCliSessions(){try{let e=Sg("npx agent-browser session list",{encoding:"utf-8",timeout:5e3}).split(`
2303
- `),r=[];for(let i of e){let n=i.match(/^\s*(?:->)?\s*(\w+)\s*$/);n&&r.push(n[1])}return r}catch{return[]}}async closeSession(t){let e=this.sessions.get(t);if(!e)return{success:!1,error:`Session "${t}" not found`};let r=e.executor.terminateDaemon();if(r.success&&(e.status="closed",this.sessions.delete(t),this.activeSession===t)){let i=Array.from(this.sessions.keys());this.activeSession=i.length>0?i[0]:null}return r}async closeAllSessions(){let t=Array.from(this.sessions.keys());for(let e of t)await this.closeSession(e);this.sessions.clear(),this.activeSession=null}async cleanupIdleSessions(t=300*1e3){let e=Date.now(),r=0;for(let[i,n]of this.sessions)n.status==="idle"&&e-n.lastActivity.getTime()>t&&(await this.closeSession(i),r++);return r}getExecutor(){let t=this.getActiveSession();if(!t)throw new Error("No active session. Create one first.");return t.executor}getSessionExecutor(t){let e=this.sessions.get(t);if(!e)throw new Error(`Session "${t}" not found`);return e.executor}touchSession(t){let e=this.sessions.get(t);e&&(e.lastActivity=new Date)}updateSessionUrl(t,e){let r=this.sessions.get(t);r&&(r.currentUrl=e,r.lastActivity=new Date,r.status="active")}generateSessionName(){return`session-${++this.sessionCounter}-${Date.now().toString(36)}`}getStats(){let t=0,e=0,r=0;for(let i of this.sessions.values())switch(i.status){case"active":t++;break;case"idle":e++;break;case"closed":r++;break}return{totalSessions:this.sessions.size,activeSessions:t,idleSessions:e,closedSessions:r,activeSessionName:this.activeSession}}};H();function gi(u){if(typeof u=="string")return/^@?e\d+$/.test(u)?u.startsWith("@")?u:`@${u}`:u;switch(u.type){case"ref":return u.value.startsWith("@")?u.value:`@${u.value}`;case"css":return u.value;case"xpath":return`xpath=${u.value}`;case"text":return`text=${u.value}`;default:return u.value}}function j(u){return{success:!0,value:u}}function $(u){return{success:!1,error:u}}function es(u){return{id:u.name,tool:"agent-browser",status:u.status,currentUrl:u.currentUrl,createdAt:u.createdAt}}function Rg(u){let t=u.elements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),e=u.interactiveElements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),r=new Map;for(let i of t)r.set(i.ref,i);return{url:u.url??"",title:u.title??"",elements:t,interactiveElements:e,refMap:r,timestamp:u.parsedAt}}var or=class{tool="agent-browser";executor;sessionManager;snapshotParser;config;isLaunched=!1;currentSessionId=null;constructor(t={}){this.config={headed:t.headed??!1,timeout:t.timeout??3e4,debug:t.debug??!1,sessionName:t.sessionName??"default"};let e={sessionName:this.config.sessionName,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug};this.executor=new lt(e),this.sessionManager=new Zn({headed:this.config.headed,timeout:this.config.timeout}),this.snapshotParser=bu()}async launch(t){try{if(this.isLaunched&&this.currentSessionId){let n=this.sessionManager.getSession(this.currentSessionId);if(n)return t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),j(es(n))}if(!await this.isAvailable())return $(new ee("agent-browser","agent-browser CLI is not available"));let r=t?.sessionName??this.config.sessionName,i=await this.sessionManager.createSession({name:r,headed:t?.headless===!1||this.config.headed,timeout:this.config.timeout});return this.currentSessionId=i.name,this.isLaunched=!0,this.executor=new lt({sessionName:i.name,timeout:this.config.timeout,headed:t?.headless===!1||this.config.headed,debug:this.config.debug}),t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),t?.deviceName&&await this.setDevice(t.deviceName),j(es(i))}catch(e){let r=new F(T(e),"LAUNCH_FAILED","agent-browser",e instanceof Error?e:void 0);return $(r)}}async quit(){try{if(this.currentSessionId){let t=await this.sessionManager.closeSession(this.currentSessionId);t.success||this.config.debug&&console.warn(`[agent-browser] Session close warning: ${t.error}`)}if(this.executor)try{this.executor.terminateDaemon()}catch(t){console.debug("[AgentBrowserClient] Daemon termination error:",t instanceof Error?t.message:t)}return this.isLaunched=!1,this.currentSessionId=null,j(void 0)}catch(t){return this.isLaunched=!1,this.currentSessionId=null,$(new F(T(t),"QUIT_FAILED","agent-browser",t instanceof Error?t:void 0))}}async isAvailable(){return yu()}async dispose(){await this.sessionManager.closeAllSessions(),this.isLaunched=!1,this.currentSessionId=null}async navigate(t){let e=Date.now();try{let r=this.executor.open(t);if(!r.success)return $(new F(r.error??"Navigation failed","NAVIGATION_FAILED","agent-browser"));this.currentSessionId&&this.sessionManager.updateSessionUrl(this.currentSessionId,t);let i=this.executor.eval("JSON.stringify({ title: document.title, url: window.location.href })"),n=i.success&&i.data?typeof i.data=="string"?E(i.data):i.data:{title:"",url:t};return j({url:n.url||t,title:n.title||"",success:!0,durationMs:Date.now()-e})}catch(r){return $(new F(T(r),"NAVIGATION_FAILED","agent-browser",r instanceof Error?r:void 0))}}async reload(){try{let t=this.executor.eval("window.location.reload()");return t.success?j(void 0):$(new F(t.error??"Reload failed","RELOAD_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"RELOAD_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goBack(){try{let t=this.executor.eval("window.history.back()");return t.success?j(void 0):$(new F(t.error??"Go back failed","HISTORY_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goForward(){try{let t=this.executor.eval("window.history.forward()");return t.success?j(void 0):$(new F(t.error??"Go forward failed","HISTORY_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async click(t){try{let e=gi(t),r=this.executor.click(e);return r.success?j(void 0):$(new Mt("agent-browser",t,new Error(r.error)))}catch(e){return $(new F(T(e),"CLICK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async fill(t,e){try{let r=gi(t),i=this.executor.fill(r,e);return i.success?j(void 0):$(new Mt("agent-browser",t,new Error(i.error)))}catch(r){return $(new F(T(r),"FILL_FAILED","agent-browser",r instanceof Error?r:void 0))}}async getText(t){try{let e=gi(t),r=this.executor.getText(e);if(!r.success)return $(new Mt("agent-browser",t,new Error(r.error)));let i=r.data;if(i&&typeof i=="object"){let n=i;if("text"in n)i=n.text;else if("data"in n&&typeof n.data=="object"){let s=n.data;"text"in s?i=s.text:"result"in s&&(i=s.result)}else"result"in n&&(i=n.result)}return j(String(i??""))}catch(e){return $(new F(T(e),"GET_TEXT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async isVisible(t){try{let e=gi(t),r=this.executor.isVisible(e);return r.success?j(!!r.data):j(!1)}catch(e){return $(new F(T(e),"VISIBILITY_CHECK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async screenshot(t){try{let e=this.executor.screenshot(t?.path,t?.fullPage);if(!e.success)return $(new F(e.error??"Screenshot failed","SCREENSHOT_FAILED","agent-browser"));let r=this.executor.eval("JSON.stringify({ width: window.innerWidth, height: window.innerHeight })"),i={width:1280,height:720};if(r.success&&r.data){let n=typeof r.data=="string"?E(r.data):r.data;i={width:n.width||1280,height:n.height||720}}return j({base64:t?.path?void 0:String(e.data??""),path:t?.path,format:"png",dimensions:i})}catch(e){return $(new F(T(e),"SCREENSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async evaluate(t){try{let e=this.executor.eval(t);if(!e.success)return $(new F(e.error??"Evaluation failed","EVAL_FAILED","agent-browser"));let r=e.data;if(r&&typeof r=="object"){let i=r;if("data"in i&&i.data&&typeof i.data=="object"){let n=i.data;"result"in n&&(r=n.result)}else"result"in i&&(r=i.result)}return j(r)}catch(e){return $(new F(T(e),"EVAL_FAILED","agent-browser",e instanceof Error?e:void 0))}}async getSnapshot(t){try{let e=this.executor.snapshot({interactive:t?.interactive,depth:t?.depth});if(!e.success)return $(new F(e.error??"Snapshot failed","SNAPSHOT_FAILED","agent-browser"));let r;try{r=this.snapshotParser.parseJson(e.data)}catch{r=this.snapshotParser.parse(String(e.data))}let i=this.executor.eval("window.location.href"),n=this.executor.eval("document.title");return i.success&&(r.url=String(i.data)),n.success&&(r.title=String(n.data)),j(Rg(r))}catch(e){return $(new F(T(e),"SNAPSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async createSession(t){try{let e=await this.sessionManager.createSession({name:t});return j(es(e))}catch(e){return $(new F(T(e),"SESSION_CREATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async switchSession(t){try{return this.sessionManager.switchSession(t),this.currentSessionId=t,this.executor=new lt({sessionName:t,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug}),j(void 0)}catch(e){return $(new F(T(e),"SESSION_SWITCH_FAILED","agent-browser",e instanceof Error?e:void 0))}}async listSessions(){try{let t=this.sessionManager.listSessions();return j(t.map(es))}catch(t){return $(new F(T(t),"SESSION_LIST_FAILED","agent-browser",t instanceof Error?t:void 0))}}async mockRoute(t,e){try{let r={status:e.status??200,body:e.body,headers:e.headers},i=this.executor.mockRoute(t,r);return i.success?j(void 0):$(new F(i.error??"Mock route failed","MOCK_ROUTE_FAILED","agent-browser"))}catch(r){return $(new F(T(r),"MOCK_ROUTE_FAILED","agent-browser",r instanceof Error?r:void 0))}}async abortRoute(t){try{let e=this.executor.abortRoute(t);return e.success?j(void 0):$(new F(e.error??"Abort route failed","ABORT_ROUTE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"ABORT_ROUTE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async clearRoutes(){try{let t=this.executor.clearRoutes();return t.success?j(void 0):$(new F(t.error??"Clear routes failed","CLEAR_ROUTES_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"CLEAR_ROUTES_FAILED","agent-browser",t instanceof Error?t:void 0))}}async setDevice(t){try{let e=this.executor.setDevice(t);return e.success?j(void 0):$(new F(e.error??"Set device failed","SET_DEVICE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"SET_DEVICE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async setViewport(t,e){try{let r=this.executor.setViewport(t,e);return r.success?j(void 0):$(new F(r.error??"Set viewport failed","SET_VIEWPORT_FAILED","agent-browser"))}catch(r){return $(new F(T(r),"SET_VIEWPORT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async saveState(t){try{let e=this.executor.saveState(t);return e.success?j(void 0):$(new F(e.error??"Save state failed","SAVE_STATE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"SAVE_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async loadState(t){try{let e=this.executor.loadState(t);return e.success?j(void 0):$(new F(e.error??"Load state failed","LOAD_STATE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"LOAD_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async waitForElement(t,e){try{let r=gi(t),i=this.executor.waitForElement(r,e);return i.success?j(void 0):$(new ct("agent-browser",`waitForElement(${r})`,new Error(i.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForText(t,e){try{let r=this.executor.waitForText(t);return r.success?j(void 0):$(new ct("agent-browser",`waitForText("${t}")`,new Error(r.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForUrl(t,e){try{let r=this.executor.waitForUrl(t);return r.success?j(void 0):$(new ct("agent-browser",`waitForUrl("${t}")`,new Error(r.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForNetworkIdle(t){try{let e=this.executor.waitForNetworkIdle();return e.success?j(void 0):$(new ct("agent-browser","waitForNetworkIdle",new Error(e.error)))}catch(e){return $(new F(T(e),"WAIT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async startTrace(){try{let t=this.executor.startTrace();return t.success?j(void 0):$(new F(t.error??"Start trace failed","START_TRACE_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"START_TRACE_FAILED","agent-browser",t instanceof Error?t:void 0))}}async stopTrace(t){try{let e=this.executor.stopTrace(t);return e.success?j(e.data??t):$(new F(e.error??"Stop trace failed","STOP_TRACE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"STOP_TRACE_FAILED","agent-browser",e instanceof Error?e:void 0))}}};import{randomUUID as Tu}from"crypto";var ts={persistentContext:!0,cloudflareWaitSeconds:0,resourceBlocking:"functional"};var Tg=new Set(["google-analytics.com","googletagmanager.com","analytics.google.com","hotjar.com","fullstory.com","segment.io","segment.com","mixpanel.com","heap.io","heapanalytics.com","amplitude.com","mouseflow.com","crazyegg.com","optimizely.com","newrelic.com","nr-data.net","sentry.io","bugsnag.com","logrocket.com","clarity.ms","facebook.net","connect.facebook.net"]),Ag=new Set(["doubleclick.net","googlesyndication.com","googleadservices.com","google-analytics.com","adservice.google.com","pagead2.googlesyndication.com","ads.twitter.com","ads-api.twitter.com","adsserver.com","adnxs.com","amazon-adsystem.com","criteo.com","moatads.com","outbrain.com","taboola.com","bidswitch.net","rubiconproject.com"]),Eg={image:"image",font:"font",media:"media",stylesheet:"stylesheet",websocket:"websocket"},wu={functional:{enabled:!0,blockedCategories:["image","font","media","stylesheet","tracking","advertising"]},visual:{enabled:!1,blockedCategories:[]},performance:{enabled:!0,blockedCategories:["image","font","media","tracking","advertising"]}};function $o(u,t,e){if(!e.enabled)return!1;if(e.allowPatterns?.length){for(let i of e.allowPatterns)if(Su(u,i))return!1}if(e.blockPatterns?.length){for(let i of e.blockPatterns)if(Su(u,i))return!0}let r=Eg[t];return!!(r&&e.blockedCategories.includes(r)||e.blockedCategories.includes("tracking")&&Ru(u,Tg)||e.blockedCategories.includes("advertising")&&Ru(u,Ag))}function hi(u){if(typeof u=="object")return u;let t=wu[u];return t?{...t,blockedCategories:[...t.blockedCategories]}:wu.visual}var Cu=new Map;function Su(u,t){let e=Cu.get(t);if(!e){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");e=new RegExp(r,"i"),Cu.set(t,e)}return e.test(u)}function Ru(u,t){try{let e=new URL(u).hostname;for(let r of t)if(e===r||e.endsWith(`.${r}`))return!0}catch{}return!1}var rs=null,Au=!1;function Eu(){if(Au)return rs;Au=!0;try{rs=Pa("patchright")}catch{rs=null}return rs}var ut=class{tool="stealth";stealthConfig;page=null;context=null;browser=null;sessionId=null;constructor(t){this.stealthConfig={...ts,...t}}async isAvailable(){return Eu()!==null}async launch(t){let e=Eu();if(!e)return{success:!1,error:new ee("stealth","Patchright is not installed. Install with: npm install patchright")};try{let r={headless:t?.headless??!0};if(t?.viewport&&(r.viewport=t.viewport),t?.args&&(r.args=t.args),this.stealthConfig.userAgent&&(r.userAgent=this.stealthConfig.userAgent),this.stealthConfig.proxy&&(r.proxy=this.stealthConfig.proxy),this.stealthConfig.persistentContext){let i=this.stealthConfig.userDataDir||`/tmp/stealth-browser-${Tu()}`;this.context=await e.chromium.launchPersistentContext(i,r);let n=this.context.pages();this.page=n.length>0?n[0]:await this.context.newPage()}else this.browser=await e.chromium.launch(r),this.page=await this.browser.newPage();return await this.applyResourceBlocking(),this.sessionId=Tu(),{success:!0,value:{id:this.sessionId,tool:"stealth",status:"active",createdAt:new Date}}}catch(r){return{success:!1,error:new F(`Failed to launch stealth browser: ${r instanceof Error?r.message:String(r)}`,"LAUNCH_FAILED","stealth",r instanceof Error?r:void 0)}}}async quit(){try{return this.context&&(await this.context.close(),this.context=null),this.browser&&(await this.browser.close(),this.browser=null),this.page=null,this.sessionId=null,{success:!0,value:void 0}}catch(t){return{success:!1,error:new F("Failed to quit stealth browser","QUIT_FAILED","stealth",t instanceof Error?t:void 0)}}}async navigate(t){if(!this.page)return this.notLaunched();try{let e=Date.now(),i=(await this.page.goto(t,{waitUntil:"domcontentloaded"}))?.status()??void 0;this.stealthConfig.cloudflareWaitSeconds>0&&await this.waitForCloudflare();let n=await this.page.title();return{success:!0,value:{url:this.page.url(),title:n,success:!0,durationMs:Date.now()-e,statusCode:i??void 0}}}catch(e){return this.wrapError("navigate",e)}}async reload(){if(!this.page)return this.notLaunched();try{return await this.page.reload(),{success:!0,value:void 0}}catch(t){return this.wrapError("reload",t)}}async goBack(){if(!this.page)return this.notLaunched();try{return await this.page.goBack(),{success:!0,value:void 0}}catch(t){return this.wrapError("goBack",t)}}async goForward(){if(!this.page)return this.notLaunched();try{return await this.page.goForward(),{success:!0,value:void 0}}catch(t){return this.wrapError("goForward",t)}}async click(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return await this.page.click(e),{success:!0,value:void 0}}catch(e){return this.wrapError("click",e)}}async fill(t,e){if(!this.page)return this.notLaunched();try{let r=this.resolveSelector(t);return await this.page.fill(r,e),{success:!0,value:void 0}}catch(r){return this.wrapError("fill",r)}}async getText(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.textContent(e)??""}}catch(e){return this.wrapError("getText",e)}}async isVisible(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.isVisible(e)}}catch(e){return this.wrapError("isVisible",e)}}async screenshot(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:{base64:(await this.page.screenshot({path:t?.path,fullPage:t?.fullPage,type:"png"})).toString("base64"),path:t?.path,format:"png",dimensions:{width:0,height:0}}}}catch(e){return this.wrapError("screenshot",e)}}async evaluate(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:await this.page.evaluate(t)}}catch(e){return this.wrapError("evaluate",e)}}async dispose(){await this.quit()}resolveSelector(t){if(typeof t=="string")return t;switch(t.type){case"css":return t.value;case"xpath":return`xpath=${t.value}`;case"text":return`text=${t.value}`;case"ref":return t.value;default:return t.value}}async applyResourceBlocking(){if(!this.page||!this.stealthConfig.resourceBlocking)return;let t=typeof this.stealthConfig.resourceBlocking=="string"?hi(this.stealthConfig.resourceBlocking):this.stealthConfig.resourceBlocking;t.enabled&&await this.page.route("**/*",e=>{let r=e.request().url(),i=e.request().resourceType();$o(r,i,t)?e.abort().catch(()=>{}):e.continue().catch(()=>{})})}async waitForCloudflare(){if(!this.page||this.stealthConfig.cloudflareWaitSeconds<=0)return;let t=this.stealthConfig.cloudflareWaitSeconds*1e3,e=Date.now();for(;Date.now()-e<t;){try{let r=await this.page.title();if(!r.includes("Just a moment")&&!r.includes("Checking your browser"))return}catch{}await new Promise(r=>setTimeout(r,500))}}notLaunched(){return{success:!1,error:new F("Stealth browser not launched. Call launch() first.","NOT_LAUNCHED","stealth")}}wrapError(t,e){return{success:!1,error:new F(`Stealth ${t} failed: ${e instanceof Error?e.message:String(e)}`,"OPERATION_FAILED","stealth",e instanceof Error?e:void 0)}}};async function Oo(){return!1}async function Vo(){try{return await new or().isAvailable()}catch{return!1}}var xg=["e2e-testing","api-mocking","responsive-testing","auth-testing"],Pg=["stealth-testing"];function kg(u){return xg.includes(u)}var is=class{tool="vibium";async isAvailable(){return!1}async launch(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async quit(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async navigate(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async reload(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async goBack(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async goForward(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async click(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async fill(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async getText(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async isVisible(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async screenshot(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async evaluate(){return{success:!1,error:new ee("vibium","Vibium client not yet implemented")}}async dispose(){}};async function _o(u={}){let{preference:t="auto",useCase:e}=u;if(e&&Pg.includes(e)&&await No())return new ut;if(e&&kg(e)||t==="agent-browser")return fi();if(t==="stealth"){if(await No())return new ut;throw new ee("stealth","Patchright is not installed")}if(t==="vibium"){if(await Oo())return new is;throw new ee("vibium","Vibium is not available")}return await Oo()?new is:(await Vo(),fi())}async function fi(){return new or}async function ns(u){return _o({useCase:u})}async function No(){try{return await new ut().isAvailable()}catch{return!1}}import{exec as Dg,execSync as NA}from"child_process";import{promisify as Mg}from"util";A();H();var GA=Mg(Dg);A();var xu={enabled:!0,similarityThreshold:.6,maxFingerprintsPerPage:200,namespace:"aqe/adaptive-locators",fallbackChain:["text","aria","fingerprint"]};function Fg(u){return`
2303
+ `),r=[];for(let i of e){let n=i.match(/^\s*(?:->)?\s*(\w+)\s*$/);n&&r.push(n[1])}return r}catch{return[]}}async closeSession(t){let e=this.sessions.get(t);if(!e)return{success:!1,error:`Session "${t}" not found`};let r=e.executor.terminateDaemon();if(r.success&&(e.status="closed",this.sessions.delete(t),this.activeSession===t)){let i=Array.from(this.sessions.keys());this.activeSession=i.length>0?i[0]:null}return r}async closeAllSessions(){let t=Array.from(this.sessions.keys());for(let e of t)await this.closeSession(e);this.sessions.clear(),this.activeSession=null}async cleanupIdleSessions(t=300*1e3){let e=Date.now(),r=0;for(let[i,n]of this.sessions)n.status==="idle"&&e-n.lastActivity.getTime()>t&&(await this.closeSession(i),r++);return r}getExecutor(){let t=this.getActiveSession();if(!t)throw new Error("No active session. Create one first.");return t.executor}getSessionExecutor(t){let e=this.sessions.get(t);if(!e)throw new Error(`Session "${t}" not found`);return e.executor}touchSession(t){let e=this.sessions.get(t);e&&(e.lastActivity=new Date)}updateSessionUrl(t,e){let r=this.sessions.get(t);r&&(r.currentUrl=e,r.lastActivity=new Date,r.status="active")}generateSessionName(){return`session-${++this.sessionCounter}-${Date.now().toString(36)}`}getStats(){let t=0,e=0,r=0;for(let i of this.sessions.values())switch(i.status){case"active":t++;break;case"idle":e++;break;case"closed":r++;break}return{totalSessions:this.sessions.size,activeSessions:t,idleSessions:e,closedSessions:r,activeSessionName:this.activeSession}}};H();function gi(u){if(typeof u=="string")return/^@?e\d+$/.test(u)?u.startsWith("@")?u:`@${u}`:u;switch(u.type){case"ref":return u.value.startsWith("@")?u.value:`@${u.value}`;case"css":return u.value;case"xpath":return`xpath=${u.value}`;case"text":return`text=${u.value}`;default:return u.value}}function j(u){return{success:!0,value:u}}function $(u){return{success:!1,error:u}}function es(u){return{id:u.name,tool:"agent-browser",status:u.status,currentUrl:u.currentUrl,createdAt:u.createdAt}}function Rg(u){let t=u.elements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),e=u.interactiveElements.map(i=>({ref:i.refWithAt,role:i.role,name:i.name,text:i.text,depth:i.depth})),r=new Map;for(let i of t)r.set(i.ref,i);return{url:u.url??"",title:u.title??"",elements:t,interactiveElements:e,refMap:r,timestamp:u.parsedAt}}var or=class{tool="agent-browser";executor;sessionManager;snapshotParser;config;isLaunched=!1;currentSessionId=null;constructor(t={}){this.config={headed:t.headed??!1,timeout:t.timeout??3e4,debug:t.debug??!1,sessionName:t.sessionName??"default"};let e={sessionName:this.config.sessionName,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug};this.executor=new lt(e),this.sessionManager=new Zn({headed:this.config.headed,timeout:this.config.timeout}),this.snapshotParser=bu()}async launch(t){try{if(this.isLaunched&&this.currentSessionId){let n=this.sessionManager.getSession(this.currentSessionId);if(n)return t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),j(es(n))}if(!await this.isAvailable())return $(new te("agent-browser","agent-browser CLI is not available"));let r=t?.sessionName??this.config.sessionName,i=await this.sessionManager.createSession({name:r,headed:t?.headless===!1||this.config.headed,timeout:this.config.timeout});return this.currentSessionId=i.name,this.isLaunched=!0,this.executor=new lt({sessionName:i.name,timeout:this.config.timeout,headed:t?.headless===!1||this.config.headed,debug:this.config.debug}),t?.viewport&&await this.setViewport(t.viewport.width,t.viewport.height),t?.deviceName&&await this.setDevice(t.deviceName),j(es(i))}catch(e){let r=new F(T(e),"LAUNCH_FAILED","agent-browser",e instanceof Error?e:void 0);return $(r)}}async quit(){try{if(this.currentSessionId){let t=await this.sessionManager.closeSession(this.currentSessionId);t.success||this.config.debug&&console.warn(`[agent-browser] Session close warning: ${t.error}`)}if(this.executor)try{this.executor.terminateDaemon()}catch(t){console.debug("[AgentBrowserClient] Daemon termination error:",t instanceof Error?t.message:t)}return this.isLaunched=!1,this.currentSessionId=null,j(void 0)}catch(t){return this.isLaunched=!1,this.currentSessionId=null,$(new F(T(t),"QUIT_FAILED","agent-browser",t instanceof Error?t:void 0))}}async isAvailable(){return yu()}async dispose(){await this.sessionManager.closeAllSessions(),this.isLaunched=!1,this.currentSessionId=null}async navigate(t){let e=Date.now();try{let r=this.executor.open(t);if(!r.success)return $(new F(r.error??"Navigation failed","NAVIGATION_FAILED","agent-browser"));this.currentSessionId&&this.sessionManager.updateSessionUrl(this.currentSessionId,t);let i=this.executor.eval("JSON.stringify({ title: document.title, url: window.location.href })"),n=i.success&&i.data?typeof i.data=="string"?E(i.data):i.data:{title:"",url:t};return j({url:n.url||t,title:n.title||"",success:!0,durationMs:Date.now()-e})}catch(r){return $(new F(T(r),"NAVIGATION_FAILED","agent-browser",r instanceof Error?r:void 0))}}async reload(){try{let t=this.executor.eval("window.location.reload()");return t.success?j(void 0):$(new F(t.error??"Reload failed","RELOAD_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"RELOAD_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goBack(){try{let t=this.executor.eval("window.history.back()");return t.success?j(void 0):$(new F(t.error??"Go back failed","HISTORY_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async goForward(){try{let t=this.executor.eval("window.history.forward()");return t.success?j(void 0):$(new F(t.error??"Go forward failed","HISTORY_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"HISTORY_FAILED","agent-browser",t instanceof Error?t:void 0))}}async click(t){try{let e=gi(t),r=this.executor.click(e);return r.success?j(void 0):$(new Mt("agent-browser",t,new Error(r.error)))}catch(e){return $(new F(T(e),"CLICK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async fill(t,e){try{let r=gi(t),i=this.executor.fill(r,e);return i.success?j(void 0):$(new Mt("agent-browser",t,new Error(i.error)))}catch(r){return $(new F(T(r),"FILL_FAILED","agent-browser",r instanceof Error?r:void 0))}}async getText(t){try{let e=gi(t),r=this.executor.getText(e);if(!r.success)return $(new Mt("agent-browser",t,new Error(r.error)));let i=r.data;if(i&&typeof i=="object"){let n=i;if("text"in n)i=n.text;else if("data"in n&&typeof n.data=="object"){let s=n.data;"text"in s?i=s.text:"result"in s&&(i=s.result)}else"result"in n&&(i=n.result)}return j(String(i??""))}catch(e){return $(new F(T(e),"GET_TEXT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async isVisible(t){try{let e=gi(t),r=this.executor.isVisible(e);return r.success?j(!!r.data):j(!1)}catch(e){return $(new F(T(e),"VISIBILITY_CHECK_FAILED","agent-browser",e instanceof Error?e:void 0))}}async screenshot(t){try{let e=this.executor.screenshot(t?.path,t?.fullPage);if(!e.success)return $(new F(e.error??"Screenshot failed","SCREENSHOT_FAILED","agent-browser"));let r=this.executor.eval("JSON.stringify({ width: window.innerWidth, height: window.innerHeight })"),i={width:1280,height:720};if(r.success&&r.data){let n=typeof r.data=="string"?E(r.data):r.data;i={width:n.width||1280,height:n.height||720}}return j({base64:t?.path?void 0:String(e.data??""),path:t?.path,format:"png",dimensions:i})}catch(e){return $(new F(T(e),"SCREENSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async evaluate(t){try{let e=this.executor.eval(t);if(!e.success)return $(new F(e.error??"Evaluation failed","EVAL_FAILED","agent-browser"));let r=e.data;if(r&&typeof r=="object"){let i=r;if("data"in i&&i.data&&typeof i.data=="object"){let n=i.data;"result"in n&&(r=n.result)}else"result"in i&&(r=i.result)}return j(r)}catch(e){return $(new F(T(e),"EVAL_FAILED","agent-browser",e instanceof Error?e:void 0))}}async getSnapshot(t){try{let e=this.executor.snapshot({interactive:t?.interactive,depth:t?.depth});if(!e.success)return $(new F(e.error??"Snapshot failed","SNAPSHOT_FAILED","agent-browser"));let r;try{r=this.snapshotParser.parseJson(e.data)}catch{r=this.snapshotParser.parse(String(e.data))}let i=this.executor.eval("window.location.href"),n=this.executor.eval("document.title");return i.success&&(r.url=String(i.data)),n.success&&(r.title=String(n.data)),j(Rg(r))}catch(e){return $(new F(T(e),"SNAPSHOT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async createSession(t){try{let e=await this.sessionManager.createSession({name:t});return j(es(e))}catch(e){return $(new F(T(e),"SESSION_CREATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async switchSession(t){try{return this.sessionManager.switchSession(t),this.currentSessionId=t,this.executor=new lt({sessionName:t,timeout:this.config.timeout,headed:this.config.headed,debug:this.config.debug}),j(void 0)}catch(e){return $(new F(T(e),"SESSION_SWITCH_FAILED","agent-browser",e instanceof Error?e:void 0))}}async listSessions(){try{let t=this.sessionManager.listSessions();return j(t.map(es))}catch(t){return $(new F(T(t),"SESSION_LIST_FAILED","agent-browser",t instanceof Error?t:void 0))}}async mockRoute(t,e){try{let r={status:e.status??200,body:e.body,headers:e.headers},i=this.executor.mockRoute(t,r);return i.success?j(void 0):$(new F(i.error??"Mock route failed","MOCK_ROUTE_FAILED","agent-browser"))}catch(r){return $(new F(T(r),"MOCK_ROUTE_FAILED","agent-browser",r instanceof Error?r:void 0))}}async abortRoute(t){try{let e=this.executor.abortRoute(t);return e.success?j(void 0):$(new F(e.error??"Abort route failed","ABORT_ROUTE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"ABORT_ROUTE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async clearRoutes(){try{let t=this.executor.clearRoutes();return t.success?j(void 0):$(new F(t.error??"Clear routes failed","CLEAR_ROUTES_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"CLEAR_ROUTES_FAILED","agent-browser",t instanceof Error?t:void 0))}}async setDevice(t){try{let e=this.executor.setDevice(t);return e.success?j(void 0):$(new F(e.error??"Set device failed","SET_DEVICE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"SET_DEVICE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async setViewport(t,e){try{let r=this.executor.setViewport(t,e);return r.success?j(void 0):$(new F(r.error??"Set viewport failed","SET_VIEWPORT_FAILED","agent-browser"))}catch(r){return $(new F(T(r),"SET_VIEWPORT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async saveState(t){try{let e=this.executor.saveState(t);return e.success?j(void 0):$(new F(e.error??"Save state failed","SAVE_STATE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"SAVE_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async loadState(t){try{let e=this.executor.loadState(t);return e.success?j(void 0):$(new F(e.error??"Load state failed","LOAD_STATE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"LOAD_STATE_FAILED","agent-browser",e instanceof Error?e:void 0))}}async waitForElement(t,e){try{let r=gi(t),i=this.executor.waitForElement(r,e);return i.success?j(void 0):$(new ct("agent-browser",`waitForElement(${r})`,new Error(i.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForText(t,e){try{let r=this.executor.waitForText(t);return r.success?j(void 0):$(new ct("agent-browser",`waitForText("${t}")`,new Error(r.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForUrl(t,e){try{let r=this.executor.waitForUrl(t);return r.success?j(void 0):$(new ct("agent-browser",`waitForUrl("${t}")`,new Error(r.error)))}catch(r){return $(new F(T(r),"WAIT_FAILED","agent-browser",r instanceof Error?r:void 0))}}async waitForNetworkIdle(t){try{let e=this.executor.waitForNetworkIdle();return e.success?j(void 0):$(new ct("agent-browser","waitForNetworkIdle",new Error(e.error)))}catch(e){return $(new F(T(e),"WAIT_FAILED","agent-browser",e instanceof Error?e:void 0))}}async startTrace(){try{let t=this.executor.startTrace();return t.success?j(void 0):$(new F(t.error??"Start trace failed","START_TRACE_FAILED","agent-browser"))}catch(t){return $(new F(T(t),"START_TRACE_FAILED","agent-browser",t instanceof Error?t:void 0))}}async stopTrace(t){try{let e=this.executor.stopTrace(t);return e.success?j(e.data??t):$(new F(e.error??"Stop trace failed","STOP_TRACE_FAILED","agent-browser"))}catch(e){return $(new F(T(e),"STOP_TRACE_FAILED","agent-browser",e instanceof Error?e:void 0))}}};import{randomUUID as Tu}from"crypto";var ts={persistentContext:!0,cloudflareWaitSeconds:0,resourceBlocking:"functional"};var Tg=new Set(["google-analytics.com","googletagmanager.com","analytics.google.com","hotjar.com","fullstory.com","segment.io","segment.com","mixpanel.com","heap.io","heapanalytics.com","amplitude.com","mouseflow.com","crazyegg.com","optimizely.com","newrelic.com","nr-data.net","sentry.io","bugsnag.com","logrocket.com","clarity.ms","facebook.net","connect.facebook.net"]),Ag=new Set(["doubleclick.net","googlesyndication.com","googleadservices.com","google-analytics.com","adservice.google.com","pagead2.googlesyndication.com","ads.twitter.com","ads-api.twitter.com","adsserver.com","adnxs.com","amazon-adsystem.com","criteo.com","moatads.com","outbrain.com","taboola.com","bidswitch.net","rubiconproject.com"]),Eg={image:"image",font:"font",media:"media",stylesheet:"stylesheet",websocket:"websocket"},wu={functional:{enabled:!0,blockedCategories:["image","font","media","stylesheet","tracking","advertising"]},visual:{enabled:!1,blockedCategories:[]},performance:{enabled:!0,blockedCategories:["image","font","media","tracking","advertising"]}};function $o(u,t,e){if(!e.enabled)return!1;if(e.allowPatterns?.length){for(let i of e.allowPatterns)if(Su(u,i))return!1}if(e.blockPatterns?.length){for(let i of e.blockPatterns)if(Su(u,i))return!0}let r=Eg[t];return!!(r&&e.blockedCategories.includes(r)||e.blockedCategories.includes("tracking")&&Ru(u,Tg)||e.blockedCategories.includes("advertising")&&Ru(u,Ag))}function hi(u){if(typeof u=="object")return u;let t=wu[u];return t?{...t,blockedCategories:[...t.blockedCategories]}:wu.visual}var Cu=new Map;function Su(u,t){let e=Cu.get(t);if(!e){let r=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");e=new RegExp(r,"i"),Cu.set(t,e)}return e.test(u)}function Ru(u,t){try{let e=new URL(u).hostname;for(let r of t)if(e===r||e.endsWith(`.${r}`))return!0}catch{}return!1}var rs=null,Au=!1;function Eu(){if(Au)return rs;Au=!0;try{rs=Pa("patchright")}catch{rs=null}return rs}var ut=class{tool="stealth";stealthConfig;page=null;context=null;browser=null;sessionId=null;constructor(t){this.stealthConfig={...ts,...t}}async isAvailable(){return Eu()!==null}async launch(t){let e=Eu();if(!e)return{success:!1,error:new te("stealth","Patchright is not installed. Install with: npm install patchright")};try{let r={headless:t?.headless??!0};if(t?.viewport&&(r.viewport=t.viewport),t?.args&&(r.args=t.args),this.stealthConfig.userAgent&&(r.userAgent=this.stealthConfig.userAgent),this.stealthConfig.proxy&&(r.proxy=this.stealthConfig.proxy),this.stealthConfig.persistentContext){let i=this.stealthConfig.userDataDir||`/tmp/stealth-browser-${Tu()}`;this.context=await e.chromium.launchPersistentContext(i,r);let n=this.context.pages();this.page=n.length>0?n[0]:await this.context.newPage()}else this.browser=await e.chromium.launch(r),this.page=await this.browser.newPage();return await this.applyResourceBlocking(),this.sessionId=Tu(),{success:!0,value:{id:this.sessionId,tool:"stealth",status:"active",createdAt:new Date}}}catch(r){return{success:!1,error:new F(`Failed to launch stealth browser: ${r instanceof Error?r.message:String(r)}`,"LAUNCH_FAILED","stealth",r instanceof Error?r:void 0)}}}async quit(){try{return this.context&&(await this.context.close(),this.context=null),this.browser&&(await this.browser.close(),this.browser=null),this.page=null,this.sessionId=null,{success:!0,value:void 0}}catch(t){return{success:!1,error:new F("Failed to quit stealth browser","QUIT_FAILED","stealth",t instanceof Error?t:void 0)}}}async navigate(t){if(!this.page)return this.notLaunched();try{let e=Date.now(),i=(await this.page.goto(t,{waitUntil:"domcontentloaded"}))?.status()??void 0;this.stealthConfig.cloudflareWaitSeconds>0&&await this.waitForCloudflare();let n=await this.page.title();return{success:!0,value:{url:this.page.url(),title:n,success:!0,durationMs:Date.now()-e,statusCode:i??void 0}}}catch(e){return this.wrapError("navigate",e)}}async reload(){if(!this.page)return this.notLaunched();try{return await this.page.reload(),{success:!0,value:void 0}}catch(t){return this.wrapError("reload",t)}}async goBack(){if(!this.page)return this.notLaunched();try{return await this.page.goBack(),{success:!0,value:void 0}}catch(t){return this.wrapError("goBack",t)}}async goForward(){if(!this.page)return this.notLaunched();try{return await this.page.goForward(),{success:!0,value:void 0}}catch(t){return this.wrapError("goForward",t)}}async click(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return await this.page.click(e),{success:!0,value:void 0}}catch(e){return this.wrapError("click",e)}}async fill(t,e){if(!this.page)return this.notLaunched();try{let r=this.resolveSelector(t);return await this.page.fill(r,e),{success:!0,value:void 0}}catch(r){return this.wrapError("fill",r)}}async getText(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.textContent(e)??""}}catch(e){return this.wrapError("getText",e)}}async isVisible(t){if(!this.page)return this.notLaunched();try{let e=this.resolveSelector(t);return{success:!0,value:await this.page.isVisible(e)}}catch(e){return this.wrapError("isVisible",e)}}async screenshot(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:{base64:(await this.page.screenshot({path:t?.path,fullPage:t?.fullPage,type:"png"})).toString("base64"),path:t?.path,format:"png",dimensions:{width:0,height:0}}}}catch(e){return this.wrapError("screenshot",e)}}async evaluate(t){if(!this.page)return this.notLaunched();try{return{success:!0,value:await this.page.evaluate(t)}}catch(e){return this.wrapError("evaluate",e)}}async dispose(){await this.quit()}resolveSelector(t){if(typeof t=="string")return t;switch(t.type){case"css":return t.value;case"xpath":return`xpath=${t.value}`;case"text":return`text=${t.value}`;case"ref":return t.value;default:return t.value}}async applyResourceBlocking(){if(!this.page||!this.stealthConfig.resourceBlocking)return;let t=typeof this.stealthConfig.resourceBlocking=="string"?hi(this.stealthConfig.resourceBlocking):this.stealthConfig.resourceBlocking;t.enabled&&await this.page.route("**/*",e=>{let r=e.request().url(),i=e.request().resourceType();$o(r,i,t)?e.abort().catch(()=>{}):e.continue().catch(()=>{})})}async waitForCloudflare(){if(!this.page||this.stealthConfig.cloudflareWaitSeconds<=0)return;let t=this.stealthConfig.cloudflareWaitSeconds*1e3,e=Date.now();for(;Date.now()-e<t;){try{let r=await this.page.title();if(!r.includes("Just a moment")&&!r.includes("Checking your browser"))return}catch{}await new Promise(r=>setTimeout(r,500))}}notLaunched(){return{success:!1,error:new F("Stealth browser not launched. Call launch() first.","NOT_LAUNCHED","stealth")}}wrapError(t,e){return{success:!1,error:new F(`Stealth ${t} failed: ${e instanceof Error?e.message:String(e)}`,"OPERATION_FAILED","stealth",e instanceof Error?e:void 0)}}};async function Oo(){return!1}async function Vo(){try{return await new or().isAvailable()}catch{return!1}}var xg=["e2e-testing","api-mocking","responsive-testing","auth-testing"],Pg=["stealth-testing"];function kg(u){return xg.includes(u)}var is=class{tool="vibium";async isAvailable(){return!1}async launch(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async quit(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async navigate(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async reload(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async goBack(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async goForward(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async click(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async fill(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async getText(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async isVisible(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async screenshot(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async evaluate(){return{success:!1,error:new te("vibium","Vibium client not yet implemented")}}async dispose(){}};async function _o(u={}){let{preference:t="auto",useCase:e}=u;if(e&&Pg.includes(e)&&await No())return new ut;if(e&&kg(e)||t==="agent-browser")return fi();if(t==="stealth"){if(await No())return new ut;throw new te("stealth","Patchright is not installed")}if(t==="vibium"){if(await Oo())return new is;throw new te("vibium","Vibium is not available")}return await Oo()?new is:(await Vo(),fi())}async function fi(){return new or}async function ns(u){return _o({useCase:u})}async function No(){try{return await new ut().isAvailable()}catch{return!1}}import{exec as Dg,execSync as NA}from"child_process";import{promisify as Mg}from"util";A();H();var GA=Mg(Dg);A();var xu={enabled:!0,similarityThreshold:.6,maxFingerprintsPerPage:200,namespace:"aqe/adaptive-locators",fallbackChain:["text","aria","fingerprint"]};function Fg(u){return`
2304
2304
  (() => {
2305
2305
  const el = document.querySelector(${JSON.stringify(u)});
2306
2306
  if (!el) return null;
@@ -2758,7 +2758,7 @@ ${t.slice(0,4e3)}
2758
2758
  // File: ${l}
2759
2759
  ${m.value.slice(0,2e3)}
2760
2760
  `)}}let o=this.calculateModelConfidence(n),c=null;if(this.isLLMPredictionAvailable()&&a.length>0){let l=await this.getHistoricalDefectPatterns(e);if(c=await this.analyzeDefectRiskWithLLM(a,n,l),c){for(let d of n)d.recommendations=this.mergeRecommendationsWithLLM(d.recommendations,c);c.confidenceLevel>.7&&(o=Math.min(1,o*1.1))}}return await this.storePrediction(n),this.modelMetrics.totalPredictions+=n.length,this.modelMetrics.lastUpdated=new Date,f({predictions:n,modelConfidence:o,factors:Array.from(s),llmAnalysis:c??void 0})}catch(e){return p(y(e))}}async getHistoricalDefectPatterns(t){let e=[];for(let i of t.slice(0,5)){let n=await this.memory.get(`${this.config.modelNamespace}:defect-patterns:${i}`);n?.patterns&&e.push(...n.patterns)}let r=await this.memory.get(`${this.config.modelNamespace}:common-defect-patterns`);return r&&e.push(...r),[...new Set(e)].slice(0,10)}async analyzeRegressionRisk(t){try{let{changeset:e,baseline:r,depth:i="shallow"}=t;if(e.length===0)return p(new Error("No files in changeset"));let n=[],s=0;for(let d of e){let m=await this.analyzeFileImpact(d,i);n.push(...m.areas),s+=m.risk}if(r&&this.config.enableHistoricalAnalysis){let d=await this.getBaselineRisk(r);s=(s+d)/2}let a=Math.min(1,s/e.length),o=this.riskToSeverity(a),c=this.generateTestRecommendations(n);return f({overallRisk:a,riskLevel:o,impactedAreas:n,recommendedTests:c,confidence:i==="deep"?.85:.7})}catch(e){return p(y(e))}}async updateModel(t){try{let e=`${this.config.modelNamespace}:feedback:${t.predictionId}`;return await this.memory.set(e,t,{namespace:"defect-intelligence",persist:!0}),await this.recalculateMetrics(t),f(void 0)}catch(e){return p(y(e))}}async getModelMetrics(){let t=await this.memory.get(`${this.config.modelNamespace}:metrics`);return t&&(this.modelMetrics={...t,lastUpdated:new Date(t.lastUpdated)}),{...this.modelMetrics}}async predictForFile(t,e,r){let i=await this.extractFileMetrics(t),n=[],s=0;for(let c of e){let d=(i[c.name]??0)*c.weight;s+=d,n.push({name:c.name,contribution:Math.round(d*100)/100})}s=Math.max(0,Math.min(1,s));let a=this.probabilityToRisk(s,r),o=this.generateRecommendations(n,s);return{file:t,probability:s,riskLevel:a,factors:n.filter(c=>c.contribution>.05),recommendations:o}}async extractFileMetrics(t){let e=await this.memory.get(`${this.config.modelNamespace}:file-metrics:${t}`);if(e)return e;let r={codeComplexity:await this.calculateComplexity(t),changeFrequency:await this.getChangeFrequency(t),developerExperience:await this.getDeveloperExperience(t),testCoverage:await this.getTestCoverage(t),codeAge:await this.getCodeAge(t),bugHistory:await this.getBugHistory(t)};return await this.memory.set(`${this.config.modelNamespace}:file-metrics:${t}`,r,{namespace:"defect-intelligence",ttl:3600}),r}async calculateComplexity(t){let e=t.split(".").pop()?.toLowerCase();if(e&&["ts","tsx","js","jsx"].includes(e)){let r=await this.fileReader.readFile(t);if(r.success)try{let i=t.split("/").pop()||t,n=this.tsParser.parseFile(i,r.value),s=this.tsParser.extractFunctions(n),a=this.tsParser.extractClasses(n),o=r.value.split(`
2761
- `).length,c=s.length,l=a.length,d=a.reduce((Y,G)=>Y+G.methods.length,0),m=s.filter(Y=>Y.isAsync).length,g=r.value,h=(g.match(/\bif\s*\(/g)||[]).length,b=(g.match(/\b(for|while|do)\s*[\(\{]/g)||[]).length,w=(g.match(/\bswitch\s*\(/g)||[]).length,C=(g.match(/\bcatch\s*\(/g)||[]).length,S=(g.match(/\?[^?:]+:/g)||[]).length,k=h+b*2+w*2+C+S,P=Math.min(1,o/500),O=Math.min(1,(c+d)/30),z=Math.min(1,k/50),K=m>0?.1:0,Ce=P*.2+O*.25+z*.4+K+(l>3?.05:0);return Math.max(0,Math.min(1,Ce))}catch(i){uc.debug(`AST parse failed: ${i instanceof Error?i.message:i}`)}}return this.estimateComplexityFromPath(t)}estimateComplexityFromPath(t){let e=t.split("/"),r=e[e.length-1],i=.3;return(t.includes("controller")||t.includes("service"))&&(i+=.2),(t.includes("coordinator")||t.includes("orchestrator"))&&(i+=.15),(t.includes("utils")||t.includes("helper"))&&(i-=.1),(t.includes("types")||t.includes("interfaces"))&&(i-=.15),r.length>30&&(i+=.1),Math.max(0,Math.min(1,i))}async getChangeFrequency(t){let e=await this.gitAnalyzer.getChangeFrequency(t);if(e!==.4)return await this.memory.set(`${this.config.modelNamespace}:history:${t}`,{changes:Math.round(e*30)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:history:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.changes/50):.4}async getDeveloperExperience(t){let e=await this.gitAnalyzer.getDeveloperExperience(t);if(e!==.5)return await this.memory.set(`${this.config.modelNamespace}:developer-exp:${t}`,{score:e},{ttl:3600}),e;let r=`${this.config.modelNamespace}:developer-exp:${t}`,i=await this.memory.get(r);return i?i.score:.5}async getTestCoverage(t){try{let e=await this.memory.get(`coverage:file:${t}`);if(e&&typeof e.line=="number")return 1-e.line/100;let r=await this.memory.get("coverage:latest");if(r&&typeof r.line=="number")return 1-r.line/100}catch{}return .4}async getCodeAge(t){let e=await this.gitAnalyzer.getCodeAge(t);if(e!==.4)return e;let r=`${this.config.modelNamespace}:age:${t}`,i=await this.memory.get(r);return i?i.days<7?.7:i.days>365?.3:.4:.4}async getBugHistory(t){let e=await this.gitAnalyzer.getBugHistory(t);if(e!==.2)return await this.memory.set(`${this.config.modelNamespace}:bugs:${t}`,{count:Math.round(e*10)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:bugs:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.count/10):.2}probabilityToRisk(t,e){return t>=e+.3?"critical":t>=e+.15?"high":t>=e?"medium":t>=e-.2?"low":"info"}riskToSeverity(t){return t>=.8?"critical":t>=.6?"high":t>=.4?"medium":t>=.2?"low":"info"}generateRecommendations(t,e){let r=[],i=[...t].sort((n,s)=>s.contribution-n.contribution);for(let n of i.slice(0,3))switch(n.name){case"codeComplexity":n.contribution>.1&&(r.push("Consider refactoring to reduce cyclomatic complexity"),r.push("Break down large functions into smaller, testable units"));break;case"changeFrequency":n.contribution>.1&&(r.push("High churn area - add comprehensive regression tests"),r.push("Consider stabilizing the interface before further changes"));break;case"testCoverage":n.contribution>.1&&(r.push("Increase test coverage to reduce defect risk"),r.push("Add unit tests for critical paths"));break;case"bugHistory":n.contribution>.1&&(r.push("Review past bug fixes for patterns"),r.push("Add regression tests for previously fixed issues"));break;case"codeAge":n.contribution>.1&&r.push("New code requires thorough review and testing");break;case"developerExperience":n.contribution>.1&&r.push("Request code review from senior developer");break}return e>.7&&r.push("CRITICAL: Schedule immediate code review"),r}async analyzeFileImpact(t,e){let r=[],i=0,n=this.categorizeFile(t),s=(await this.extractFileMetrics(t)).codeComplexity;if(r.push({area:n,files:[t],risk:s,reason:`Modified file in ${n} area`}),i+=s,e==="deep"){let a=await this.analyzeDependencies(t);for(let o of a){let c=(await this.extractFileMetrics(o)).codeComplexity*.5;r.push({area:this.categorizeFile(o),files:[o],risk:c,reason:`Dependency of ${t}`}),i+=c}}return{areas:r,risk:i}}categorizeFile(t){return t.includes("controller")?"API Layer":t.includes("service")?"Business Logic":t.includes("repository")||t.includes("dao")?"Data Access":t.includes("model")||t.includes("entity")?"Domain Model":t.includes("util")||t.includes("helper")?"Utilities":t.includes("test")?"Tests":t.includes("config")?"Configuration":"General"}async analyzeDependencies(t){let e=`code-intelligence:dependencies:${t}`,r=await this.memory.get(e);if(r&&r.length>0)return r;let i=[];try{let n=await this.fileReader.readFile(t);if(!n.success)return[];let s=t.split("/").pop()||t,a=this.tsParser.parseFile(s,n.value),o=this.tsParser.extractImports(a);for(let c of o)if(c.module.startsWith(".")){let l=this.resolveRelativeImport(t,c.module);i.push(l)}else c.module.startsWith("node:")||i.push(c.module);i.length>0&&await this.memory.set(e,i,{namespace:"code-intelligence",ttl:3600})}catch(n){uc.error(`Failed to analyze dependencies for ${t}`,n instanceof Error?n:void 0)}return i}resolveRelativeImport(t,e){let i=t.substring(0,t.lastIndexOf("/")).split("/"),n=e.split("/");for(let a of n)a!=="."&&(a===".."?i.pop():i.push(a));let s=i.join("/");return!s.endsWith(".ts")&&!s.endsWith(".tsx")&&!s.endsWith(".js")&&(s=s+".ts"),s}async getBaselineRisk(t){let e=`${this.config.modelNamespace}:baseline:${t}`;return(await this.memory.get(e))?.risk??.3}generateTestRecommendations(t){let e=[],r=new Set(t.map(n=>n.area));for(let n of r)switch(n){case"API Layer":e.push("Run API integration tests"),e.push("Verify endpoint response contracts");break;case"Business Logic":e.push("Run unit tests for business rules"),e.push("Execute scenario-based tests");break;case"Data Access":e.push("Run database integration tests"),e.push("Verify data integrity constraints");break;case"Domain Model":e.push("Run entity validation tests"),e.push("Check serialization/deserialization");break}return t.filter(n=>n.risk>.6).length>0&&(e.push("Run full regression test suite"),e.push("Consider exploratory testing for edge cases")),[...new Set(e)]}calculateModelConfidence(t){let e=this.modelMetrics.accuracy,r=t.map(n=>n.probability);return this.calculateVariance(r)>.2&&(e*=.9),t.length>10&&(e*=1.05),Math.min(1,Math.max(0,e))}calculateVariance(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length;return t.map(i=>Math.pow(i-e,2)).reduce((i,n)=>i+n,0)/t.length}async storePrediction(t){let e=v();await this.memory.set(`${this.config.modelNamespace}:prediction:${e}`,{id:e,predictions:t,timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}async recalculateMetrics(t){let e=t.predictedProbability>=this.config.defaultThreshold,r=e===t.actualDefect,i=.01;this.modelMetrics.accuracy=this.modelMetrics.accuracy*(1-i)+(r?1:0)*i,e&&t.actualDefect?(this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+1*i,this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+1*i):e&&!t.actualDefect?this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+0*i:!e&&t.actualDefect&&(this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+0*i),this.modelMetrics.f1Score=2*this.modelMetrics.precision*this.modelMetrics.recall/(this.modelMetrics.precision+this.modelMetrics.recall||1),this.modelMetrics.lastUpdated=new Date,await this.memory.set(`${this.config.modelNamespace}:metrics`,this.modelMetrics,{namespace:"defect-intelligence",persist:!0})}};M();A();var kh={minPatternFrequency:2,maxPatterns:50,clusterThreshold:.7,embeddingDimension:Ct.DIMENSIONS,patternNamespace:"defect-intelligence:patterns",enableSemanticClustering:!0,enableFlashAttention:!0},xs={"null-pointer":{indicators:["null","undefined","NullPointerException","TypeError: Cannot read"],prevention:"Use null-safe operators and defensive programming"},"race-condition":{indicators:["concurrent","async","race","timing","intermittent"],prevention:"Implement proper synchronization and use atomic operations"},"memory-leak":{indicators:["memory","leak","OutOfMemory","heap","gc"],prevention:"Ensure proper resource cleanup and avoid circular references"},"off-by-one":{indicators:["index","boundary","array","loop","range"],prevention:"Validate array bounds and use inclusive/exclusive ranges consistently"},"input-validation":{indicators:["validation","sanitize","input","injection","XSS"],prevention:"Implement strict input validation and sanitization"},"resource-exhaustion":{indicators:["timeout","resource","exhausted","limit","quota"],prevention:"Implement rate limiting and resource pooling"},"state-corruption":{indicators:["state","inconsistent","corrupt","invalid state"],prevention:"Use immutable state patterns and proper state machines"},"encoding-issue":{indicators:["encoding","charset","UTF","unicode","character"],prevention:"Use consistent encoding throughout the application"}},Ih=R.create("defect-intelligence/pattern-learner"),mr=class{constructor(t,e={}){this.memory=t;this.config={...kh,...e},this.embedder=e.embedder??new St({enableFallback:!0}),this.config.enableFlashAttention&&this.initializeFlashAttention()}memory;config;patternCache=new Map;embedder;flashAttention=null;flashAttentionAvailable=!1;MAX_CACHED_PATTERNS=5e3;async initializeFlashAttention(){let{createQEFlashAttention:t}=await import("./wrappers-VGKEBQLW.js");this.flashAttention=await t("defect-matching",this.config.flashAttentionConfig),this.flashAttentionAvailable=!0,Ih.info("Flash Attention initialized for defect matching")}async ensureFlashAttentionInitialized(){this.config.enableFlashAttention&&!this.flashAttention&&await this.initializeFlashAttention()}async learnPatterns(t){try{let{defects:e,includeResolutions:r=!1}=t;if(e.length===0)return p(new Error("No defects provided for learning"));let i=[],n=!1,s=await this.extractPatterns(e),a=this.mergeWithKnownPatterns(s);for(let c of a)c.frequency>=this.config.minPatternFrequency&&(i.push(c),await this.storePattern(c),n=!0);let o=this.calculateImprovementEstimate(e.length,i);return r&&await this.learnResolutions(e,i),f({patterns:i.slice(0,this.config.maxPatterns),modelUpdated:n,improvementEstimate:o})}catch(e){return p(y(e))}}async clusterDefects(t){try{let{defects:e,method:r,minClusterSize:i=2}=t;if(e.length===0)return p(new Error("No defects provided for clustering"));let n;switch(r){case"semantic":n=await this.clusterBySemantic(e,i);break;case"behavioral":n=await this.clusterByBehavior(e,i);break;case"temporal":n=await this.clusterByTemporal(e,i);break;default:return p(new Error(`Unknown clustering method: ${r}`))}let s=new Set(n.flatMap(c=>c.defects)),a=e.filter(c=>!s.has(c.id)).map(c=>c.id),o=this.calculateClusteringMetrics(n,e.length);return f({clusters:n,outliers:a,clusteringMetrics:o})}catch(e){return p(y(e))}}async findSimilarDefects(t,e=5){try{let r=await this.generateDefectEmbedding(t),i=await this.memory.vectorSearch(r,e+1),n=[];for(let s of i)if(s.score>=this.config.clusterThreshold){let a=await this.memory.get(s.key);a&&a.id!==t.id&&n.push(a)}return f(n.slice(0,e))}catch(r){return p(y(r))}}async getPatternById(t){if(this.patternCache.has(t))return this.patternCache.get(t);let e=`${this.config.patternNamespace}:${t}`,r=await this.memory.get(e);if(r)return this.cachePattern(r),r}async listPatterns(t=this.config.maxPatterns){let e=[],r=await this.memory.search(`${this.config.patternNamespace}:*`,t*2);for(let i of r){let n=await this.memory.get(i);if(n&&(e.push(n),e.length>=t))break}return e.sort((i,n)=>n.frequency-i.frequency)}getFlashAttentionStatus(){let t=0,e=null,r=null;return this.flashAttention&&(t=this.flashAttention.getMetrics().length,e=this.flashAttention.getAverageSpeedup(),r=this.flashAttention.getWorkload()),{enabled:this.config.enableFlashAttention??!1,available:this.flashAttentionAvailable,workload:r,metricsCount:t,averageSpeedup:e}}async extractPatterns(t){let e=new Map;for(let i of t){let n=`${i.title} ${i.description}`.toLowerCase();for(let[s,a]of Object.entries(xs)){let o=a.indicators.filter(c=>n.includes(c.toLowerCase()));if(o.length>0){let c=e.get(s);c?(c.defects.push(i.id),c.indicators.push(...o.filter(l=>!c.indicators.includes(l)))):e.set(s,{indicators:o,defects:[i.id]})}}if(i.tags)for(let s of i.tags){let a=`tag-${s}`,o=e.get(a);o?o.defects.push(i.id):e.set(a,{indicators:[s],defects:[i.id]})}}let r=[];for(let[i,n]of e){let s=xs[i];r.push({id:v(),name:this.formatPatternName(i),indicators:[...new Set(n.indicators)],frequency:n.defects.length,prevention:s?.prevention||`Address ${i} issues proactively`})}return r}mergeWithKnownPatterns(t){let e=[...t];for(let[r,i]of Object.entries(xs))e.some(s=>s.name.toLowerCase().includes(r.replace("-"," ")))||e.push({id:v(),name:this.formatPatternName(r),indicators:i.indicators,frequency:0,prevention:i.prevention});return e}formatPatternName(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async storePattern(t){let e=`${this.config.patternNamespace}:${t.id}`;if(await this.memory.set(e,t,{namespace:"defect-intelligence",persist:!0}),this.config.enableSemanticClustering){let r=await this.generatePatternEmbedding(t);await this.memory.storeVector(e,r,{patternId:t.id,name:t.name})}this.cachePattern(t)}async learnResolutions(t,e){for(let r of e){let i=t.filter(n=>{let s=`${n.title} ${n.description}`.toLowerCase();return r.indicators.some(a=>s.includes(a.toLowerCase()))});i.length>0&&await this.memory.set(`${this.config.patternNamespace}:resolutions:${r.id}`,{patternId:r.id,defectIds:i.map(n=>n.id),learnedAt:new Date().toISOString()},{namespace:"defect-intelligence",persist:!0})}}calculateImprovementEstimate(t,e){if(t===0)return 0;let r=e.reduce((s,a)=>s+a.frequency,0),i=Math.min(1,r/t),n=e.length>0?e.reduce((s,a)=>s+(a.prevention?.1:0),0)/e.length:0;return i*.7+n*.3}async clusterBySemantic(t,e){let r=new Map;await this.ensureFlashAttentionInitialized();let i=[];for(let s of t){let a=await this.generateDefectEmbedding(s);i.push({defect:s,embedding:a}),await this.memory.storeVector(`${this.config.patternNamespace}:defect:${s.id}`,a,{defectId:s.id})}let n=new Set;for(let{defect:s,embedding:a}of i){if(n.has(s.id))continue;let o=[s.id];n.add(s.id);for(let c of i){if(c.defect.id===s.id||n.has(c.defect.id))continue;await this.computeSimilarity(a,c.embedding)>=this.config.clusterThreshold&&(o.push(c.defect.id),n.add(c.defect.id))}if(o.length>=e){let c=v(),l=this.findCommonFactors(t.filter(d=>o.includes(d.id)));r.set(c,{id:c,label:this.generateClusterLabel(t.filter(d=>o.includes(d.id))),defects:o,commonFactors:l,suggestedFix:this.suggestFix(l)})}}return Array.from(r.values())}async computeSimilarity(t,e){if(!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Call ensureFlashAttentionInitialized() first.");return this.computeFlashAttentionSimilarity(t,e)}async computeFlashAttentionSimilarity(t,e){let r=t.length,i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let c=0;c<r;c++)i[c]=t[c],n[c]=e[c],s[c]=e[c];let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=0;for(let c=0;c<r;c++)o+=a[c]*t[c];return Math.max(0,Math.min(1,(o+1)/2))}async batchComputeSimilarities(t,e){if(await this.ensureFlashAttentionInitialized(),!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Ensure @ruvector/attention is installed as a dependency.");let r=new Float32Array(t),i=e.map(a=>new Float32Array(a)),n=await this.flashAttention.matchDefectPattern(r,i),s=new Array(e.length).fill(0);for(let a of n)a.pattern<s.length&&(s[a.pattern]=Math.max(0,Math.min(1,(a.score+1)/2)));return s}async clusterByBehavior(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.tags?.sort().join("|")||n.file||"unknown",a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=e){let a=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Behavioral: ${n.replace(/\|/g,", ")}`,defects:s.map(c=>c.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}async clusterByTemporal(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.title.toLowerCase().split(/\s+/).slice(0,2).join(" "),a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=2){let a=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Temporal: ${n}`,defects:s.map(c=>c.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}findCommonFactors(t){let e=[];if(t.every(n=>n.tags)){let n=t.map(a=>new Set(a.tags)),s=[...n[0]].filter(a=>n.every(o=>o.has(a)));e.push(...s)}if(t.every(n=>n.file)){let n=t.map(a=>a.file.split("/")),s=Math.min(...n.map(a=>a.length));for(let a=0;a<s;a++)n.every(o=>o[a]===n[0][a])&&e.push(`Path: ${n[0][a]}`)}let r=t.map(n=>new Set(n.title.toLowerCase().split(/\s+/))),i=[...r[0]].filter(n=>n.length>3&&r.every(s=>s.has(n)));return e.push(...i.map(n=>`Keyword: ${n}`)),[...new Set(e)]}generateClusterLabel(t){let r=t.map(s=>s.title.toLowerCase()).flatMap(s=>s.split(/\s+/)),i=new Map;for(let s of r)s.length>3&&i.set(s,(i.get(s)||0)+1);return[...i.entries()].sort((s,a)=>a[1]-s[1]).slice(0,2).map(([s])=>s).join(" ")||"Unnamed Cluster"}suggestFix(t){for(let e of t)for(let[r,i]of Object.entries(xs))if(e.toLowerCase().includes(r)||i.indicators.some(n=>e.toLowerCase().includes(n.toLowerCase())))return i.prevention;return"Review common factors and implement targeted fixes"}calculateClusteringMetrics(t,e){if(t.length===0||e===0)return{silhouette:0,cohesion:0};let r=t.reduce((c,l)=>c+l.defects.length,0),i=r/t.length,n=r/e,s=t.map(c=>c.defects.length),a=s.reduce((c,l)=>c+Math.pow(l-i,2),0)/s.length,o=Math.max(0,1-a/(i*i||1));return{silhouette:Math.round(o*100)/100,cohesion:Math.round(n*100)/100}}async generateDefectEmbedding(t){let e=this.formatDefectForEmbedding(t);return this.embedder.embed(e)}async generatePatternEmbedding(t){let e=this.formatPatternForEmbedding(t);return this.embedder.embed(e)}formatDefectForEmbedding(t){return[`Title: ${t.title}`,t.description?`Description: ${t.description}`:"",t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",t.file?`File: ${t.file}`:""].filter(Boolean).join(`
2761
+ `).length,c=s.length,l=a.length,d=a.reduce((Y,G)=>Y+G.methods.length,0),m=s.filter(Y=>Y.isAsync).length,g=r.value,h=(g.match(/\bif\s*\(/g)||[]).length,b=(g.match(/\b(for|while|do)\s*[\(\{]/g)||[]).length,w=(g.match(/\bswitch\s*\(/g)||[]).length,C=(g.match(/\bcatch\s*\(/g)||[]).length,S=(g.match(/\?[^?:]+:/g)||[]).length,k=h+b*2+w*2+C+S,P=Math.min(1,o/500),O=Math.min(1,(c+d)/30),z=Math.min(1,k/50),K=m>0?.1:0,Ce=P*.2+O*.25+z*.4+K+(l>3?.05:0);return Math.max(0,Math.min(1,Ce))}catch(i){uc.debug(`AST parse failed: ${i instanceof Error?i.message:i}`)}}return this.estimateComplexityFromPath(t)}estimateComplexityFromPath(t){let e=t.split("/"),r=e[e.length-1],i=.3;return(t.includes("controller")||t.includes("service"))&&(i+=.2),(t.includes("coordinator")||t.includes("orchestrator"))&&(i+=.15),(t.includes("utils")||t.includes("helper"))&&(i-=.1),(t.includes("types")||t.includes("interfaces"))&&(i-=.15),r.length>30&&(i+=.1),Math.max(0,Math.min(1,i))}async getChangeFrequency(t){let e=await this.gitAnalyzer.getChangeFrequency(t);if(e!==.4)return await this.memory.set(`${this.config.modelNamespace}:history:${t}`,{changes:Math.round(e*30)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:history:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.changes/50):.4}async getDeveloperExperience(t){let e=await this.gitAnalyzer.getDeveloperExperience(t);if(e!==.5)return await this.memory.set(`${this.config.modelNamespace}:developer-exp:${t}`,{score:e},{ttl:3600}),e;let r=`${this.config.modelNamespace}:developer-exp:${t}`,i=await this.memory.get(r);return i?i.score:.5}async getTestCoverage(t){try{let e=await this.memory.get(`coverage:file:${t}`);if(e&&typeof e.line=="number")return 1-e.line/100;let r=await this.memory.get("coverage:latest");if(r&&typeof r.line=="number")return 1-r.line/100}catch{}return .4}async getCodeAge(t){let e=await this.gitAnalyzer.getCodeAge(t);if(e!==.4)return e;let r=`${this.config.modelNamespace}:age:${t}`,i=await this.memory.get(r);return i?i.days<7?.7:i.days>365?.3:.4:.4}async getBugHistory(t){let e=await this.gitAnalyzer.getBugHistory(t);if(e!==.2)return await this.memory.set(`${this.config.modelNamespace}:bugs:${t}`,{count:Math.round(e*10)},{ttl:3600}),e;let r=`${this.config.modelNamespace}:bugs:${t}`,i=await this.memory.get(r);return i?Math.min(1,i.count/10):.2}probabilityToRisk(t,e){return t>=e+.3?"critical":t>=e+.15?"high":t>=e?"medium":t>=e-.2?"low":"info"}riskToSeverity(t){return t>=.8?"critical":t>=.6?"high":t>=.4?"medium":t>=.2?"low":"info"}generateRecommendations(t,e){let r=[],i=[...t].sort((n,s)=>s.contribution-n.contribution);for(let n of i.slice(0,3))switch(n.name){case"codeComplexity":n.contribution>.1&&(r.push("Consider refactoring to reduce cyclomatic complexity"),r.push("Break down large functions into smaller, testable units"));break;case"changeFrequency":n.contribution>.1&&(r.push("High churn area - add comprehensive regression tests"),r.push("Consider stabilizing the interface before further changes"));break;case"testCoverage":n.contribution>.1&&(r.push("Increase test coverage to reduce defect risk"),r.push("Add unit tests for critical paths"));break;case"bugHistory":n.contribution>.1&&(r.push("Review past bug fixes for patterns"),r.push("Add regression tests for previously fixed issues"));break;case"codeAge":n.contribution>.1&&r.push("New code requires thorough review and testing");break;case"developerExperience":n.contribution>.1&&r.push("Request code review from senior developer");break}return e>.7&&r.push("CRITICAL: Schedule immediate code review"),r}async analyzeFileImpact(t,e){let r=[],i=0,n=this.categorizeFile(t),s=(await this.extractFileMetrics(t)).codeComplexity;if(r.push({area:n,files:[t],risk:s,reason:`Modified file in ${n} area`}),i+=s,e==="deep"){let a=await this.analyzeDependencies(t);for(let o of a){let c=(await this.extractFileMetrics(o)).codeComplexity*.5;r.push({area:this.categorizeFile(o),files:[o],risk:c,reason:`Dependency of ${t}`}),i+=c}}return{areas:r,risk:i}}categorizeFile(t){return t.includes("controller")?"API Layer":t.includes("service")?"Business Logic":t.includes("repository")||t.includes("dao")?"Data Access":t.includes("model")||t.includes("entity")?"Domain Model":t.includes("util")||t.includes("helper")?"Utilities":t.includes("test")?"Tests":t.includes("config")?"Configuration":"General"}async analyzeDependencies(t){let e=`code-intelligence:dependencies:${t}`,r=await this.memory.get(e);if(r&&r.length>0)return r;let i=[];try{let n=await this.fileReader.readFile(t);if(!n.success)return[];let s=t.split("/").pop()||t,a=this.tsParser.parseFile(s,n.value),o=this.tsParser.extractImports(a);for(let c of o)if(c.module.startsWith(".")){let l=this.resolveRelativeImport(t,c.module);i.push(l)}else c.module.startsWith("node:")||i.push(c.module);i.length>0&&await this.memory.set(e,i,{namespace:"code-intelligence",ttl:3600})}catch(n){uc.error(`Failed to analyze dependencies for ${t}`,n instanceof Error?n:void 0)}return i}resolveRelativeImport(t,e){let i=t.substring(0,t.lastIndexOf("/")).split("/"),n=e.split("/");for(let a of n)a!=="."&&(a===".."?i.pop():i.push(a));let s=i.join("/");return!s.endsWith(".ts")&&!s.endsWith(".tsx")&&!s.endsWith(".js")&&(s=s+".ts"),s}async getBaselineRisk(t){let e=`${this.config.modelNamespace}:baseline:${t}`;return(await this.memory.get(e))?.risk??.3}generateTestRecommendations(t){let e=[],r=new Set(t.map(n=>n.area));for(let n of r)switch(n){case"API Layer":e.push("Run API integration tests"),e.push("Verify endpoint response contracts");break;case"Business Logic":e.push("Run unit tests for business rules"),e.push("Execute scenario-based tests");break;case"Data Access":e.push("Run database integration tests"),e.push("Verify data integrity constraints");break;case"Domain Model":e.push("Run entity validation tests"),e.push("Check serialization/deserialization");break}return t.filter(n=>n.risk>.6).length>0&&(e.push("Run full regression test suite"),e.push("Consider exploratory testing for edge cases")),[...new Set(e)]}calculateModelConfidence(t){let e=this.modelMetrics.accuracy,r=t.map(n=>n.probability);return this.calculateVariance(r)>.2&&(e*=.9),t.length>10&&(e*=1.05),Math.min(1,Math.max(0,e))}calculateVariance(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length;return t.map(i=>Math.pow(i-e,2)).reduce((i,n)=>i+n,0)/t.length}async storePrediction(t){let e=v();await this.memory.set(`${this.config.modelNamespace}:prediction:${e}`,{id:e,predictions:t,timestamp:new Date().toISOString()},{namespace:"defect-intelligence",ttl:86400*7})}async recalculateMetrics(t){let e=t.predictedProbability>=this.config.defaultThreshold,r=e===t.actualDefect,i=.01;this.modelMetrics.accuracy=this.modelMetrics.accuracy*(1-i)+(r?1:0)*i,e&&t.actualDefect?(this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+1*i,this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+1*i):e&&!t.actualDefect?this.modelMetrics.precision=this.modelMetrics.precision*(1-i)+0*i:!e&&t.actualDefect&&(this.modelMetrics.recall=this.modelMetrics.recall*(1-i)+0*i),this.modelMetrics.f1Score=2*this.modelMetrics.precision*this.modelMetrics.recall/(this.modelMetrics.precision+this.modelMetrics.recall||1),this.modelMetrics.lastUpdated=new Date,await this.memory.set(`${this.config.modelNamespace}:metrics`,this.modelMetrics,{namespace:"defect-intelligence",persist:!0})}};M();A();var kh={minPatternFrequency:2,maxPatterns:50,clusterThreshold:.7,embeddingDimension:Ct.DIMENSIONS,patternNamespace:"defect-intelligence:patterns",enableSemanticClustering:!0,enableFlashAttention:!0},xs={"null-pointer":{indicators:["null","undefined","NullPointerException","TypeError: Cannot read"],prevention:"Use null-safe operators and defensive programming"},"race-condition":{indicators:["concurrent","async","race","timing","intermittent"],prevention:"Implement proper synchronization and use atomic operations"},"memory-leak":{indicators:["memory","leak","OutOfMemory","heap","gc"],prevention:"Ensure proper resource cleanup and avoid circular references"},"off-by-one":{indicators:["index","boundary","array","loop","range"],prevention:"Validate array bounds and use inclusive/exclusive ranges consistently"},"input-validation":{indicators:["validation","sanitize","input","injection","XSS"],prevention:"Implement strict input validation and sanitization"},"resource-exhaustion":{indicators:["timeout","resource","exhausted","limit","quota"],prevention:"Implement rate limiting and resource pooling"},"state-corruption":{indicators:["state","inconsistent","corrupt","invalid state"],prevention:"Use immutable state patterns and proper state machines"},"encoding-issue":{indicators:["encoding","charset","UTF","unicode","character"],prevention:"Use consistent encoding throughout the application"}},Ih=R.create("defect-intelligence/pattern-learner"),mr=class{constructor(t,e={}){this.memory=t;this.config={...kh,...e},this.embedder=e.embedder??new St({enableFallback:!0}),this.config.enableFlashAttention&&this.initializeFlashAttention()}memory;config;patternCache=new Map;embedder;flashAttention=null;flashAttentionAvailable=!1;MAX_CACHED_PATTERNS=5e3;async initializeFlashAttention(){let{createQEFlashAttention:t}=await import("./wrappers-HU3SB4FT.js");this.flashAttention=await t("defect-matching",this.config.flashAttentionConfig),this.flashAttentionAvailable=!0,Ih.info("Flash Attention initialized for defect matching")}async ensureFlashAttentionInitialized(){this.config.enableFlashAttention&&!this.flashAttention&&await this.initializeFlashAttention()}async learnPatterns(t){try{let{defects:e,includeResolutions:r=!1}=t;if(e.length===0)return p(new Error("No defects provided for learning"));let i=[],n=!1,s=await this.extractPatterns(e),a=this.mergeWithKnownPatterns(s);for(let c of a)c.frequency>=this.config.minPatternFrequency&&(i.push(c),await this.storePattern(c),n=!0);let o=this.calculateImprovementEstimate(e.length,i);return r&&await this.learnResolutions(e,i),f({patterns:i.slice(0,this.config.maxPatterns),modelUpdated:n,improvementEstimate:o})}catch(e){return p(y(e))}}async clusterDefects(t){try{let{defects:e,method:r,minClusterSize:i=2}=t;if(e.length===0)return p(new Error("No defects provided for clustering"));let n;switch(r){case"semantic":n=await this.clusterBySemantic(e,i);break;case"behavioral":n=await this.clusterByBehavior(e,i);break;case"temporal":n=await this.clusterByTemporal(e,i);break;default:return p(new Error(`Unknown clustering method: ${r}`))}let s=new Set(n.flatMap(c=>c.defects)),a=e.filter(c=>!s.has(c.id)).map(c=>c.id),o=this.calculateClusteringMetrics(n,e.length);return f({clusters:n,outliers:a,clusteringMetrics:o})}catch(e){return p(y(e))}}async findSimilarDefects(t,e=5){try{let r=await this.generateDefectEmbedding(t),i=await this.memory.vectorSearch(r,e+1),n=[];for(let s of i)if(s.score>=this.config.clusterThreshold){let a=await this.memory.get(s.key);a&&a.id!==t.id&&n.push(a)}return f(n.slice(0,e))}catch(r){return p(y(r))}}async getPatternById(t){if(this.patternCache.has(t))return this.patternCache.get(t);let e=`${this.config.patternNamespace}:${t}`,r=await this.memory.get(e);if(r)return this.cachePattern(r),r}async listPatterns(t=this.config.maxPatterns){let e=[],r=await this.memory.search(`${this.config.patternNamespace}:*`,t*2);for(let i of r){let n=await this.memory.get(i);if(n&&(e.push(n),e.length>=t))break}return e.sort((i,n)=>n.frequency-i.frequency)}getFlashAttentionStatus(){let t=0,e=null,r=null;return this.flashAttention&&(t=this.flashAttention.getMetrics().length,e=this.flashAttention.getAverageSpeedup(),r=this.flashAttention.getWorkload()),{enabled:this.config.enableFlashAttention??!1,available:this.flashAttentionAvailable,workload:r,metricsCount:t,averageSpeedup:e}}async extractPatterns(t){let e=new Map;for(let i of t){let n=`${i.title} ${i.description}`.toLowerCase();for(let[s,a]of Object.entries(xs)){let o=a.indicators.filter(c=>n.includes(c.toLowerCase()));if(o.length>0){let c=e.get(s);c?(c.defects.push(i.id),c.indicators.push(...o.filter(l=>!c.indicators.includes(l)))):e.set(s,{indicators:o,defects:[i.id]})}}if(i.tags)for(let s of i.tags){let a=`tag-${s}`,o=e.get(a);o?o.defects.push(i.id):e.set(a,{indicators:[s],defects:[i.id]})}}let r=[];for(let[i,n]of e){let s=xs[i];r.push({id:v(),name:this.formatPatternName(i),indicators:[...new Set(n.indicators)],frequency:n.defects.length,prevention:s?.prevention||`Address ${i} issues proactively`})}return r}mergeWithKnownPatterns(t){let e=[...t];for(let[r,i]of Object.entries(xs))e.some(s=>s.name.toLowerCase().includes(r.replace("-"," ")))||e.push({id:v(),name:this.formatPatternName(r),indicators:i.indicators,frequency:0,prevention:i.prevention});return e}formatPatternName(t){return t.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ")}async storePattern(t){let e=`${this.config.patternNamespace}:${t.id}`;if(await this.memory.set(e,t,{namespace:"defect-intelligence",persist:!0}),this.config.enableSemanticClustering){let r=await this.generatePatternEmbedding(t);await this.memory.storeVector(e,r,{patternId:t.id,name:t.name})}this.cachePattern(t)}async learnResolutions(t,e){for(let r of e){let i=t.filter(n=>{let s=`${n.title} ${n.description}`.toLowerCase();return r.indicators.some(a=>s.includes(a.toLowerCase()))});i.length>0&&await this.memory.set(`${this.config.patternNamespace}:resolutions:${r.id}`,{patternId:r.id,defectIds:i.map(n=>n.id),learnedAt:new Date().toISOString()},{namespace:"defect-intelligence",persist:!0})}}calculateImprovementEstimate(t,e){if(t===0)return 0;let r=e.reduce((s,a)=>s+a.frequency,0),i=Math.min(1,r/t),n=e.length>0?e.reduce((s,a)=>s+(a.prevention?.1:0),0)/e.length:0;return i*.7+n*.3}async clusterBySemantic(t,e){let r=new Map;await this.ensureFlashAttentionInitialized();let i=[];for(let s of t){let a=await this.generateDefectEmbedding(s);i.push({defect:s,embedding:a}),await this.memory.storeVector(`${this.config.patternNamespace}:defect:${s.id}`,a,{defectId:s.id})}let n=new Set;for(let{defect:s,embedding:a}of i){if(n.has(s.id))continue;let o=[s.id];n.add(s.id);for(let c of i){if(c.defect.id===s.id||n.has(c.defect.id))continue;await this.computeSimilarity(a,c.embedding)>=this.config.clusterThreshold&&(o.push(c.defect.id),n.add(c.defect.id))}if(o.length>=e){let c=v(),l=this.findCommonFactors(t.filter(d=>o.includes(d.id)));r.set(c,{id:c,label:this.generateClusterLabel(t.filter(d=>o.includes(d.id))),defects:o,commonFactors:l,suggestedFix:this.suggestFix(l)})}}return Array.from(r.values())}async computeSimilarity(t,e){if(!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Call ensureFlashAttentionInitialized() first.");return this.computeFlashAttentionSimilarity(t,e)}async computeFlashAttentionSimilarity(t,e){let r=t.length,i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let c=0;c<r;c++)i[c]=t[c],n[c]=e[c],s[c]=e[c];let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=0;for(let c=0;c<r;c++)o+=a[c]*t[c];return Math.max(0,Math.min(1,(o+1)/2))}async batchComputeSimilarities(t,e){if(await this.ensureFlashAttentionInitialized(),!this.flashAttention)throw new Error("[PatternLearnerService] Flash Attention not initialized. Ensure @ruvector/attention is installed as a dependency.");let r=new Float32Array(t),i=e.map(a=>new Float32Array(a)),n=await this.flashAttention.matchDefectPattern(r,i),s=new Array(e.length).fill(0);for(let a of n)a.pattern<s.length&&(s[a.pattern]=Math.max(0,Math.min(1,(a.score+1)/2)));return s}async clusterByBehavior(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.tags?.sort().join("|")||n.file||"unknown",a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=e){let a=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Behavioral: ${n.replace(/\|/g,", ")}`,defects:s.map(c=>c.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}async clusterByTemporal(t,e){let r=new Map,i=new Map;for(let n of t){let s=n.title.toLowerCase().split(/\s+/).slice(0,2).join(" "),a=i.get(s)||[];a.push(n),i.set(s,a)}for(let[n,s]of i)if(s.length>=2){let a=v(),o=this.findCommonFactors(s);r.set(a,{id:a,label:`Temporal: ${n}`,defects:s.map(c=>c.id),commonFactors:o,suggestedFix:this.suggestFix(o)})}return Array.from(r.values())}findCommonFactors(t){let e=[];if(t.every(n=>n.tags)){let n=t.map(a=>new Set(a.tags)),s=[...n[0]].filter(a=>n.every(o=>o.has(a)));e.push(...s)}if(t.every(n=>n.file)){let n=t.map(a=>a.file.split("/")),s=Math.min(...n.map(a=>a.length));for(let a=0;a<s;a++)n.every(o=>o[a]===n[0][a])&&e.push(`Path: ${n[0][a]}`)}let r=t.map(n=>new Set(n.title.toLowerCase().split(/\s+/))),i=[...r[0]].filter(n=>n.length>3&&r.every(s=>s.has(n)));return e.push(...i.map(n=>`Keyword: ${n}`)),[...new Set(e)]}generateClusterLabel(t){let r=t.map(s=>s.title.toLowerCase()).flatMap(s=>s.split(/\s+/)),i=new Map;for(let s of r)s.length>3&&i.set(s,(i.get(s)||0)+1);return[...i.entries()].sort((s,a)=>a[1]-s[1]).slice(0,2).map(([s])=>s).join(" ")||"Unnamed Cluster"}suggestFix(t){for(let e of t)for(let[r,i]of Object.entries(xs))if(e.toLowerCase().includes(r)||i.indicators.some(n=>e.toLowerCase().includes(n.toLowerCase())))return i.prevention;return"Review common factors and implement targeted fixes"}calculateClusteringMetrics(t,e){if(t.length===0||e===0)return{silhouette:0,cohesion:0};let r=t.reduce((c,l)=>c+l.defects.length,0),i=r/t.length,n=r/e,s=t.map(c=>c.defects.length),a=s.reduce((c,l)=>c+Math.pow(l-i,2),0)/s.length,o=Math.max(0,1-a/(i*i||1));return{silhouette:Math.round(o*100)/100,cohesion:Math.round(n*100)/100}}async generateDefectEmbedding(t){let e=this.formatDefectForEmbedding(t);return this.embedder.embed(e)}async generatePatternEmbedding(t){let e=this.formatPatternForEmbedding(t);return this.embedder.embed(e)}formatDefectForEmbedding(t){return[`Title: ${t.title}`,t.description?`Description: ${t.description}`:"",t.tags?.length?`Tags: ${t.tags.join(", ")}`:"",t.file?`File: ${t.file}`:""].filter(Boolean).join(`
2762
2762
  `)}formatPatternForEmbedding(t){return[`Pattern: ${t.name}`,`Indicators: ${t.indicators.join(", ")}`,`Prevention: ${t.prevention}`,`Frequency: ${t.frequency}`].filter(Boolean).join(`
2763
2763
  `)}cachePattern(t){if(this.patternCache.size>=this.MAX_CACHED_PATTERNS){let e=this.patternCache.keys().next().value;e&&this.patternCache.delete(e)}this.patternCache.set(t.id,t)}destroy(){this.patternCache.clear(),this.flashAttention=null,this.flashAttentionAvailable=!1}};M();A();H();var Dh={maxTimelineEvents:20,maxRelatedFiles:10,minConfidenceThreshold:.3,analyzerNamespace:"defect-intelligence:root-cause",enableDeepAnalysis:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:2048},Ps={"logic-error":{symptoms:["wrong result","incorrect output","unexpected behavior","calculation"],causes:["Incorrect algorithm implementation","Missing edge case handling","Wrong operator usage","Off-by-one error"],impact:"high",remediation:["Review algorithm logic step by step","Add comprehensive unit tests","Use property-based testing for edge cases"]},"null-reference":{symptoms:["null","undefined","cannot read property","NullPointerException"],causes:["Missing null check","Uninitialized variable","Race condition in initialization","API returning null unexpectedly"],impact:"high",remediation:["Add defensive null checks","Use Optional/Maybe pattern","Initialize variables at declaration"]},concurrency:{symptoms:["race","deadlock","intermittent","timing","thread"],causes:["Missing synchronization","Shared mutable state","Lock ordering issue","Async operation not awaited"],impact:"high",remediation:["Use immutable data structures","Implement proper locking strategy","Add synchronization primitives"]},"resource-management":{symptoms:["memory","leak","connection","file handle","exhausted"],causes:["Resource not properly released","Missing cleanup in error path","Connection pool misconfiguration","Circular reference preventing GC"],impact:"medium",remediation:["Use try-finally or using blocks","Implement IDisposable pattern","Configure resource pools properly"]},configuration:{symptoms:["config","environment","setting","property","parameter"],causes:["Wrong configuration value","Missing required setting","Environment mismatch","Hardcoded values"],impact:"medium",remediation:["Validate configuration at startup","Use configuration schema validation","Document all required settings"]},integration:{symptoms:["api","service","external","timeout","connection"],causes:["External service change","API contract violation","Network configuration issue","Missing retry logic"],impact:"high",remediation:["Implement circuit breaker pattern","Add contract tests","Use retry with exponential backoff"]},"data-integrity":{symptoms:["corrupt","invalid","constraint","duplicate","data"],causes:["Missing validation","Database constraint violated","Race condition in data update","Inconsistent state transitions"],impact:"high",remediation:["Add input validation at all layers","Use database transactions properly","Implement optimistic locking"]},security:{symptoms:["injection","auth","permission","access","security"],causes:["Missing input sanitization","Broken authentication","Insufficient authorization checks","Sensitive data exposure"],impact:"high",remediation:["Sanitize all user inputs","Implement proper authentication","Follow principle of least privilege"]}},Mh=R.create("defect-intelligence/root-cause-analyzer"),pr=class{config;memory;llmRouter;constructor(t,e={}){this.config={...Dh,...e},this.isMemoryBackend(t)?(this.memory=t,this.llmRouter=void 0):(this.memory=t.memory,this.llmRouter=t.llmRouter)}isMemoryBackend(t){return typeof t.get=="function"&&typeof t.set=="function"&&!("memory"in t)}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis===!0&&this.llmRouter!==void 0}getModelForTier(t){switch(t){case 1:return"claude-haiku-4-5-20251001";case 2:return"claude-sonnet-4-6";case 3:return"claude-sonnet-4-6";case 4:return"claude-opus-4-7";default:return"claude-sonnet-4-6"}}async analyzeRootCauseWithLLM(t,e,r){if(!this.llmRouter)return null;try{let i=this.buildLLMAnalysisPrompt(t,e,r),n=this.getModelForTier(this.config.llmModelTier??2),s=await this.llmRouter.chat({messages:[{role:"system",content:`You are an expert software engineer specialized in debugging and root cause analysis.
2764
2764
  Analyze the provided defect information and provide:
@@ -2889,7 +2889,7 @@ Please analyze these requirements for:
2889
2889
  `).map(i=>i.trim()).filter(i=>i.length>0&&ge(i));if(r.length>0){let i=0;for(let n of r)i+=Td(n);return Ns(i,"jest",u)}return Mi(u,t)}catch{return Mi(u,t)}}function hf(u,t){try{let r=Fi("cargo test --list",{cwd:u,encoding:"utf-8",timeout:t.timeout}).split(`
2890
2890
  `).filter(o=>o.endsWith(": test")),i=r.length,n=r.filter(o=>!o.includes("integration")&&!o.includes("e2e")).length,s=r.filter(o=>o.includes("integration")).length,a=r.filter(o=>o.includes("e2e")).length;return{total:i,unit:n,integration:s,e2e:a,source:"cargo"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"cargo"}}}function ff(u,t){try{let r=Fi("pytest --collect-only -q",{cwd:u,encoding:"utf-8",timeout:t.timeout}).split(`
2891
2891
  `).filter(o=>o.includes("::test_")||o.includes("::Test")),i=r.length,n=r.filter(o=>o.includes("unit")||!o.includes("integration")&&!o.includes("e2e")).length,s=r.filter(o=>o.includes("integration")||o.includes("_integration")).length,a=r.filter(o=>o.includes("e2e")||o.includes("end_to_end")).length;return{total:i,unit:n-s-a,integration:s,e2e:a,source:"pytest"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"pytest"}}}function yf(u,t){try{let r=Fi('go test -list ".*" ./...',{cwd:u,encoding:"utf-8",timeout:t.timeout}).split(`
2892
- `).filter(o=>o.startsWith("Test")||o.startsWith("Example")||o.startsWith("Benchmark")),i=r.filter(o=>o.startsWith("Test")).length,n=r.filter(o=>o.startsWith("Test")&&!o.includes("Integration")&&!o.includes("E2E")).length,s=r.filter(o=>o.includes("Integration")).length,a=r.filter(o=>o.includes("E2E")).length;return{total:i,unit:n,integration:s,e2e:a,source:"go"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"go"}}}function Mi(u,t){let e=0,r=0,i=0,n=0;function s(a){if(!ge(a))return;let o=df(a,{withFileTypes:!0});for(let c of o){let l=ve(a,c.name);if(c.isDirectory()){if(t.excludeDirs.includes(c.name))continue;s(l)}else if(c.isFile()&&vf(c.name)){let d=mf(c.name).toLowerCase(),m=0;[".ts",".tsx",".js",".jsx",".mjs"].includes(d)?m=Td(l):d===".py"?m=bf(l):d===".rs"?m=wf(l):d===".go"&&(m=Cf(l)),e+=m;let g=l.toLowerCase();g.includes("e2e")||g.includes("end-to-end")?n+=m:g.includes("integration")?i+=m:r+=m}}}return s(u),{total:e,unit:r,integration:i,e2e:n,source:"fallback"}}function vf(u){let t=u.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||t.includes("_test.")||t.startsWith("test_")||t.endsWith("_test.ts")||t.endsWith("_test.js")||t.endsWith("_test.py")||t.endsWith("_test.go")||t.endsWith("_test.rs")}function Td(u){try{let t=Li(u,"utf-8"),e=t.match(/\bit\s*\(/g)||[],r=t.match(/\btest\s*\(/g)||[];return e.length+r.length}catch{return 0}}function bf(u){try{let t=Li(u,"utf-8"),e=t.match(/\bdef\s+test_\w+\s*\(/g)||[],r=t.match(/\basync\s+def\s+test_\w+\s*\(/g)||[];return e.length+r.length}catch{return 0}}function wf(u){try{let t=Li(u,"utf-8"),e=t.match(/#\[test\]/g)||[],r=t.match(/#\[tokio::test\]/g)||[],i=t.match(/#\[async_std::test\]/g)||[];return e.length+r.length+i.length}catch{return 0}}function Cf(u){try{return(Li(u,"utf-8").match(/\bfunc\s+Test\w+\s*\(/g)||[]).length}catch{return 0}}function Ns(u,t,e){let r=u,i=0,n=0;return(ge(ve(e,"tests","integration"))||ge(ve(e,"test","integration"))||ge(ve(e,"__tests__","integration")))&&(i=Math.floor(u*.2),r-=i),(ge(ve(e,"tests","e2e"))||ge(ve(e,"test","e2e"))||ge(ve(e,"e2e"))||ge(ve(e,"cypress")))&&(n=Math.floor(u*.1),r-=n),{total:u,unit:Math.max(0,r),integration:i,e2e:n,source:t}}var Cc=class{config;cache=new Map;cacheHits=0;cacheMisses=0;constructor(t={}){this.config={...Nt,...t}}async collectAll(t){let e=`all:${t}`;if(this.config.enableCache){let l=this.getFromCache(e);if(l)return l}let[r,i,n]=await Promise.all([this.countLOC(t),this.countTests(t),this.countPatterns(t,this.detectLanguage(t))]),s=[];r.source!=="fallback"&&s.push(r.source),i.source!=="fallback"&&s.push(i.source);let a=r.source==="fallback"?"approximate":"accurate",o=i.source==="fallback"?"approximate":"accurate",c={loc:r,tests:i,patterns:n,collectedAt:new Date,toolsUsed:s,accuracy:{loc:a,tests:o,overall:a==="accurate"&&o==="accurate"?"accurate":"approximate"}};return this.config.enableCache&&this.setInCache(e,c),c}async countLOC(t){let e=`loc:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await fc(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countTests(t){let e=`tests:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await bc(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countPatterns(t,e){let r=`patterns:${t}:${e}`;if(this.config.enableCache){let n=this.getFromCache(r);if(n)return n}let i=this.countPatternsInternal(t,e);return this.config.enableCache&&this.setInCache(r,i),i}checkTools(){let t=yc(),e=wc(process.cwd());return[...t,...e]}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0}getCacheStats(){return{hits:this.cacheHits,misses:this.cacheMisses,size:this.cache.size}}getFromCache(t){let e=this.cache.get(t);return e&&Date.now()-e.timestamp<this.config.cacheTTL?(this.cacheHits++,e.data):(this.cacheMisses++,null)}setInCache(t,e){this.cache.set(t,{data:e,timestamp:Date.now()})}detectLanguage(t){return Vt(_t(t,"Cargo.toml"))?"rust":Vt(_t(t,"go.mod"))?"go":Vt(_t(t,"pyproject.toml"))||Vt(_t(t,"requirements.txt"))?"python":Vt(_t(t,"package.json"))?Vt(_t(t,"tsconfig.json"))?"typescript":"javascript":"unknown"}countPatternsInternal(t,e){let r={},i=0,n=0,s=0,a=0,o=this.getPatternsForLanguage(e);function c(l){if(!Vt(l))return;let d=Rf(l,{withFileTypes:!0});for(let m of d){let g=_t(l,m.name);if(m.isDirectory()){if(["node_modules","dist","coverage","build",".git","vendor","target"].includes(m.name))continue;c(g)}else if(m.isFile()){let h=Tf(m.name).toLowerCase();if(Af(h,e)){let b=Ef(g,o);(b.unwraps>0||b.unsafeBlocks>0||b.todoComments>0||b.consoleStatements>0)&&(r[g]=b,i+=b.unwraps,n+=b.unsafeBlocks,s+=b.todoComments,a+=b.consoleStatements)}}}}return c(t),{unwraps:i,unsafeBlocks:n,todoComments:s,consoleStatements:a,byFile:r}}getPatternsForLanguage(t){switch(t){case"rust":return{unwrap:/\.unwrap\s*\(/g,unsafe:/\bunsafe\s*\{/g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(println!|print!|eprintln!|eprint!|dbg!)\s*\(/g};case"python":return{unwrap:null,unsafe:null,todo:/#\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(print)\s*\(/g};case"go":return{unwrap:null,unsafe:/\bunsafe\./g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(fmt\.Print|fmt\.Printf|fmt\.Println|log\.Print|log\.Printf|log\.Println)\s*\(/g};default:return{unwrap:null,unsafe:null,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\bconsole\.(log|debug|info|warn|error)\s*\(/g}}}};function Af(u,t){switch(t){case"rust":return u===".rs";case"python":return[".py",".pyw"].includes(u);case"go":return u===".go";case"typescript":return[".ts",".tsx"].includes(u);case"javascript":return[".js",".jsx",".mjs",".cjs"].includes(u);default:return[".ts",".tsx",".js",".jsx",".py",".rs",".go"].includes(u)}}function Ef(u,t){try{let e=Sf(u,"utf-8");return{unwraps:t.unwrap?(e.match(t.unwrap)||[]).length:0,unsafeBlocks:t.unsafe?(e.match(t.unsafe)||[]).length:0,todoComments:(e.match(t.todo)||[]).length,consoleStatements:(e.match(t.console)||[]).length}}catch{return{unwraps:0,unsafeBlocks:0,todoComments:0,consoleStatements:0}}}function Ad(u={}){return new Cc(u)}M();A();se();Yt();A();Yt();A();Yt();A();Yt();A();se();Yt();A();var NO=300*1e3;qe();qe();M();qe();var YO=R.create("temporal-compression");A();M();var t1=R.create("ruvector-server-client");qm();import{Buffer as _f}from"buffer";var c1=_f.from("COGCNTNR","ascii");qe();qe();var Bf={capacity:1e4,minCoherenceThreshold:.3,highTierThreshold:.8,mediumTierThreshold:.5,highTierWeight:3,mediumTierWeight:1.5,lowTierWeight:1},Sc=class{config;cusumDetector;buffer;totalSeen=0;totalAdmitted=0;totalRejected=0;totalEvicted=0;totalSampled=0;constructor(t){this.config={...Bf,...t},this.cusumDetector=new _a({threshold:this.config.cusumConfig?.threshold??5,slack:this.config.cusumConfig?.slack??.5,resetOnAlarm:!1,warmupSamples:20}),this.buffer=[]}admit(t,e,r){this.totalSeen++;let i=this.getEffectiveThreshold();if(r<i)return this.totalRejected++,!1;let n=this.classifyTier(r),s={id:t,data:e,coherenceScore:r,tier:n,admittedAt:Date.now(),replayCount:0};if(this.buffer.length<this.config.capacity)return this.buffer.push(s),this.totalAdmitted++,!0;let a=Math.floor(Math.random()*this.totalAdmitted),o=this.getTierWeight(n),c=Math.floor(a/o);if(c<this.config.capacity){let l=this.selectEvictionTarget(c);return this.buffer[l]=s,this.totalEvicted++,this.totalAdmitted++,!0}return this.totalRejected++,!1}sample(t,e){if(this.buffer.length===0)return[];let r=e!==void 0?this.buffer.filter(a=>a.coherenceScore>=e):this.buffer;if(r.length===0)return[];if(t>=r.length){let a=[...r];for(let o of a)o.replayCount++;return this.totalSampled+=a.length,a}let i=r.map(a=>this.getTierWeight(a.tier)),n=[],s=new Set;for(;n.length<t&&s.size<r.length;){let a=0;for(let l=0;l<r.length;l++)s.has(l)||(a+=i[l]);if(a<=0)break;let o=Math.random()*a,c=-1;for(let l=0;l<r.length;l++)if(!s.has(l)&&(o-=i[l],o<=0)){c=l;break}if(c===-1){for(let l=0;l<r.length;l++)if(!s.has(l)){c=l;break}}c>=0&&(s.add(c),r[c].replayCount++,n.push(r[c]))}return this.totalSampled+=n.length,n}size(){return this.buffer.length}getStats(){let t={high:0,medium:0,low:0};for(let e of this.buffer)t[e.tier]++;return{size:this.buffer.length,capacity:this.config.capacity,totalAdmitted:this.totalAdmitted,totalRejected:this.totalRejected,totalEvicted:this.totalEvicted,tierCounts:t,totalSampled:this.totalSampled}}getByTier(t){return this.buffer.filter(e=>e.tier===t)}clear(){this.buffer.length=0,this.totalSeen=0,this.totalAdmitted=0,this.totalRejected=0,this.totalEvicted=0,this.totalSampled=0,this.cusumDetector.reset()}getCusumState(t){return this.cusumDetector.getState(t)}observeCoherence(t,e){return this.cusumDetector.update(t,e)}classifyTier(t){return t>=this.config.highTierThreshold?"high":t>=this.config.mediumTierThreshold?"medium":"low"}getTierWeight(t){switch(t){case"high":return this.config.highTierWeight;case"medium":return this.config.mediumTierWeight;case"low":return this.config.lowTierWeight}}getEffectiveThreshold(){let t=["retrieve","write","learn","act"],e=!1;for(let r of t)if(this.cusumDetector.getState(r).driftDetected){e=!0;break}return e?Math.min(this.config.minCoherenceThreshold*1.5,.9):this.config.minCoherenceThreshold}selectEvictionTarget(t){let e=Math.min(10,this.buffer.length),r=Math.max(0,t-Math.floor(e/2)),i=Math.min(this.buffer.length,r+e),n=t,s=this.buffer[t].coherenceScore;for(let a=r;a<i;a++)this.buffer[a].coherenceScore<s&&(s=this.buffer[a].coherenceScore,n=a);return n}};se();var yr=R.create("code-intelligence/gnn");async function Ed(u,t,e){try{for(let r of e)try{let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Rc(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}};u.addEmbedding(s)}}catch(i){yr.error(`Failed to index ${r}:`,i instanceof Error?i:void 0)}yr.info(`Indexed ${e.length} code embeddings`)}catch(r){yr.error("Failed to index code embeddings:",r instanceof Error?r:void 0)}}async function Rc(u,t){let e=[],r=u.split(".").pop(),i=_s(r||"");e.push(i%1e3/1e3),e.push(Math.min(1,t.length/1e4));let n=t.match(/function\s+\w+/g)||[],s=t.match(/class\s+\w+/g)||[];e.push(Math.min(1,(n.length+s.length)/50));let a=t.match(/import\s+.*from|require\s*\(/g)||[];e.push(Math.min(1,a.length/20));let o=t.match(/for\s*\(|while\s*\(/g)||[],c=t.match(/if\s*\(/g)||[];e.push(Math.min(1,(o.length+c.length)/30));let l=t.match(/\/\/.*|\/\*[\s\S]*?\*\//g)||[];e.push(Math.min(1,l.length/50));let d=_s(t.slice(0,500));for(let m=e.length;m<384;m++)e.push(d*(m+1)%1e4/1e4);return e.slice(0,384)}async function xd(u,t){try{let r={vector:await Rc("query",t),dimension:384,namespace:"code",text:t,timestamp:Date.now(),quantization:"none"};return u.search(r,{limit:10,namespace:"code"}).map(n=>({file:n.metadata?.path??`file-${n.id}`,similarity:1-n.distance}))}catch(e){return yr.error("Failed to search with GNN:",e instanceof Error?e:void 0),[]}}async function Pd(u,t,e){try{for(let r of e.changedFiles){let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Rc(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}},a=u.search(s,{limit:5,namespace:"code"});yr.info(`Found ${a.length} semantically similar files to ${r}`)}}}catch(r){yr.error("Failed to enhance impact analysis:",r instanceof Error?r:void 0)}}function kd(u,t){let e=new Map,r=new Map;for(let i of u)e.set(i.file,i.score),r.set(i.file,i);for(let i of t){let n=e.get(i.file);n!==void 0?e.set(i.file,(n+i.similarity)/2):(e.set(i.file,i.similarity*.8),r.set(i.file,{file:i.file,snippet:"",score:i.similarity*.8,highlights:[]}))}return Array.from(r.values()).map(i=>({...i,score:e.get(i.file)??i.score})).sort((i,n)=>n.score-i.score).slice(0,20)}function _s(u){let t=0;for(let e=0;e<u.length;e++)t=(t<<5)-t+u.charCodeAt(e),t=t|0;return Math.abs(t)}M();A();var Ve=R.create("code-intelligence/hypergraph");async function Id(u,t,e){try{let r=await u.findUntestedFunctions();if(Ve.info(`[CodeIntelligence] Found ${r.length} untested functions via hypergraph`),e){let i=D("code-intelligence.UntestedFunctionsFound","code-intelligence",{count:r.length,functions:r.slice(0,10).map(n=>({name:n.name,file:n.filePath,complexity:n.complexity}))});await t.publish(i)}return{success:!0,value:r}}catch(r){let i=y(r);return Ve.error("Failed to find untested functions:"),p(i)}}async function Dd(u,t,e,r){if(t.length===0)return{success:!0,value:[]};try{let i=await u.findImpactedTests(t);if(Ve.info(`[CodeIntelligence] Found ${i.length} impacted tests for ${t.length} changed files via hypergraph`),r){let n=D("code-intelligence.ImpactedTestsFound","code-intelligence",{changedFiles:t,testCount:i.length,tests:i.slice(0,10).map(s=>({name:s.name,file:s.filePath}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return Ve.error("Failed to find impacted tests:"),p(n)}}async function Md(u,t,e,r){try{let i=await u.findCoverageGaps(t);if(Ve.info(`[CodeIntelligence] Found ${i.length} coverage gaps (functions with <=${t}% coverage) via hypergraph`),r){let n=D("code-intelligence.CoverageGapsFound","code-intelligence",{maxCoverage:t,gapCount:i.length,gaps:i.slice(0,10).map(s=>({name:s.name,file:s.filePath,coverage:s.coverage,complexity:s.complexity}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return Ve.error("Failed to find coverage gaps:"),p(n)}}async function Fd(u,t,e,r,i){try{Ve.info(`[CodeIntelligence] Building hypergraph from ${t.files.length} indexed files`);let n=await u.buildFromIndexResult(t);if(Ve.info(`[CodeIntelligence] Hypergraph built: ${n.nodesCreated} nodes created, ${n.nodesUpdated} nodes updated, ${n.edgesCreated} edges created (${n.durationMs}ms)`),await e.set("hypergraph:build:latest",{timestamp:new Date().toISOString(),...n},{namespace:"code-intelligence",persist:!0}),i){let s=D("code-intelligence.HypergraphBuilt","code-intelligence",{nodesCreated:n.nodesCreated,nodesUpdated:n.nodesUpdated,edgesCreated:n.edgesCreated,durationMs:n.durationMs,errorCount:n.errors.length});await r.publish(s)}return{success:!0,value:n}}catch(n){let s=y(n);return Ve.error("Failed to build hypergraph:"),p(s)}}async function Ld(u,t,e){try{let r=await u.findImpactedTests(t.changedFiles),i=new Set([...e.impactedTests,...r.map(a=>a.filePath||a.name)]),n=e.riskLevel;if(r.length>e.impactedTests.length){let a=e.directImpact.length+e.transitiveImpact.length;a>10&&i.size>20?n="critical":a>5&&i.size>10&&(n="high")}let s=[...e.recommendations];return r.length>0&&s.push(`Hypergraph analysis found ${r.length} additional test(s) to run`),{...e,impactedTests:Array.from(i),riskLevel:n,recommendations:s}}catch(r){return Ve.error("Failed to enhance impact with hypergraph:",r instanceof Error?r:void 0),e}}M();var vr=R.create("code-intelligence/consensus");async function $d(u,t,e,r){let i=V({id:v(),type:"code-pattern-detection",confidence:t,description:`Verify code pattern: ${u.name} (${u.type}) at ${u.location}`,payload:u,detectedBy:"code-intelligence-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(vr.info(`Code pattern '${u.name}' verified by consensus`),!0):(vr.warn(`Code pattern '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Od(u,t,e,r){let i=V({id:v(),type:"impact-analysis",confidence:t,description:`Verify impact analysis: ${u.changedFiles.length} files, risk=${u.riskLevel}, ${u.impactedTests.length} tests`,payload:u,detectedBy:"code-intelligence-coordinator",severity:u.riskLevel==="critical"||u.riskLevel==="high"?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(vr.info(`Impact analysis verified by consensus (risk=${u.riskLevel})`),!0):(vr.warn(`Impact analysis NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Nd(u,t,e,r){let i=V({id:v(),type:"dependency-mapping",confidence:t,description:`Verify dependency: ${u.source} -> ${u.targets.length} targets (${u.type})`,payload:u,detectedBy:"code-intelligence-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(vr.info("Dependency mapping verified by consensus"),!0):(vr.warn(`Dependency mapping NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var ny={maxConcurrentWorkflows:5,defaultTimeout:12e4,publishEvents:!0,enableIncrementalIndex:!0,enableGNN:!0,enableSONA:!0,enableMetricCollector:!0,enableHypergraph:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},ie=R.create("code-intelligence"),Oi=class extends Q{constructor(e,r,i,n={}){let s={...ny,...n};super(e,"code-intelligence",s,{verifyFindingTypes:["code-pattern-detection","impact-analysis","dependency-mapping"]});this.memory=r;this.agentCoordinator=i;this.knowledgeGraph=new Rt(r),this.semanticAnalyzer=new Ot(r),this.impactAnalyzer=new Br(r,this.knowledgeGraph),this.fileReader=new De,this.productFactorsBridge=new $s(e,r,{publishEvents:this.config.publishEvents})}memory;agentCoordinator;knowledgeGraph;semanticAnalyzer;impactAnalyzer;fileReader;gnnIndex;sonaEngine;rlInitialized=!1;metricCollector;hypergraph;hypergraphDb;productFactorsBridge;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enableGNN||this.config.enableSONA)&&await this.initializeRLIntegrations(),this.config.enableMetricCollector&&(this.metricCollector=Ad({enableCache:!0,cacheTTL:3e5}),ie.info("MetricCollector initialized for real code metrics")),this.config.enableHypergraph&&await this.initializeHypergraph(),await this.productFactorsBridge.initialize()}async initializeHypergraph(){try{let{openDatabase:e}=await import("./safe-db-3JQP4EPU.js"),r=await import("fs"),i=await import("path"),{findProjectRoot:n}=await import("./unified-memory-2ETCY22B.js"),s=n(),a=this.config.hypergraphDbPath||i.join(s,".agentic-qe","memory.db"),o=i.dirname(a);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),this.hypergraphDb=e(a),this.hypergraph=await nn({db:this.hypergraphDb,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:this.config.enableGNN}),ie.info(`Hypergraph Engine initialized at ${a}`)}catch(e){let r=e instanceof Error?e.message:String(e);if(ie.warn(`Hypergraph Engine initialization failed (feature degraded): ${r}`),this.hypergraph=void 0,this.hypergraphDb=void 0,this.config.publishEvents){let i=D("code-intelligence.HypergraphDegraded","code-intelligence",{reason:r});this.eventBus.publish(i).catch(()=>{})}}}async initializeRLIntegrations(){try{if(this.config.enableGNN&&(Va(),this.gnnIndex=rn.getInstance("code-intelligence",{M:16,efConstruction:200,efSearch:50,dimension:384,metric:"cosine"}),this.gnnIndex.initializeIndex("code"),this.gnnIndex.initializeIndex("test")),this.config.enableSONA)try{this.sonaEngine=await me({domain:"code-intelligence",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.6}),ie.info("PersistentSONAEngine initialized for code pattern learning")}catch(e){ie.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(e){throw ie.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){if(await this.saveWorkflowState(),this.gnnIndex&&rn.closeInstance("code-intelligence"),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(e){ie.error("Error closing SONA engine:",e instanceof Error?e:void 0)}if(this.hypergraphDb){try{this.hypergraphDb.close()}catch(e){ie.error("Error closing hypergraph database:",e instanceof Error?e:void 0)}this.hypergraphDb=void 0}this.hypergraph=void 0,await this.productFactorsBridge.dispose()}getActiveWorkflows(){return super.getActiveWorkflows()}async index(e){let r=v();try{if(this.startWorkflow(r,"index"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Indexing paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn indexing agents"));let i=await this.spawnIndexerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,10);let n=await this.knowledgeGraph.index(e);if(n.success){if(this.updateWorkflowProgress(r,40),this.config.enableGNN&&this.gnnIndex&&e.paths.length>0&&await this.indexCodeEmbeddings(e.paths),this.updateWorkflowProgress(r,60),this.config.enableMetricCollector&&this.metricCollector&&e.paths.length>0){let s=this.getProjectRootFromPaths(e.paths);s&&await this.collectProjectMetrics(s)}if(this.updateWorkflowProgress(r,70),e.paths.length>0&&await this.indexForSemanticSearch(e.paths),this.updateWorkflowProgress(r,85),this.config.enableHypergraph&&this.hypergraph&&e.paths.length>0)try{let s=await this.buildCodeIndexResultFromPaths(e.paths);s.files.length>0&&(await this.hypergraph.buildFromIndexResult(s),ie.info(`Hypergraph rebuilt from ${s.files.length} indexed files`))}catch(s){ie.warn(`Hypergraph rebuild skipped: ${s instanceof Error?s.message:s}`)}this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.publishEvents&&await this.publishKnowledgeGraphUpdated(n.value)}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async search(e){let r=v();try{this.startWorkflow(r,"search");let i=await this.spawnSearchAgent(r,e);if(i.success&&this.addAgentToWorkflow(r,i.value),this.config.enableSONA&&this.sonaEngine){let a=await this.adaptSearchPattern(e);a.success&&a.pattern&&ie.info(`Adapted search pattern with ${a.similarity.toFixed(3)} similarity`)}let n=[];this.config.enableGNN&&this.gnnIndex&&(n=await this.searchCodeWithGNN(e));let s=await this.semanticAnalyzer.search(e);return s.success?(n.length>0&&(s.value.results=this.mergeSearchResults(s.value.results,n)),this.completeWorkflow(r),this.config.publishEvents&&await this.publishSemanticSearchCompleted(e,s.value)):this.failWorkflow(r,s.error.message),i.success&&await this.agentCoordinator.stop(i.value),s}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async analyzeImpact(e){let r=v();try{if(this.startWorkflow(r,"impact"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative impact analysis"),this.minCutMixin.shouldPauseOperations())return p(new Error("Impact analysis paused: topology is in critical state"));let i=await this.spawnImpactAnalyzerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,20),this.config.enableGNN&&this.gnnIndex&&await this.enhanceImpactAnalysisWithGNN(e);let n=await this.impactAnalyzer.analyzeImpact(e);if(n.success){this.updateWorkflowProgress(r,80);let s=n.value;return this.config.enableHypergraph&&this.hypergraph&&(s=await this.enhanceImpactWithHypergraph(e,n.value)),this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.enableSONA&&this.sonaEngine&&await this.storeImpactPattern(e,s),this.config.publishEvents&&await this.publishImpactAnalysisCompleted(e,s),{success:!0,value:s}}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async mapDependencies(e){let r=v();try{this.startWorkflow(r,"dependency");let i=await this.knowledgeGraph.mapDependencies(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async queryKG(e){let r=v();try{this.startWorkflow(r,"query");let i=await this.knowledgeGraph.query(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async indexCodeEmbeddings(e){!this.gnnIndex||!this.rlInitialized||await Ed(this.gnnIndex,this.fileReader,e)}async searchCodeWithGNN(e){return!this.gnnIndex||!this.rlInitialized?[]:xd(this.gnnIndex,e.query)}async enhanceImpactAnalysisWithGNN(e){!this.gnnIndex||!this.rlInitialized||await Pd(this.gnnIndex,this.fileReader,e)}async adaptSearchPattern(e){if(!this.sonaEngine||!this.rlInitialized)return{success:!1,pattern:null,similarity:0};try{let r=Array.isArray(e.filters)?e.filters.find(s=>s.field==="language")?.value:void 0,i={id:`search-${e.type}`,features:[e.query.length,e.type==="semantic"?1:0,e.type==="exact"?1:0,r==="typescript"?1:0,r==="javascript"?1:0]},n=await this.sonaEngine.adaptPattern(i,"coverage-optimization","code-intelligence");return{success:n.success,pattern:n.pattern,similarity:n.similarity}}catch(r){return ie.error("Failed to adapt search pattern:",r instanceof Error?r:void 0),{success:!1,pattern:null,similarity:0}}}async storeImpactPattern(e,r){if(!(!this.sonaEngine||!this.rlInitialized))try{let i={id:`impact-${e.changedFiles.join(",")}`,features:[e.changedFiles.length,e.depth||1,r.directImpact.length,r.transitiveImpact.length,r.impactedTests.length,r.riskLevel==="high"?1:r.riskLevel==="medium"?.5:0]},n={type:"analyze-impact",value:r.riskLevel},s={reward:r.riskLevel==="high"?.8:r.riskLevel==="medium"?.5:.3,success:r.impactedTests.length>0,quality:(r.directImpact.length+r.transitiveImpact.length)/100},a=this.sonaEngine.createPattern(i,n,s,"coverage-optimization","code-intelligence",{changedFiles:e.changedFiles,impactCount:r.directImpact.length+r.transitiveImpact.length,testImpactCount:r.impactedTests.length});ie.info(`Stored impact pattern ${a.id}`)}catch(i){ie.error("Failed to store impact pattern:",i instanceof Error?i:void 0)}}mergeSearchResults(e,r){return kd(e,r)}hashCode(e){return _s(e)}async spawnIndexerAgent(e,r){let i={name:`kg-indexer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["indexing","ast-parsing","graph-building"],config:{workflowId:e,paths:r.paths,incremental:r.incremental}};return this.agentCoordinator.spawn(i)}async spawnSearchAgent(e,r){let i={name:`semantic-search-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["semantic-search","vector-similarity",r.type],config:{workflowId:e,query:r.query,type:r.type}};return this.agentCoordinator.spawn(i)}async spawnImpactAnalyzerAgent(e,r){let i={name:`impact-analyzer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["impact-analysis","dependency-traversal","risk-assessment"],config:{workflowId:e,changedFiles:r.changedFiles,depth:r.depth}};return this.agentCoordinator.spawn(i)}async publishKnowledgeGraphUpdated(e){let r={nodes:e.nodesCreated,edges:e.edgesCreated,filesIndexed:e.filesIndexed,duration:e.duration},i=D(tt.KnowledgeGraphUpdated,"code-intelligence",r);await this.eventBus.publish(i)}async publishImpactAnalysisCompleted(e,r){let i={analysisId:v(),changedFiles:e.changedFiles,impactedFiles:[...r.directImpact.map(s=>s.file),...r.transitiveImpact.map(s=>s.file)],impactedTests:r.impactedTests,riskLevel:r.riskLevel},n=D(tt.ImpactAnalysisCompleted,"code-intelligence",i);await this.eventBus.publish(n)}async publishSemanticSearchCompleted(e,r){let i=D(tt.SemanticSearchCompleted,"code-intelligence",{query:e.query,type:e.type,resultCount:r.total,searchTime:r.searchTime});await this.eventBus.publish(i)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("source-control.FilesChanged",this.handleFilesChanged.bind(this))}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`code-intelligence:test-correlation:${r.runId}`,r,{namespace:"code-intelligence",ttl:86400})}async handleFilesChanged(e){if(!this.config.enableIncrementalIndex)return;let r=e.payload;r.files&&r.files.length>0&&await this.memory.set(`code-intelligence:pending-index:${Date.now()}`,{files:r.files,timestamp:new Date().toISOString()},{namespace:"code-intelligence",ttl:3600})}async indexForSemanticSearch(e){let r=e.slice(0,100);for(let i of r)try{let n=await this.fileReader.readFile(i);n.success&&n.value&&await this.semanticAnalyzer.indexCode(i,n.value)}catch{}}async loadWorkflowState(){let e=await this.memory.get("code-intelligence:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("code-intelligence:coordinator:workflows",e,{namespace:"code-intelligence",persist:!0})}async generateC4Diagrams(e,r){let i=v();try{this.startWorkflow(i,"query");let n={projectPath:e,detectExternalSystems:r?.detectExternalSystems??!0,analyzeComponents:r?.analyzeComponents??!0,analyzeCoupling:r?.analyzeCoupling??!0,includeContext:r?.includeContext??!0,includeContainer:r?.includeContainer??!0,includeComponent:r?.includeComponent??!0,includeDependency:r?.includeDependency??!1,excludePatterns:r?.excludePatterns};this.updateWorkflowProgress(i,20);let s=await this.productFactorsBridge.requestC4Diagrams(n);return s.success?(this.updateWorkflowProgress(i,80),await this.storeC4DiagramsInMemory(e,s.value),this.updateWorkflowProgress(i,100),this.completeWorkflow(i),ie.info(`[CodeIntelligenceCoordinator] C4 diagrams generated for ${e}: ${s.value.components.length} components, ${s.value.externalSystems.length} external systems`)):this.failWorkflow(i,s.error.message),s}catch(n){let s=y(n);return this.failWorkflow(i,s.message),p(s)}}getProductFactorsBridge(){return this.productFactorsBridge}async storeC4DiagramsInMemory(e,r){let i=`c4-diagrams:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:36e5}),await this.memory.set(`c4-components:${this.hashCode(e)}`,r.components,{namespace:"code-intelligence",ttl:36e5}),await this.memory.set(`c4-external-systems:${this.hashCode(e)}`,r.externalSystems,{namespace:"code-intelligence",ttl:36e5})}async collectProjectMetrics(e){if(!this.config.enableMetricCollector||!this.metricCollector)return p(new Error("MetricCollector is not enabled"));try{ie.info(`Collecting real metrics for ${e}`);let r=await this.metricCollector.collectAll(e),i=r.toolsUsed.length>0?r.toolsUsed.join(", "):r.loc.source==="node-native"?"node-native":"fallback";if(ie.info(`[CodeIntelligence] Real metrics collected: ${r.loc.total} LOC, ${r.tests.total} tests, tools: ${i}`),r.loc.source==="node-native"&&ie.info("[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)"),await this.storeProjectMetricsInMemory(e,r),this.config.publishEvents){let n=D("code-intelligence.MetricsCollected","code-intelligence",{projectPath:e,loc:r.loc.total,tests:r.tests.total,toolsUsed:r.toolsUsed});await this.eventBus.publish(n)}return{success:!0,value:r}}catch(r){let i=y(r);return ie.error("Failed to collect metrics:"),p(i)}}async storeProjectMetricsInMemory(e,r){let i=`project-metrics:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:3e5}),await this.memory.set(`loc-metrics:${this.hashCode(e)}`,r.loc,{namespace:"code-intelligence",ttl:3e5}),await this.memory.set(`test-metrics:${this.hashCode(e)}`,r.tests,{namespace:"code-intelligence",ttl:3e5})}getMetricCollector(){return this.metricCollector}getProjectRootFromPaths(e){if(e.length===0)return null;let r=e[0],i=r.split("/"),n="";for(let a of i){n=n?`${n}/${a}`:a;let o=["package.json","Cargo.toml","go.mod","pyproject.toml",".git"];for(let c of o)try{let l=`${n}/${c}`;if(Pa("fs").existsSync(l))return n}catch{}}let s=r.lastIndexOf("/");return s>0?r.substring(0,s):r}isHypergraphEnabled(){return this.config.enableHypergraph&&this.hypergraph!==void 0}async findUntestedFunctions(){return this.hypergraph?Id(this.hypergraph,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findImpactedTestsFromHypergraph(e){return this.hypergraph?Dd(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findCoverageGapsFromHypergraph(e=50){return this.hypergraph?Md(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async buildHypergraphFromIndex(e){return this.hypergraph?Fd(this.hypergraph,e,this.memory,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}getHypergraph(){return this.hypergraph}async enhanceImpactWithHypergraph(e,r){return this.hypergraph?Ld(this.hypergraph,e,r):r}async buildCodeIndexResultFromPaths(e){let{extractCodeIndex:r}=await import("./code-index-extractor-B2KUPAEH.js");return r(e)}async verifyCodePatternDetection(e,r){return $d(e,r,this.consensusMixin,this.domainName)}async verifyImpactAnalysis(e,r){return Od(e,r,this.consensusMixin,this.domainName)}async verifyDependencyMapping(e,r){return Nd(e,r,this.consensusMixin,this.domainName)}};A();var zs=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;pluginConfig;get name(){return"code-intelligence"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{index:this.index.bind(this),search:this.search.bind(this),analyzeImpact:this.analyzeImpact.bind(this),mapDependencies:this.mapDependencies.bind(this),getDependencies:this.mapDependencies.bind(this),queryKG:this.queryKG.bind(this),getMetrics:this.getMetrics.bind(this),getCoordinator:()=>this.coordinator,getKnowledgeGraph:()=>this.knowledgeGraph,getSemanticAnalyzer:()=>this.semanticAnalyzer,getImpactAnalyzer:()=>this.impactAnalyzer}}getTaskHandlers(){return new Map([["index",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.paths;if(!r||r.length===0)return p(new Error("Invalid index payload: missing paths"));let i=e.language?[e.language]:e.languages;return this.coordinator.index({paths:r,languages:i})}],["search",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.query;return r?this.coordinator.search({query:r,type:e.type??"semantic",limit:e.limit}):p(new Error("Invalid search payload: missing query"))}],["analyze-impact",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.changedFiles;return!r||r.length===0?p(new Error("Invalid analyze-impact payload: missing changedFiles")):this.coordinator.analyzeImpact({changedFiles:r})}],["query-dependencies",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.file,n=e.files??(r?[r]:void 0);return!n||n.length===0?p(new Error("Invalid query-dependencies payload: missing file or files")):this.coordinator.mapDependencies({files:n,direction:e.direction??"both",depth:e.depth})}]])}async onInitialize(){this.knowledgeGraph=new Rt(this.memory,this.pluginConfig.knowledgeGraph),this.semanticAnalyzer=new Ot(this.memory,this.pluginConfig.semanticAnalyzer),this.impactAnalyzer=new Br(this.memory,this.knowledgeGraph,this.pluginConfig.impactAnalyzer),this.coordinator=new Oi(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.knowledgeGraph=null,this.semanticAnalyzer=null,this.impactAnalyzer=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPredicted(e);break;default:break}}async index(e){this.ensureInitialized();try{let r=await this.coordinator.index(e);return r.success?this.trackSuccessfulOperation("index",r.value):this.trackFailedOperation("index",r.error),r}catch(r){return this.handleError(r)}}async search(e){this.ensureInitialized();try{let r=await this.coordinator.search(e);return r.success?this.trackSuccessfulOperation("search",r.value):this.trackFailedOperation("search",r.error),r}catch(r){return this.handleError(r)}}async analyzeImpact(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeImpact(e);return r.success?this.trackSuccessfulOperation("impact",r.value):this.trackFailedOperation("impact",r.error),r}catch(r){return this.handleError(r)}}async mapDependencies(e){this.ensureInitialized();try{let r=await this.coordinator.mapDependencies(e);return r.success?this.trackSuccessfulOperation("dependency",r.value):this.trackFailedOperation("dependency",r.error),r}catch(r){return this.handleError(r)}}async queryKG(e){this.ensureInitialized();try{let r=await this.coordinator.queryKG(e);return r.success?this.trackSuccessfulOperation("query",r.value):this.trackFailedOperation("query",r.error),r}catch(r){return this.handleError(r)}}async getMetrics(){this.ensureInitialized();try{let e=this.getHealth();return{success:!0,value:{indexed:e.agents.total,queries:e.agents.idle,impacts:e.agents.active}}}catch(e){return this.handleError(e)}}async handleTestGenerated(e){let r=e.payload;await this.memory.set(`code-intelligence:test-mapping:${r.testId}`,{testFile:r.testFile,sourceFile:r.sourceFile,generatedAt:new Date().toISOString()},{namespace:"code-intelligence",ttl:86400*30})}async handleCoverageGap(e){let r=e.payload;await this.memory.set(`code-intelligence:coverage-gap:${r.gapId}`,r,{namespace:"code-intelligence",ttl:86400*7})}async handleDefectPredicted(e){let r=e.payload;await this.memory.set(`code-intelligence:defect-prediction:${r.predictionId}`,r,{namespace:"code-intelligence",ttl:86400*7})}ensureInitialized(){if(!this._initialized)throw new Error("CodeIntelligencePlugin is not initialized");if(!this.coordinator||!this.knowledgeGraph||!this.semanticAnalyzer||!this.impactAnalyzer)throw new Error("CodeIntelligencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,total:i.agents.total+1,idle:i.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function Tc(u,t,e,r){return new zs(u,t,e,r)}M();A();var he=class u{constructor(t){this._value=t;if(!t||t.trim()==="")throw new Error("FilePath cannot be empty")}_value;get value(){return this._value}get extension(){let t=this._value.split(".");return t.length>1?t[t.length-1]:""}get directory(){let t=this._value.lastIndexOf("/");return t>0?this._value.substring(0,t):""}get filename(){let t=this._value.lastIndexOf("/");return t>=0?this._value.substring(t+1):this._value}equals(t){return this._value===t._value}static create(t){return new u(t)}};var br=class u{constructor(t){this._value=t;if(t<0||t>1)throw new Error("RiskScore must be between 0 and 1")}_value;get value(){return this._value}get percentage(){return this._value*100}get level(){return this._value>=.8?"critical":this._value>=.6?"high":this._value>=.3?"medium":"low"}isHigherThan(t){return this._value>t._value}equals(t){return this._value===t._value}static create(t){return new u(t)}static fromPercentage(t){return new u(t/100)}},_e=class u{constructor(t,e){this._start=t;this._end=e;if(t>e)throw new Error("Start date cannot be after end date")}_start;_end;get start(){return this._start}get end(){return this._end}get durationMs(){return this._end.getTime()-this._start.getTime()}get durationSeconds(){return this.durationMs/1e3}contains(t){return t>=this._start&&t<=this._end}overlaps(t){return this._start<=t._end&&t._start<=this._end}equals(t){return this._start.getTime()===t._start.getTime()&&this._end.getTime()===t._end.getTime()}static create(t,e){return new u(t,e)}static lastNDays(t){let e=new Date,r=new Date(e.getTime()-t*24*60*60*1e3);return new u(r,e)}},zt=class u{constructor(t,e,r,i){this._major=t;this._minor=e;this._patch=r;this._prerelease=i}_major;_minor;_patch;_prerelease;get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let t=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${t}-${this._prerelease}`:t}isNewerThan(t){return this._major!==t._major?this._major>t._major:this._minor!==t._minor?this._minor>t._minor:this._patch>t._patch}equals(t){return this._major===t._major&&this._minor===t._minor&&this._patch===t._patch&&this._prerelease===t._prerelease}static create(t,e,r,i){return new u(t,e,r,i)}static parse(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!e)throw new Error(`Invalid version format: ${t}`);return new u(parseInt(e[1]),parseInt(e[2]),parseInt(e[3]),e[4])}};var Bs={defaultRuleSets:["owasp-top-10","cwe-sans-25"],maxConcurrentScans:4,timeout:3e5,enableFalsePositiveDetection:!0,dastMaxDepth:5,dastActiveScanning:!1,enableLLMAnalysis:!0,llmModelTier:4,enableSemgrep:!0};M();var Ac=[{id:"sqli-string-concat",pattern:/query\s*\(\s*['"`].*\+.*['"`]\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via String Concatenation",description:"SQL query constructed using string concatenation with potentially untrusted input",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries or prepared statements instead of string concatenation",fixExample:'db.query("SELECT * FROM users WHERE id = $1", [userId])'},{id:"sqli-template-literal",pattern:/execute\s*\(\s*`[^`]*\$\{[^}]+\}[^`]*`\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via Template Literal",description:"SQL query constructed using template literals with embedded expressions",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries instead of template literals for SQL",fixExample:'db.execute("DELETE FROM users WHERE id = ?", [userId])'},{id:"sqli-raw-query",pattern:/\.raw\s*\(\s*['"`].*\+|\.raw\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"high",title:"SQL Injection via Raw Query",description:"Raw SQL query with potential user input interpolation",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Avoid raw queries with user input; use ORM methods or parameterized queries"},{id:"sqli-exec",pattern:/exec(?:ute)?(?:Sql|Query)?\s*\([^)]*\+[^)]*\)/gi,category:"injection",severity:"critical",title:"SQL Injection via Dynamic Execution",description:"Dynamic SQL execution with string concatenation detected",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Never concatenate user input into SQL queries"}],Ec=[{id:"xss-innerhtml",pattern:/\.innerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via innerHTML Assignment",description:"Direct innerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Use textContent for text, or sanitize HTML with DOMPurify before innerHTML assignment",fixExample:"element.textContent = userInput; // or DOMPurify.sanitize(userInput)"},{id:"xss-document-write",pattern:/document\.write\s*\([^)]+\)/g,category:"xss",severity:"high",title:"XSS via document.write",description:"document.write() can execute scripts from untrusted data",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Avoid document.write(); use DOM manipulation methods instead",fixExample:"document.body.appendChild(document.createTextNode(text))"},{id:"xss-dangerously-set",pattern:/dangerouslySetInnerHTML\s*=\s*\{/g,category:"xss",severity:"medium",title:"React dangerouslySetInnerHTML Usage",description:"dangerouslySetInnerHTML bypasses React XSS protections",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize HTML content with DOMPurify before using dangerouslySetInnerHTML",fixExample:"dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}"},{id:"xss-eval",pattern:/eval\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via eval()",description:"eval() executes arbitrary code and is a major security risk",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Never use eval(); use JSON.parse() for JSON data or safer alternatives",fixExample:"JSON.parse(jsonString) // instead of eval(jsonString)"},{id:"xss-new-function",pattern:/new\s+Function\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via Function Constructor",description:"Function constructor can execute arbitrary code like eval()",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Avoid the Function constructor; use predefined functions instead"},{id:"xss-outerhtml",pattern:/\.outerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via outerHTML Assignment",description:"Direct outerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize content before outerHTML assignment"}],xc=[{id:"secret-aws-access-key",pattern:/['"`]AKIA[0-9A-Z]{16}['"`]/g,category:"sensitive-data",severity:"critical",title:"AWS Access Key Detected",description:"Hardcoded AWS Access Key ID found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or AWS Secrets Manager for credentials",fixExample:"const accessKey = process.env.AWS_ACCESS_KEY_ID"},{id:"secret-aws-secret-key",pattern:/['"`][A-Za-z0-9/+=]{40}['"`]/g,category:"sensitive-data",severity:"critical",title:"Potential AWS Secret Key Detected",description:"Potential hardcoded AWS Secret Access Key found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store secrets in environment variables or secrets manager"},{id:"secret-openai-key",pattern:/['"`]sk-[a-zA-Z0-9]{48,}['"`]/g,category:"sensitive-data",severity:"critical",title:"OpenAI API Key Detected",description:"Hardcoded OpenAI API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.OPENAI_API_KEY"},{id:"secret-generic-password",pattern:/password\s*[:=]\s*['"`][^'"`]{4,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded Password Detected",description:"Hardcoded password found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Never hardcode passwords; use environment variables or secrets manager",fixExample:"const password = process.env.DB_PASSWORD"},{id:"secret-api-key",pattern:/api[_-]?key\s*[:=]\s*['"`][a-zA-Z0-9_\-]{16,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded API Key Detected",description:"Hardcoded API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.API_KEY"},{id:"secret-jwt",pattern:/['"`]eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+['"`]/g,category:"sensitive-data",severity:"high",title:"Hardcoded JWT Token Detected",description:"Hardcoded JWT token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Generate JWT tokens dynamically; never hardcode them"},{id:"secret-private-key",pattern:/-----BEGIN\s+(RSA|EC|OPENSSH|DSA)?\s*PRIVATE\s+KEY-----/g,category:"sensitive-data",severity:"critical",title:"Private Key Detected",description:"Private key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store private keys in secure key management systems, not in code"},{id:"secret-github-token",pattern:/['"`]ghp_[a-zA-Z0-9]{36}['"`]|['"`]github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59}['"`]/g,category:"sensitive-data",severity:"critical",title:"GitHub Token Detected",description:"Hardcoded GitHub personal access token found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or GitHub Actions secrets"},{id:"secret-slack-token",pattern:/['"`]xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*['"`]/g,category:"sensitive-data",severity:"high",title:"Slack Token Detected",description:"Hardcoded Slack token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for Slack tokens"},{id:"secret-generic-assignment",pattern:/\b\w*(?:SECRET|secret)(?:_KEY|_key|Key)?\s*[:=]\s*['"`][^'"`]{4,}['"`]/g,category:"sensitive-data",severity:"high",title:"Generic Secret Assignment Detected",description:"Hardcoded secret assignment (SECRET_KEY, JWT_SECRET, APP_SECRET, etc.) found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or a secrets manager instead of hardcoding secrets",fixExample:"const secretKey = process.env.SECRET_KEY"}],Pc=[{id:"path-traversal-readfile",pattern:/(?:readFile|readFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Read",description:"File read operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths; use path.resolve() and check against base directory",fixExample:"const safePath = path.resolve(baseDir, path.basename(userInput))"},{id:"path-traversal-pattern",pattern:/\.\.\/.*\.\.\//g,category:"access-control",severity:"medium",title:"Path Traversal Pattern Detected",description:"Suspicious path traversal pattern (../) found in code",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate paths and ensure they resolve within expected directories"},{id:"path-traversal-writefile",pattern:/(?:writeFile|writeFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Write",description:"File write operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate file paths before writing; ensure path is within allowed directory"},{id:"path-traversal-createstream",pattern:/createReadStream\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via Stream",description:"Stream creation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths before creating streams"}],kc=[{id:"cmd-injection-exec",pattern:/exec\s*\([^)]*\+[^)]*\)|exec\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via exec()",description:"Shell command execution with unsanitized input",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use execFile() with argument array instead of exec() with string concatenation",fixExample:'execFile("command", [arg1, arg2], callback)'},{id:"cmd-injection-spawn",pattern:/spawn\s*\(\s*[^,]+\+|spawn\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via spawn()",description:"Process spawn with potentially unsanitized command",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use spawn with command and args array; validate inputs",fixExample:'spawn("command", [sanitizedArg1, sanitizedArg2])'},{id:"cmd-injection-shell-true",pattern:/spawn\s*\([^)]+,\s*\{[^}]*shell\s*:\s*true/g,category:"injection",severity:"high",title:"Dangerous Shell Option in spawn()",description:"spawn() with shell: true can enable command injection",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Avoid shell: true option; use direct command execution"}],Ic=[{id:"misc-cors-wildcard",pattern:/cors\s*\(\s*\{[^}]*origin\s*:\s*['"]\*['"]/gi,category:"security-misconfiguration",severity:"medium",title:"Permissive CORS Configuration",description:"CORS allows all origins (*) which may expose sensitive data",owaspId:"A05:2021",cweId:"CWE-942",remediation:"Restrict CORS to specific trusted origins",fixExample:'cors({ origin: ["https://trusted-domain.com"] })'},{id:"misc-debug-enabled",pattern:/debug\s*[:=]\s*true|DEBUG\s*[:=]\s*['"]?true['"]?/gi,category:"security-misconfiguration",severity:"low",title:"Debug Mode Enabled",description:"Debug mode may expose sensitive information in production",owaspId:"A05:2021",cweId:"CWE-489",remediation:"Disable debug mode in production environments"},{id:"misc-ssl-disabled",pattern:/rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0['"]?/g,category:"security-misconfiguration",severity:"high",title:"TLS Certificate Validation Disabled",description:"Disabling TLS certificate validation exposes to MITM attacks",owaspId:"A05:2021",cweId:"CWE-295",remediation:"Always enable TLS certificate validation in production"},{id:"misc-helmet-missing",pattern:/app\.use\s*\(\s*express\s*\(\s*\)\s*\)/g,category:"security-misconfiguration",severity:"low",title:"Express App Without Security Headers",description:"Express app initialized without helmet or security headers",owaspId:"A05:2021",cweId:"CWE-693",remediation:"Use helmet middleware for security headers",fixExample:"app.use(helmet())"}],Dc=[{id:"deser-yaml-load",pattern:/yaml\.load\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe YAML Deserialization",description:"yaml.load() can execute arbitrary code from untrusted YAML",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use yaml.safeLoad() or schema-constrained loading",fixExample:"yaml.load(content, { schema: yaml.SAFE_SCHEMA })"},{id:"deser-serialize-js",pattern:/serialize\s*\([^)]+\)|unserialize\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe Serialization Function",description:"Node serialize/unserialize functions can execute arbitrary code",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use JSON.parse/stringify for serialization"}],Mc=[{id:"auth-weak-jwt-secret",pattern:/jwt\.sign\s*\([^)]+,\s*['"][a-zA-Z0-9]{1,16}['"]/g,category:"broken-auth",severity:"high",title:"Weak JWT Secret",description:"JWT signed with a weak or short secret key",owaspId:"A07:2021",cweId:"CWE-327",remediation:"Use a strong, randomly generated secret of at least 256 bits"},{id:"auth-no-algorithm",pattern:/jwt\.verify\s*\([^)]+\)\s*(?!.*algorithm)/g,category:"broken-auth",severity:"medium",title:"JWT Without Algorithm Specification",description:"JWT verification without explicit algorithm can be exploited",owaspId:"A07:2021",cweId:"CWE-347",remediation:"Always specify the expected algorithm in JWT verification",fixExample:'jwt.verify(token, secret, { algorithms: ["HS256"] })'}],qs=[...Ac,...Ec,...xc,...Pc,...kc,...Ic,...Dc,...Mc],Ni=[{id:"owasp-top-10",name:"OWASP Top 10",description:"OWASP Top 10 most critical security risks",ruleCount:45,categories:["injection","broken-auth","sensitive-data","xxe","access-control","security-misconfiguration","xss","insecure-deserialization","vulnerable-components","insufficient-logging"]},{id:"cwe-sans-25",name:"CWE/SANS Top 25",description:"Most dangerous software errors",ruleCount:38,categories:["injection","xss","access-control","sensitive-data","broken-auth"]},{id:"nodejs-security",name:"Node.js Security",description:"Node.js specific security rules",ruleCount:25,categories:["injection","xss","sensitive-data","security-misconfiguration"]},{id:"typescript-security",name:"TypeScript Security",description:"TypeScript specific security rules",ruleCount:20,categories:["injection","xss","sensitive-data"]}];A();H();A();H();import{execFile as sy}from"child_process";import{promisify as ay}from"util";import*as zd from"path";var Fc=ay(sy);async function Vi(){try{return await Fc("semgrep",["--version"],{timeout:5e3}),!0}catch{return!1}}async function Vd(){try{let{stdout:u}=await Fc("semgrep",["--version"],{timeout:5e3});return u.trim()}catch{return null}}async function oy(u){let t={target:u.target||".",config:u.config||"auto",exclude:u.exclude||["node_modules",".git","dist","build","coverage"],maxFileSize:u.maxFileSize||5e6,timeout:u.timeout||300,verbose:u.verbose||!1};if(!await Vi())return{success:!1,findings:[],errors:["Semgrep is not installed. Install with: pip install semgrep"]};try{let r=["scan",`--config=${t.config}`,"--json",t.verbose?"--verbose":"--quiet",`--max-target-bytes=${t.maxFileSize}`];for(let o of t.exclude)r.push(`--exclude=${o}`);r.push(t.target);let i=(t.timeout??300)*1e3,{stdout:n,stderr:s}=await Fc("semgrep",r,{timeout:i,maxBuffer:50*1024*1024,cwd:zd.isAbsolute(t.target)?void 0:process.cwd()}),a=_d(n);return s&&t.verbose&&a.errors.push(s),a.version=await Vd()||void 0,a}catch(r){let i=r;if(i.stdout)try{let n=_d(i.stdout);return n.version=await Vd()||void 0,n}catch{}return{success:!1,findings:[],errors:[i.message??String(r)]}}}function _d(u){try{let t=E(u),e=t.results||t.findings||[],r=t.errors?.map(i=>i.message||String(i))||[];return{success:!0,findings:e.map(i=>({check_id:i.check_id||i.rule_id||"unknown",path:i.path,start:{line:i.start?.line||1,col:i.start?.col||1},end:{line:i.end?.line||i.start?.line||1,col:i.end?.col||1},extra:{message:i.extra?.message||i.message||"Security issue detected",severity:i.extra?.severity||i.severity||"WARNING",lines:i.extra?.lines||"",metadata:{cwe:i.extra?.metadata?.cwe||i.metadata?.cwe,owasp:i.extra?.metadata?.owasp||i.metadata?.owasp,category:i.extra?.metadata?.category||i.metadata?.category,description:i.extra?.metadata?.description||i.metadata?.description,fix:i.extra?.metadata?.fix||i.extra?.fix,references:i.extra?.metadata?.references||i.metadata?.references,confidence:i.extra?.metadata?.confidence||i.metadata?.confidence}}})),errors:r}}catch(t){return{success:!1,findings:[],errors:[`Failed to parse semgrep output: ${T(t)}`]}}}async function Gs(u,t,e){let r={"owasp-top-10":"p/owasp-top-ten","cwe-sans-25":"p/cwe-top-25","nodejs-security":"p/nodejs","typescript-security":"p/typescript","javascript-security":"p/javascript","react-security":"p/react","express-security":"p/express",secrets:"p/secrets","sql-injection":"p/sql-injection",xss:"p/xss","command-injection":"p/command-injection","path-traversal":"p/path-traversal"},i=t.map(n=>r[n]||`p/${n}`).join(",");return oy({...e,target:u,config:i||"auto"})}function cy(u){return{ERROR:"high",WARNING:"medium",INFO:"low"}[u]||"medium"}function Hs(u){return u.map(t=>({id:t.check_id,title:t.check_id.split(".").pop()||t.check_id,description:t.extra.message,severity:cy(t.extra.severity),file:t.path,line:t.start.line,column:t.start.col,snippet:t.extra.lines,cweId:t.extra.metadata?.cwe?.[0],owaspCategory:t.extra.metadata?.owasp?.[0],remediation:t.extra.metadata?.fix||"Review and fix the identified security issue",references:t.extra.metadata?.references||[]}))}var ly=R.create("security-compliance/sast-scanner"),wr=class{config;memory;llmRouter;activeScans;constructor(t,e,r,i){this.config=t,this.memory=e,this.llmRouter=r,this.activeScans=i||new Map}async scanFiles(t){return this.scanWithRules(t,this.config.defaultRuleSets)}async scanWithRules(t,e){let r=v();try{if(t.length===0)return p(new Error("No files provided for scanning"));this.activeScans.set(r,"running");let i=Date.now(),n=Ni.filter(h=>e.includes(h.id));if(n.length===0)return p(new Error(`No valid rule sets found: ${e.join(", ")}`));let[s,a]=await Promise.all([this.runPatternScanning(t,n),this.runSemgrepScanning(t,e)]),o=this.mergeVulnerabilities(s.vulnerabilities,a),c=s.linesScanned,l=Date.now()-i,d=this.calculateSummary(o,t.length,l),m=n.reduce((h,b)=>h+b.ruleCount,0),g={filesScanned:t.length,linesScanned:c,rulesApplied:m+(a.length>0?a.length:0)};return await this.storeScanResults(r,"sast",o,d),this.activeScans.set(r,"completed"),f({scanId:r,vulnerabilities:o,summary:d,coverage:g})}catch(i){return this.activeScans.set(r,"failed"),p(y(i))}}async runPatternScanning(t,e){let r=[],i=0;for(let n of t){let s=await this.analyzeFile(n,e);r.push(...s.vulnerabilities),i+=s.linesScanned}return{vulnerabilities:r,linesScanned:i}}async runSemgrepScanning(t,e){if(!this.config.enableSemgrep)return[];try{if(!await Vi())return[];let i=this.resolveTargetDirectory(t),n=await Gs(i,e);return!n.success||n.findings.length===0?[]:Hs(n.findings).map(a=>({id:v(),cveId:void 0,title:a.title,description:`[semgrep] ${a.description}`,severity:a.severity,category:this.mapSemgrepCategory(a.owaspCategory),location:{file:a.file,line:a.line,column:a.column,snippet:a.snippet},remediation:{description:a.remediation,estimatedEffort:"moderate",automatable:!1},references:a.references}))}catch{return[]}}resolveTargetDirectory(t){if(t.length===0)return".";if(t.length===1)return t[0].directory||".";let e=t.map(a=>a.directory||"."),r=e[0],i=r.length;for(let a=1;a<e.length;a++){let o=e[a],c=Math.min(i,o.length),l=0;for(;l<c&&r[l]===o[l];)l++;i=l}let n=r.substring(0,i),s=n.lastIndexOf("/");return s>0?n.substring(0,s):n||"."}mapSemgrepCategory(t){if(!t)return"injection";let e={A01:"access-control",A02:"sensitive-data",A03:"injection",A04:"insecure-deserialization",A05:"security-misconfiguration",A06:"vulnerable-components",A07:"broken-auth",A08:"insecure-deserialization",A09:"insufficient-logging",A10:"xxe"};for(let[r,i]of Object.entries(e))if(t.startsWith(r))return i;return"injection"}mergeVulnerabilities(t,e){if(e.length===0)return t;if(t.length===0)return e;let r=new Set(t.map(n=>`${n.location.file}:${n.location.line??0}:${n.category}`)),i=e.filter(n=>!r.has(`${n.location.file}:${n.location.line??0}:${n.category}`));return[...t,...i]}async getAvailableRuleSets(){let t=await this.memory.get("security:custom-rule-sets");return[...Ni,...t||[]]}async checkFalsePositive(t){try{if(!this.config.enableFalsePositiveDetection)return f({isFalsePositive:!1,confidence:0,reason:"False positive detection is disabled"});let e=await this.analyzeFalsePositive(t);return await this.memory.set(`security:fp-check:${t.id}`,{vulnerability:t,analysis:e},{namespace:"security-compliance",ttl:86400*30}),f(e)}catch(e){return p(y(e))}}async analyzeFile(t,e){let r=[],i=t.value,n=t.extension,s,a;try{s=await(await import("fs/promises")).readFile(i,"utf-8"),a=s.split(`
2892
+ `).filter(o=>o.startsWith("Test")||o.startsWith("Example")||o.startsWith("Benchmark")),i=r.filter(o=>o.startsWith("Test")).length,n=r.filter(o=>o.startsWith("Test")&&!o.includes("Integration")&&!o.includes("E2E")).length,s=r.filter(o=>o.includes("Integration")).length,a=r.filter(o=>o.includes("E2E")).length;return{total:i,unit:n,integration:s,e2e:a,source:"go"}}catch{return{total:0,unit:0,integration:0,e2e:0,source:"go"}}}function Mi(u,t){let e=0,r=0,i=0,n=0;function s(a){if(!ge(a))return;let o=df(a,{withFileTypes:!0});for(let c of o){let l=ve(a,c.name);if(c.isDirectory()){if(t.excludeDirs.includes(c.name))continue;s(l)}else if(c.isFile()&&vf(c.name)){let d=mf(c.name).toLowerCase(),m=0;[".ts",".tsx",".js",".jsx",".mjs"].includes(d)?m=Td(l):d===".py"?m=bf(l):d===".rs"?m=wf(l):d===".go"&&(m=Cf(l)),e+=m;let g=l.toLowerCase();g.includes("e2e")||g.includes("end-to-end")?n+=m:g.includes("integration")?i+=m:r+=m}}}return s(u),{total:e,unit:r,integration:i,e2e:n,source:"fallback"}}function vf(u){let t=u.toLowerCase();return t.includes(".test.")||t.includes(".spec.")||t.includes("_test.")||t.startsWith("test_")||t.endsWith("_test.ts")||t.endsWith("_test.js")||t.endsWith("_test.py")||t.endsWith("_test.go")||t.endsWith("_test.rs")}function Td(u){try{let t=Li(u,"utf-8"),e=t.match(/\bit\s*\(/g)||[],r=t.match(/\btest\s*\(/g)||[];return e.length+r.length}catch{return 0}}function bf(u){try{let t=Li(u,"utf-8"),e=t.match(/\bdef\s+test_\w+\s*\(/g)||[],r=t.match(/\basync\s+def\s+test_\w+\s*\(/g)||[];return e.length+r.length}catch{return 0}}function wf(u){try{let t=Li(u,"utf-8"),e=t.match(/#\[test\]/g)||[],r=t.match(/#\[tokio::test\]/g)||[],i=t.match(/#\[async_std::test\]/g)||[];return e.length+r.length+i.length}catch{return 0}}function Cf(u){try{return(Li(u,"utf-8").match(/\bfunc\s+Test\w+\s*\(/g)||[]).length}catch{return 0}}function Ns(u,t,e){let r=u,i=0,n=0;return(ge(ve(e,"tests","integration"))||ge(ve(e,"test","integration"))||ge(ve(e,"__tests__","integration")))&&(i=Math.floor(u*.2),r-=i),(ge(ve(e,"tests","e2e"))||ge(ve(e,"test","e2e"))||ge(ve(e,"e2e"))||ge(ve(e,"cypress")))&&(n=Math.floor(u*.1),r-=n),{total:u,unit:Math.max(0,r),integration:i,e2e:n,source:t}}var Cc=class{config;cache=new Map;cacheHits=0;cacheMisses=0;constructor(t={}){this.config={...Nt,...t}}async collectAll(t){let e=`all:${t}`;if(this.config.enableCache){let l=this.getFromCache(e);if(l)return l}let[r,i,n]=await Promise.all([this.countLOC(t),this.countTests(t),this.countPatterns(t,this.detectLanguage(t))]),s=[];r.source!=="fallback"&&s.push(r.source),i.source!=="fallback"&&s.push(i.source);let a=r.source==="fallback"?"approximate":"accurate",o=i.source==="fallback"?"approximate":"accurate",c={loc:r,tests:i,patterns:n,collectedAt:new Date,toolsUsed:s,accuracy:{loc:a,tests:o,overall:a==="accurate"&&o==="accurate"?"accurate":"approximate"}};return this.config.enableCache&&this.setInCache(e,c),c}async countLOC(t){let e=`loc:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await fc(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countTests(t){let e=`tests:${t}`;if(this.config.enableCache){let i=this.getFromCache(e);if(i)return i}let r=await bc(t,this.config);return this.config.enableCache&&this.setInCache(e,r),r}async countPatterns(t,e){let r=`patterns:${t}:${e}`;if(this.config.enableCache){let n=this.getFromCache(r);if(n)return n}let i=this.countPatternsInternal(t,e);return this.config.enableCache&&this.setInCache(r,i),i}checkTools(){let t=yc(),e=wc(process.cwd());return[...t,...e]}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0}getCacheStats(){return{hits:this.cacheHits,misses:this.cacheMisses,size:this.cache.size}}getFromCache(t){let e=this.cache.get(t);return e&&Date.now()-e.timestamp<this.config.cacheTTL?(this.cacheHits++,e.data):(this.cacheMisses++,null)}setInCache(t,e){this.cache.set(t,{data:e,timestamp:Date.now()})}detectLanguage(t){return Vt(_t(t,"Cargo.toml"))?"rust":Vt(_t(t,"go.mod"))?"go":Vt(_t(t,"pyproject.toml"))||Vt(_t(t,"requirements.txt"))?"python":Vt(_t(t,"package.json"))?Vt(_t(t,"tsconfig.json"))?"typescript":"javascript":"unknown"}countPatternsInternal(t,e){let r={},i=0,n=0,s=0,a=0,o=this.getPatternsForLanguage(e);function c(l){if(!Vt(l))return;let d=Rf(l,{withFileTypes:!0});for(let m of d){let g=_t(l,m.name);if(m.isDirectory()){if(["node_modules","dist","coverage","build",".git","vendor","target"].includes(m.name))continue;c(g)}else if(m.isFile()){let h=Tf(m.name).toLowerCase();if(Af(h,e)){let b=Ef(g,o);(b.unwraps>0||b.unsafeBlocks>0||b.todoComments>0||b.consoleStatements>0)&&(r[g]=b,i+=b.unwraps,n+=b.unsafeBlocks,s+=b.todoComments,a+=b.consoleStatements)}}}}return c(t),{unwraps:i,unsafeBlocks:n,todoComments:s,consoleStatements:a,byFile:r}}getPatternsForLanguage(t){switch(t){case"rust":return{unwrap:/\.unwrap\s*\(/g,unsafe:/\bunsafe\s*\{/g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(println!|print!|eprintln!|eprint!|dbg!)\s*\(/g};case"python":return{unwrap:null,unsafe:null,todo:/#\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(print)\s*\(/g};case"go":return{unwrap:null,unsafe:/\bunsafe\./g,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\b(fmt\.Print|fmt\.Printf|fmt\.Println|log\.Print|log\.Printf|log\.Println)\s*\(/g};default:return{unwrap:null,unsafe:null,todo:/\/\/\s*(TODO|FIXME|HACK|XXX)[\s:]/gi,console:/\bconsole\.(log|debug|info|warn|error)\s*\(/g}}}};function Af(u,t){switch(t){case"rust":return u===".rs";case"python":return[".py",".pyw"].includes(u);case"go":return u===".go";case"typescript":return[".ts",".tsx"].includes(u);case"javascript":return[".js",".jsx",".mjs",".cjs"].includes(u);default:return[".ts",".tsx",".js",".jsx",".py",".rs",".go"].includes(u)}}function Ef(u,t){try{let e=Sf(u,"utf-8");return{unwraps:t.unwrap?(e.match(t.unwrap)||[]).length:0,unsafeBlocks:t.unsafe?(e.match(t.unsafe)||[]).length:0,todoComments:(e.match(t.todo)||[]).length,consoleStatements:(e.match(t.console)||[]).length}}catch{return{unwraps:0,unsafeBlocks:0,todoComments:0,consoleStatements:0}}}function Ad(u={}){return new Cc(u)}M();A();se();Yt();A();Yt();A();Yt();A();Yt();A();se();Yt();A();var NO=300*1e3;qe();qe();M();qe();var YO=R.create("temporal-compression");A();M();var t1=R.create("ruvector-server-client");qm();import{Buffer as _f}from"buffer";var c1=_f.from("COGCNTNR","ascii");qe();qe();var Bf={capacity:1e4,minCoherenceThreshold:.3,highTierThreshold:.8,mediumTierThreshold:.5,highTierWeight:3,mediumTierWeight:1.5,lowTierWeight:1},Sc=class{config;cusumDetector;buffer;totalSeen=0;totalAdmitted=0;totalRejected=0;totalEvicted=0;totalSampled=0;constructor(t){this.config={...Bf,...t},this.cusumDetector=new _a({threshold:this.config.cusumConfig?.threshold??5,slack:this.config.cusumConfig?.slack??.5,resetOnAlarm:!1,warmupSamples:20}),this.buffer=[]}admit(t,e,r){this.totalSeen++;let i=this.getEffectiveThreshold();if(r<i)return this.totalRejected++,!1;let n=this.classifyTier(r),s={id:t,data:e,coherenceScore:r,tier:n,admittedAt:Date.now(),replayCount:0};if(this.buffer.length<this.config.capacity)return this.buffer.push(s),this.totalAdmitted++,!0;let a=Math.floor(Math.random()*this.totalAdmitted),o=this.getTierWeight(n),c=Math.floor(a/o);if(c<this.config.capacity){let l=this.selectEvictionTarget(c);return this.buffer[l]=s,this.totalEvicted++,this.totalAdmitted++,!0}return this.totalRejected++,!1}sample(t,e){if(this.buffer.length===0)return[];let r=e!==void 0?this.buffer.filter(a=>a.coherenceScore>=e):this.buffer;if(r.length===0)return[];if(t>=r.length){let a=[...r];for(let o of a)o.replayCount++;return this.totalSampled+=a.length,a}let i=r.map(a=>this.getTierWeight(a.tier)),n=[],s=new Set;for(;n.length<t&&s.size<r.length;){let a=0;for(let l=0;l<r.length;l++)s.has(l)||(a+=i[l]);if(a<=0)break;let o=Math.random()*a,c=-1;for(let l=0;l<r.length;l++)if(!s.has(l)&&(o-=i[l],o<=0)){c=l;break}if(c===-1){for(let l=0;l<r.length;l++)if(!s.has(l)){c=l;break}}c>=0&&(s.add(c),r[c].replayCount++,n.push(r[c]))}return this.totalSampled+=n.length,n}size(){return this.buffer.length}getStats(){let t={high:0,medium:0,low:0};for(let e of this.buffer)t[e.tier]++;return{size:this.buffer.length,capacity:this.config.capacity,totalAdmitted:this.totalAdmitted,totalRejected:this.totalRejected,totalEvicted:this.totalEvicted,tierCounts:t,totalSampled:this.totalSampled}}getByTier(t){return this.buffer.filter(e=>e.tier===t)}clear(){this.buffer.length=0,this.totalSeen=0,this.totalAdmitted=0,this.totalRejected=0,this.totalEvicted=0,this.totalSampled=0,this.cusumDetector.reset()}getCusumState(t){return this.cusumDetector.getState(t)}observeCoherence(t,e){return this.cusumDetector.update(t,e)}classifyTier(t){return t>=this.config.highTierThreshold?"high":t>=this.config.mediumTierThreshold?"medium":"low"}getTierWeight(t){switch(t){case"high":return this.config.highTierWeight;case"medium":return this.config.mediumTierWeight;case"low":return this.config.lowTierWeight}}getEffectiveThreshold(){let t=["retrieve","write","learn","act"],e=!1;for(let r of t)if(this.cusumDetector.getState(r).driftDetected){e=!0;break}return e?Math.min(this.config.minCoherenceThreshold*1.5,.9):this.config.minCoherenceThreshold}selectEvictionTarget(t){let e=Math.min(10,this.buffer.length),r=Math.max(0,t-Math.floor(e/2)),i=Math.min(this.buffer.length,r+e),n=t,s=this.buffer[t].coherenceScore;for(let a=r;a<i;a++)this.buffer[a].coherenceScore<s&&(s=this.buffer[a].coherenceScore,n=a);return n}};se();var yr=R.create("code-intelligence/gnn");async function Ed(u,t,e){try{for(let r of e)try{let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Rc(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}};u.addEmbedding(s)}}catch(i){yr.error(`Failed to index ${r}:`,i instanceof Error?i:void 0)}yr.info(`Indexed ${e.length} code embeddings`)}catch(r){yr.error("Failed to index code embeddings:",r instanceof Error?r:void 0)}}async function Rc(u,t){let e=[],r=u.split(".").pop(),i=_s(r||"");e.push(i%1e3/1e3),e.push(Math.min(1,t.length/1e4));let n=t.match(/function\s+\w+/g)||[],s=t.match(/class\s+\w+/g)||[];e.push(Math.min(1,(n.length+s.length)/50));let a=t.match(/import\s+.*from|require\s*\(/g)||[];e.push(Math.min(1,a.length/20));let o=t.match(/for\s*\(|while\s*\(/g)||[],c=t.match(/if\s*\(/g)||[];e.push(Math.min(1,(o.length+c.length)/30));let l=t.match(/\/\/.*|\/\*[\s\S]*?\*\//g)||[];e.push(Math.min(1,l.length/50));let d=_s(t.slice(0,500));for(let m=e.length;m<384;m++)e.push(d*(m+1)%1e4/1e4);return e.slice(0,384)}async function xd(u,t){try{let r={vector:await Rc("query",t),dimension:384,namespace:"code",text:t,timestamp:Date.now(),quantization:"none"};return u.search(r,{limit:10,namespace:"code"}).map(n=>({file:n.metadata?.path??`file-${n.id}`,similarity:1-n.distance}))}catch(e){return yr.error("Failed to search with GNN:",e instanceof Error?e:void 0),[]}}async function Pd(u,t,e){try{for(let r of e.changedFiles){let i=await t.readFile(r);if(i.success&&i.value){let s={vector:await Rc(r,i.value),dimension:384,namespace:"code",text:i.value.slice(0,1e3),timestamp:Date.now(),quantization:"none",metadata:{path:r}},a=u.search(s,{limit:5,namespace:"code"});yr.info(`Found ${a.length} semantically similar files to ${r}`)}}}catch(r){yr.error("Failed to enhance impact analysis:",r instanceof Error?r:void 0)}}function kd(u,t){let e=new Map,r=new Map;for(let i of u)e.set(i.file,i.score),r.set(i.file,i);for(let i of t){let n=e.get(i.file);n!==void 0?e.set(i.file,(n+i.similarity)/2):(e.set(i.file,i.similarity*.8),r.set(i.file,{file:i.file,snippet:"",score:i.similarity*.8,highlights:[]}))}return Array.from(r.values()).map(i=>({...i,score:e.get(i.file)??i.score})).sort((i,n)=>n.score-i.score).slice(0,20)}function _s(u){let t=0;for(let e=0;e<u.length;e++)t=(t<<5)-t+u.charCodeAt(e),t=t|0;return Math.abs(t)}M();A();var Ve=R.create("code-intelligence/hypergraph");async function Id(u,t,e){try{let r=await u.findUntestedFunctions();if(Ve.info(`[CodeIntelligence] Found ${r.length} untested functions via hypergraph`),e){let i=D("code-intelligence.UntestedFunctionsFound","code-intelligence",{count:r.length,functions:r.slice(0,10).map(n=>({name:n.name,file:n.filePath,complexity:n.complexity}))});await t.publish(i)}return{success:!0,value:r}}catch(r){let i=y(r);return Ve.error("Failed to find untested functions:"),p(i)}}async function Dd(u,t,e,r){if(t.length===0)return{success:!0,value:[]};try{let i=await u.findImpactedTests(t);if(Ve.info(`[CodeIntelligence] Found ${i.length} impacted tests for ${t.length} changed files via hypergraph`),r){let n=D("code-intelligence.ImpactedTestsFound","code-intelligence",{changedFiles:t,testCount:i.length,tests:i.slice(0,10).map(s=>({name:s.name,file:s.filePath}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return Ve.error("Failed to find impacted tests:"),p(n)}}async function Md(u,t,e,r){try{let i=await u.findCoverageGaps(t);if(Ve.info(`[CodeIntelligence] Found ${i.length} coverage gaps (functions with <=${t}% coverage) via hypergraph`),r){let n=D("code-intelligence.CoverageGapsFound","code-intelligence",{maxCoverage:t,gapCount:i.length,gaps:i.slice(0,10).map(s=>({name:s.name,file:s.filePath,coverage:s.coverage,complexity:s.complexity}))});await e.publish(n)}return{success:!0,value:i}}catch(i){let n=y(i);return Ve.error("Failed to find coverage gaps:"),p(n)}}async function Fd(u,t,e,r,i){try{Ve.info(`[CodeIntelligence] Building hypergraph from ${t.files.length} indexed files`);let n=await u.buildFromIndexResult(t);if(Ve.info(`[CodeIntelligence] Hypergraph built: ${n.nodesCreated} nodes created, ${n.nodesUpdated} nodes updated, ${n.edgesCreated} edges created (${n.durationMs}ms)`),await e.set("hypergraph:build:latest",{timestamp:new Date().toISOString(),...n},{namespace:"code-intelligence",persist:!0}),i){let s=D("code-intelligence.HypergraphBuilt","code-intelligence",{nodesCreated:n.nodesCreated,nodesUpdated:n.nodesUpdated,edgesCreated:n.edgesCreated,durationMs:n.durationMs,errorCount:n.errors.length});await r.publish(s)}return{success:!0,value:n}}catch(n){let s=y(n);return Ve.error("Failed to build hypergraph:"),p(s)}}async function Ld(u,t,e){try{let r=await u.findImpactedTests(t.changedFiles),i=new Set([...e.impactedTests,...r.map(a=>a.filePath||a.name)]),n=e.riskLevel;if(r.length>e.impactedTests.length){let a=e.directImpact.length+e.transitiveImpact.length;a>10&&i.size>20?n="critical":a>5&&i.size>10&&(n="high")}let s=[...e.recommendations];return r.length>0&&s.push(`Hypergraph analysis found ${r.length} additional test(s) to run`),{...e,impactedTests:Array.from(i),riskLevel:n,recommendations:s}}catch(r){return Ve.error("Failed to enhance impact with hypergraph:",r instanceof Error?r:void 0),e}}M();var vr=R.create("code-intelligence/consensus");async function $d(u,t,e,r){let i=V({id:v(),type:"code-pattern-detection",confidence:t,description:`Verify code pattern: ${u.name} (${u.type}) at ${u.location}`,payload:u,detectedBy:"code-intelligence-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(vr.info(`Code pattern '${u.name}' verified by consensus`),!0):(vr.warn(`Code pattern '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Od(u,t,e,r){let i=V({id:v(),type:"impact-analysis",confidence:t,description:`Verify impact analysis: ${u.changedFiles.length} files, risk=${u.riskLevel}, ${u.impactedTests.length} tests`,payload:u,detectedBy:"code-intelligence-coordinator",severity:u.riskLevel==="critical"||u.riskLevel==="high"?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(vr.info(`Impact analysis verified by consensus (risk=${u.riskLevel})`),!0):(vr.warn(`Impact analysis NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Nd(u,t,e,r){let i=V({id:v(),type:"dependency-mapping",confidence:t,description:`Verify dependency: ${u.source} -> ${u.targets.length} targets (${u.type})`,payload:u,detectedBy:"code-intelligence-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(vr.info("Dependency mapping verified by consensus"),!0):(vr.warn(`Dependency mapping NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var ny={maxConcurrentWorkflows:5,defaultTimeout:12e4,publishEvents:!0,enableIncrementalIndex:!0,enableGNN:!0,enableSONA:!0,enableMetricCollector:!0,enableHypergraph:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Z=R.create("code-intelligence"),Oi=class extends Q{constructor(e,r,i,n={}){let s={...ny,...n};super(e,"code-intelligence",s,{verifyFindingTypes:["code-pattern-detection","impact-analysis","dependency-mapping"]});this.memory=r;this.agentCoordinator=i;this.knowledgeGraph=new Rt(r),this.semanticAnalyzer=new Ot(r),this.impactAnalyzer=new Br(r,this.knowledgeGraph),this.fileReader=new De,this.productFactorsBridge=new $s(e,r,{publishEvents:this.config.publishEvents})}memory;agentCoordinator;knowledgeGraph;semanticAnalyzer;impactAnalyzer;fileReader;gnnIndex;sonaEngine;rlInitialized=!1;metricCollector;hypergraph;hypergraphDb;productFactorsBridge;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enableGNN||this.config.enableSONA)&&await this.initializeRLIntegrations(),this.config.enableMetricCollector&&(this.metricCollector=Ad({enableCache:!0,cacheTTL:3e5}),Z.info("MetricCollector initialized for real code metrics")),this.config.enableHypergraph&&await this.initializeHypergraph(),await this.productFactorsBridge.initialize()}async initializeHypergraph(){try{let{openDatabase:e}=await import("./safe-db-PEJN42TX.js"),r=await import("fs"),i=await import("path"),{findProjectRoot:n}=await import("./unified-memory-SAIRUPOI.js"),s=n(),a=this.config.hypergraphDbPath||i.join(s,".agentic-qe","memory.db"),o=i.dirname(a);r.existsSync(o)||r.mkdirSync(o,{recursive:!0}),this.hypergraphDb=e(a),this.hypergraph=await nn({db:this.hypergraphDb,maxTraversalDepth:10,maxQueryResults:1e3,enableVectorSearch:this.config.enableGNN}),Z.info(`Hypergraph Engine initialized at ${a}`)}catch(e){let r=e instanceof Error?e.message:String(e);if(Z.warn(`Hypergraph Engine initialization failed (feature degraded): ${r}`),this.hypergraph=void 0,this.hypergraphDb=void 0,this.config.publishEvents){let i=D("code-intelligence.HypergraphDegraded","code-intelligence",{reason:r});this.eventBus.publish(i).catch(()=>{})}}}async initializeRLIntegrations(){try{if(this.config.enableGNN&&(Va(),this.gnnIndex=rn.getInstance("code-intelligence",{M:16,efConstruction:200,efSearch:50,dimension:384,metric:"cosine"}),this.gnnIndex.initializeIndex("code"),this.gnnIndex.initializeIndex("test")),this.config.enableSONA)try{this.sonaEngine=await me({domain:"code-intelligence",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.6}),Z.info("PersistentSONAEngine initialized for code pattern learning")}catch(e){Z.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),this.sonaEngine=void 0}this.rlInitialized=!0}catch(e){throw Z.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){if(await this.saveWorkflowState(),this.gnnIndex&&rn.closeInstance("code-intelligence"),this.sonaEngine)try{await this.sonaEngine.close(),this.sonaEngine=void 0}catch(e){Z.error("Error closing SONA engine:",e instanceof Error?e:void 0)}if(this.hypergraphDb){try{this.hypergraphDb.close()}catch(e){Z.error("Error closing hypergraph database:",e instanceof Error?e:void 0)}this.hypergraphDb=void 0}this.hypergraph=void 0,await this.productFactorsBridge.dispose()}getActiveWorkflows(){return super.getActiveWorkflows()}async index(e){let r=v();try{if(this.startWorkflow(r,"index"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Z.warn("Topology degraded, using conservative strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Indexing paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn indexing agents"));let i=await this.spawnIndexerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,10);let n=await this.knowledgeGraph.index(e);if(n.success){if(this.updateWorkflowProgress(r,40),this.config.enableGNN&&this.gnnIndex&&e.paths.length>0&&await this.indexCodeEmbeddings(e.paths),this.updateWorkflowProgress(r,60),this.config.enableMetricCollector&&this.metricCollector&&e.paths.length>0){let s=this.getProjectRootFromPaths(e.paths);s&&await this.collectProjectMetrics(s)}if(this.updateWorkflowProgress(r,70),e.paths.length>0&&await this.indexForSemanticSearch(e.paths),this.updateWorkflowProgress(r,85),this.config.enableHypergraph&&this.hypergraph&&e.paths.length>0)try{let s=await this.buildCodeIndexResultFromPaths(e.paths);if(s.files.length>0){await this.hypergraph.buildFromIndexResult(s),Z.info(`Hypergraph rebuilt from ${s.files.length} indexed files`);try{let a=await this.hypergraph.synthesizeTestCoverage();(a.testsTagged>0||a.coversCreated>0)&&Z.info(`Test coverage synthesized: tests_tagged=${a.testsTagged} covers_created=${a.coversCreated}`)}catch(a){Z.warn(`Test coverage synthesis skipped: ${a instanceof Error?a.message:a}`)}}}catch(s){Z.warn(`Hypergraph rebuild skipped: ${s instanceof Error?s.message:s}`)}this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.publishEvents&&await this.publishKnowledgeGraphUpdated(n.value)}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async search(e){let r=v();try{this.startWorkflow(r,"search");let i=await this.spawnSearchAgent(r,e);if(i.success&&this.addAgentToWorkflow(r,i.value),this.config.enableSONA&&this.sonaEngine){let a=await this.adaptSearchPattern(e);a.success&&a.pattern&&Z.info(`Adapted search pattern with ${a.similarity.toFixed(3)} similarity`)}let n=[];this.config.enableGNN&&this.gnnIndex&&(n=await this.searchCodeWithGNN(e));let s=await this.semanticAnalyzer.search(e);return s.success?(n.length>0&&(s.value.results=this.mergeSearchResults(s.value.results,n)),this.completeWorkflow(r),this.config.publishEvents&&await this.publishSemanticSearchCompleted(e,s.value)):this.failWorkflow(r,s.error.message),i.success&&await this.agentCoordinator.stop(i.value),s}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async analyzeImpact(e){let r=v();try{if(this.startWorkflow(r,"impact"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Z.warn("Topology degraded, using conservative impact analysis"),this.minCutMixin.shouldPauseOperations())return p(new Error("Impact analysis paused: topology is in critical state"));let i=await this.spawnImpactAnalyzerAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value),this.updateWorkflowProgress(r,20),this.config.enableGNN&&this.gnnIndex&&await this.enhanceImpactAnalysisWithGNN(e);let n=await this.impactAnalyzer.analyzeImpact(e);if(n.success){this.updateWorkflowProgress(r,80);let s=n.value;return this.config.enableHypergraph&&this.hypergraph&&(s=await this.enhanceImpactWithHypergraph(e,n.value)),this.updateWorkflowProgress(r,100),this.completeWorkflow(r),this.config.enableSONA&&this.sonaEngine&&await this.storeImpactPattern(e,s),this.config.publishEvents&&await this.publishImpactAnalysisCompleted(e,s),{success:!0,value:s}}else this.failWorkflow(r,n.error.message);return await this.agentCoordinator.stop(i.value),n}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async mapDependencies(e){let r=v();try{this.startWorkflow(r,"dependency");let i=await this.knowledgeGraph.mapDependencies(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async queryKG(e){let r=v();try{this.startWorkflow(r,"query");let i=await this.knowledgeGraph.query(e);return i.success?this.completeWorkflow(r):this.failWorkflow(r,i.error.message),i}catch(i){let n=y(i);return this.failWorkflow(r,n.message),p(n)}}async indexCodeEmbeddings(e){!this.gnnIndex||!this.rlInitialized||await Ed(this.gnnIndex,this.fileReader,e)}async searchCodeWithGNN(e){return!this.gnnIndex||!this.rlInitialized?[]:xd(this.gnnIndex,e.query)}async enhanceImpactAnalysisWithGNN(e){!this.gnnIndex||!this.rlInitialized||await Pd(this.gnnIndex,this.fileReader,e)}async adaptSearchPattern(e){if(!this.sonaEngine||!this.rlInitialized)return{success:!1,pattern:null,similarity:0};try{let r=Array.isArray(e.filters)?e.filters.find(s=>s.field==="language")?.value:void 0,i={id:`search-${e.type}`,features:[e.query.length,e.type==="semantic"?1:0,e.type==="exact"?1:0,r==="typescript"?1:0,r==="javascript"?1:0]},n=await this.sonaEngine.adaptPattern(i,"coverage-optimization","code-intelligence");return{success:n.success,pattern:n.pattern,similarity:n.similarity}}catch(r){return Z.error("Failed to adapt search pattern:",r instanceof Error?r:void 0),{success:!1,pattern:null,similarity:0}}}async storeImpactPattern(e,r){if(!(!this.sonaEngine||!this.rlInitialized))try{let i={id:`impact-${e.changedFiles.join(",")}`,features:[e.changedFiles.length,e.depth||1,r.directImpact.length,r.transitiveImpact.length,r.impactedTests.length,r.riskLevel==="high"?1:r.riskLevel==="medium"?.5:0]},n={type:"analyze-impact",value:r.riskLevel},s={reward:r.riskLevel==="high"?.8:r.riskLevel==="medium"?.5:.3,success:r.impactedTests.length>0,quality:(r.directImpact.length+r.transitiveImpact.length)/100},a=this.sonaEngine.createPattern(i,n,s,"coverage-optimization","code-intelligence",{changedFiles:e.changedFiles,impactCount:r.directImpact.length+r.transitiveImpact.length,testImpactCount:r.impactedTests.length});Z.info(`Stored impact pattern ${a.id}`)}catch(i){Z.error("Failed to store impact pattern:",i instanceof Error?i:void 0)}}mergeSearchResults(e,r){return kd(e,r)}hashCode(e){return _s(e)}async spawnIndexerAgent(e,r){let i={name:`kg-indexer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["indexing","ast-parsing","graph-building"],config:{workflowId:e,paths:r.paths,incremental:r.incremental}};return this.agentCoordinator.spawn(i)}async spawnSearchAgent(e,r){let i={name:`semantic-search-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["semantic-search","vector-similarity",r.type],config:{workflowId:e,query:r.query,type:r.type}};return this.agentCoordinator.spawn(i)}async spawnImpactAnalyzerAgent(e,r){let i={name:`impact-analyzer-${e.slice(0,8)}`,domain:"code-intelligence",type:"analyzer",capabilities:["impact-analysis","dependency-traversal","risk-assessment"],config:{workflowId:e,changedFiles:r.changedFiles,depth:r.depth}};return this.agentCoordinator.spawn(i)}async publishKnowledgeGraphUpdated(e){let r={nodes:e.nodesCreated,edges:e.edgesCreated,filesIndexed:e.filesIndexed,duration:e.duration},i=D(tt.KnowledgeGraphUpdated,"code-intelligence",r);await this.eventBus.publish(i)}async publishImpactAnalysisCompleted(e,r){let i={analysisId:v(),changedFiles:e.changedFiles,impactedFiles:[...r.directImpact.map(s=>s.file),...r.transitiveImpact.map(s=>s.file)],impactedTests:r.impactedTests,riskLevel:r.riskLevel},n=D(tt.ImpactAnalysisCompleted,"code-intelligence",i);await this.eventBus.publish(n)}async publishSemanticSearchCompleted(e,r){let i=D(tt.SemanticSearchCompleted,"code-intelligence",{query:e.query,type:e.type,resultCount:r.total,searchTime:r.searchTime});await this.eventBus.publish(i)}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("source-control.FilesChanged",this.handleFilesChanged.bind(this))}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`code-intelligence:test-correlation:${r.runId}`,r,{namespace:"code-intelligence",ttl:86400})}async handleFilesChanged(e){if(!this.config.enableIncrementalIndex)return;let r=e.payload;r.files&&r.files.length>0&&await this.memory.set(`code-intelligence:pending-index:${Date.now()}`,{files:r.files,timestamp:new Date().toISOString()},{namespace:"code-intelligence",ttl:3600})}async indexForSemanticSearch(e){let r=e.slice(0,100);for(let i of r)try{let n=await this.fileReader.readFile(i);n.success&&n.value&&await this.semanticAnalyzer.indexCode(i,n.value)}catch{}}async loadWorkflowState(){let e=await this.memory.get("code-intelligence:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("code-intelligence:coordinator:workflows",e,{namespace:"code-intelligence",persist:!0})}async generateC4Diagrams(e,r){let i=v();try{this.startWorkflow(i,"query");let n={projectPath:e,detectExternalSystems:r?.detectExternalSystems??!0,analyzeComponents:r?.analyzeComponents??!0,analyzeCoupling:r?.analyzeCoupling??!0,includeContext:r?.includeContext??!0,includeContainer:r?.includeContainer??!0,includeComponent:r?.includeComponent??!0,includeDependency:r?.includeDependency??!1,excludePatterns:r?.excludePatterns};this.updateWorkflowProgress(i,20);let s=await this.productFactorsBridge.requestC4Diagrams(n);return s.success?(this.updateWorkflowProgress(i,80),await this.storeC4DiagramsInMemory(e,s.value),this.updateWorkflowProgress(i,100),this.completeWorkflow(i),Z.info(`[CodeIntelligenceCoordinator] C4 diagrams generated for ${e}: ${s.value.components.length} components, ${s.value.externalSystems.length} external systems`)):this.failWorkflow(i,s.error.message),s}catch(n){let s=y(n);return this.failWorkflow(i,s.message),p(s)}}getProductFactorsBridge(){return this.productFactorsBridge}async storeC4DiagramsInMemory(e,r){let i=`c4-diagrams:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:36e5}),await this.memory.set(`c4-components:${this.hashCode(e)}`,r.components,{namespace:"code-intelligence",ttl:36e5}),await this.memory.set(`c4-external-systems:${this.hashCode(e)}`,r.externalSystems,{namespace:"code-intelligence",ttl:36e5})}async collectProjectMetrics(e){if(!this.config.enableMetricCollector||!this.metricCollector)return p(new Error("MetricCollector is not enabled"));try{Z.info(`Collecting real metrics for ${e}`);let r=await this.metricCollector.collectAll(e),i=r.toolsUsed.length>0?r.toolsUsed.join(", "):r.loc.source==="node-native"?"node-native":"fallback";if(Z.info(`[CodeIntelligence] Real metrics collected: ${r.loc.total} LOC, ${r.tests.total} tests, tools: ${i}`),r.loc.source==="node-native"&&Z.info("[CodeIntelligence] Using Node.js-native line counter (no cloc/tokei needed)"),await this.storeProjectMetricsInMemory(e,r),this.config.publishEvents){let n=D("code-intelligence.MetricsCollected","code-intelligence",{projectPath:e,loc:r.loc.total,tests:r.tests.total,toolsUsed:r.toolsUsed});await this.eventBus.publish(n)}return{success:!0,value:r}}catch(r){let i=y(r);return Z.error("Failed to collect metrics:"),p(i)}}async storeProjectMetricsInMemory(e,r){let i=`project-metrics:latest:${this.hashCode(e)}`;await this.memory.set(i,r,{namespace:"code-intelligence",persist:!0,ttl:3e5}),await this.memory.set(`loc-metrics:${this.hashCode(e)}`,r.loc,{namespace:"code-intelligence",ttl:3e5}),await this.memory.set(`test-metrics:${this.hashCode(e)}`,r.tests,{namespace:"code-intelligence",ttl:3e5})}getMetricCollector(){return this.metricCollector}getProjectRootFromPaths(e){if(e.length===0)return null;let r=e[0],i=r.split("/"),n="";for(let a of i){n=n?`${n}/${a}`:a;let o=["package.json","Cargo.toml","go.mod","pyproject.toml",".git"];for(let c of o)try{let l=`${n}/${c}`;if(Pa("fs").existsSync(l))return n}catch{}}let s=r.lastIndexOf("/");return s>0?r.substring(0,s):r}isHypergraphEnabled(){return this.config.enableHypergraph&&this.hypergraph!==void 0}async findUntestedFunctions(){return this.hypergraph?Id(this.hypergraph,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findImpactedTestsFromHypergraph(e){return this.hypergraph?Dd(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async findCoverageGapsFromHypergraph(e=50){return this.hypergraph?Md(this.hypergraph,e,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}async buildHypergraphFromIndex(e){return this.hypergraph?Fd(this.hypergraph,e,this.memory,this.eventBus,this.config.publishEvents):p(new Error("Hypergraph is not enabled or not initialized"))}getHypergraph(){return this.hypergraph}async enhanceImpactWithHypergraph(e,r){return this.hypergraph?Ld(this.hypergraph,e,r):r}async buildCodeIndexResultFromPaths(e){let{extractCodeIndex:r}=await import("./code-index-extractor-A6KAUQOU.js");return r(e)}async verifyCodePatternDetection(e,r){return $d(e,r,this.consensusMixin,this.domainName)}async verifyImpactAnalysis(e,r){return Od(e,r,this.consensusMixin,this.domainName)}async verifyDependencyMapping(e,r){return Nd(e,r,this.consensusMixin,this.domainName)}};A();var zs=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;knowledgeGraph=null;semanticAnalyzer=null;impactAnalyzer=null;pluginConfig;get name(){return"code-intelligence"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{index:this.index.bind(this),search:this.search.bind(this),analyzeImpact:this.analyzeImpact.bind(this),mapDependencies:this.mapDependencies.bind(this),getDependencies:this.mapDependencies.bind(this),queryKG:this.queryKG.bind(this),getMetrics:this.getMetrics.bind(this),getCoordinator:()=>this.coordinator,getKnowledgeGraph:()=>this.knowledgeGraph,getSemanticAnalyzer:()=>this.semanticAnalyzer,getImpactAnalyzer:()=>this.impactAnalyzer}}getTaskHandlers(){return new Map([["index",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.paths;if(!r||r.length===0)return p(new Error("Invalid index payload: missing paths"));let i=e.language?[e.language]:e.languages;return this.coordinator.index({paths:r,languages:i})}],["search",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.query;return r?this.coordinator.search({query:r,type:e.type??"semantic",limit:e.limit}):p(new Error("Invalid search payload: missing query"))}],["analyze-impact",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.changedFiles;return!r||r.length===0?p(new Error("Invalid analyze-impact payload: missing changedFiles")):this.coordinator.analyzeImpact({changedFiles:r})}],["query-dependencies",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.file,n=e.files??(r?[r]:void 0);return!n||n.length===0?p(new Error("Invalid query-dependencies payload: missing file or files")):this.coordinator.mapDependencies({files:n,direction:e.direction??"both",depth:e.depth})}]])}async onInitialize(){this.knowledgeGraph=new Rt(this.memory,this.pluginConfig.knowledgeGraph),this.semanticAnalyzer=new Ot(this.memory,this.pluginConfig.semanticAnalyzer),this.impactAnalyzer=new Br(this.memory,this.knowledgeGraph,this.pluginConfig.impactAnalyzer),this.coordinator=new Oi(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.knowledgeGraph=null,this.semanticAnalyzer=null,this.impactAnalyzer=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;case"defect-intelligence.DefectPredicted":await this.handleDefectPredicted(e);break;default:break}}async index(e){this.ensureInitialized();try{let r=await this.coordinator.index(e);return r.success?this.trackSuccessfulOperation("index",r.value):this.trackFailedOperation("index",r.error),r}catch(r){return this.handleError(r)}}async search(e){this.ensureInitialized();try{let r=await this.coordinator.search(e);return r.success?this.trackSuccessfulOperation("search",r.value):this.trackFailedOperation("search",r.error),r}catch(r){return this.handleError(r)}}async analyzeImpact(e){this.ensureInitialized();try{let r=await this.coordinator.analyzeImpact(e);return r.success?this.trackSuccessfulOperation("impact",r.value):this.trackFailedOperation("impact",r.error),r}catch(r){return this.handleError(r)}}async mapDependencies(e){this.ensureInitialized();try{let r=await this.coordinator.mapDependencies(e);return r.success?this.trackSuccessfulOperation("dependency",r.value):this.trackFailedOperation("dependency",r.error),r}catch(r){return this.handleError(r)}}async queryKG(e){this.ensureInitialized();try{let r=await this.coordinator.queryKG(e);return r.success?this.trackSuccessfulOperation("query",r.value):this.trackFailedOperation("query",r.error),r}catch(r){return this.handleError(r)}}async getMetrics(){this.ensureInitialized();try{let e=this.getHealth();return{success:!0,value:{indexed:e.agents.total,queries:e.agents.idle,impacts:e.agents.active}}}catch(e){return this.handleError(e)}}async handleTestGenerated(e){let r=e.payload;await this.memory.set(`code-intelligence:test-mapping:${r.testId}`,{testFile:r.testFile,sourceFile:r.sourceFile,generatedAt:new Date().toISOString()},{namespace:"code-intelligence",ttl:86400*30})}async handleCoverageGap(e){let r=e.payload;await this.memory.set(`code-intelligence:coverage-gap:${r.gapId}`,r,{namespace:"code-intelligence",ttl:86400*7})}async handleDefectPredicted(e){let r=e.payload;await this.memory.set(`code-intelligence:defect-prediction:${r.predictionId}`,r,{namespace:"code-intelligence",ttl:86400*7})}ensureInitialized(){if(!this._initialized)throw new Error("CodeIntelligencePlugin is not initialized");if(!this.coordinator||!this.knowledgeGraph||!this.semanticAnalyzer||!this.impactAnalyzer)throw new Error("CodeIntelligencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,total:i.agents.total+1,idle:i.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function Tc(u,t,e,r){return new zs(u,t,e,r)}M();A();var he=class u{constructor(t){this._value=t;if(!t||t.trim()==="")throw new Error("FilePath cannot be empty")}_value;get value(){return this._value}get extension(){let t=this._value.split(".");return t.length>1?t[t.length-1]:""}get directory(){let t=this._value.lastIndexOf("/");return t>0?this._value.substring(0,t):""}get filename(){let t=this._value.lastIndexOf("/");return t>=0?this._value.substring(t+1):this._value}equals(t){return this._value===t._value}static create(t){return new u(t)}};var br=class u{constructor(t){this._value=t;if(t<0||t>1)throw new Error("RiskScore must be between 0 and 1")}_value;get value(){return this._value}get percentage(){return this._value*100}get level(){return this._value>=.8?"critical":this._value>=.6?"high":this._value>=.3?"medium":"low"}isHigherThan(t){return this._value>t._value}equals(t){return this._value===t._value}static create(t){return new u(t)}static fromPercentage(t){return new u(t/100)}},_e=class u{constructor(t,e){this._start=t;this._end=e;if(t>e)throw new Error("Start date cannot be after end date")}_start;_end;get start(){return this._start}get end(){return this._end}get durationMs(){return this._end.getTime()-this._start.getTime()}get durationSeconds(){return this.durationMs/1e3}contains(t){return t>=this._start&&t<=this._end}overlaps(t){return this._start<=t._end&&t._start<=this._end}equals(t){return this._start.getTime()===t._start.getTime()&&this._end.getTime()===t._end.getTime()}static create(t,e){return new u(t,e)}static lastNDays(t){let e=new Date,r=new Date(e.getTime()-t*24*60*60*1e3);return new u(r,e)}},zt=class u{constructor(t,e,r,i){this._major=t;this._minor=e;this._patch=r;this._prerelease=i}_major;_minor;_patch;_prerelease;get major(){return this._major}get minor(){return this._minor}get patch(){return this._patch}get prerelease(){return this._prerelease}toString(){let t=`${this._major}.${this._minor}.${this._patch}`;return this._prerelease?`${t}-${this._prerelease}`:t}isNewerThan(t){return this._major!==t._major?this._major>t._major:this._minor!==t._minor?this._minor>t._minor:this._patch>t._patch}equals(t){return this._major===t._major&&this._minor===t._minor&&this._patch===t._patch&&this._prerelease===t._prerelease}static create(t,e,r,i){return new u(t,e,r,i)}static parse(t){let e=t.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!e)throw new Error(`Invalid version format: ${t}`);return new u(parseInt(e[1]),parseInt(e[2]),parseInt(e[3]),e[4])}};var Bs={defaultRuleSets:["owasp-top-10","cwe-sans-25"],maxConcurrentScans:4,timeout:3e5,enableFalsePositiveDetection:!0,dastMaxDepth:5,dastActiveScanning:!1,enableLLMAnalysis:!0,llmModelTier:4,enableSemgrep:!0};M();var Ac=[{id:"sqli-string-concat",pattern:/query\s*\(\s*['"`].*\+.*['"`]\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via String Concatenation",description:"SQL query constructed using string concatenation with potentially untrusted input",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries or prepared statements instead of string concatenation",fixExample:'db.query("SELECT * FROM users WHERE id = $1", [userId])'},{id:"sqli-template-literal",pattern:/execute\s*\(\s*`[^`]*\$\{[^}]+\}[^`]*`\s*\)/g,category:"injection",severity:"critical",title:"SQL Injection via Template Literal",description:"SQL query constructed using template literals with embedded expressions",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Use parameterized queries instead of template literals for SQL",fixExample:'db.execute("DELETE FROM users WHERE id = ?", [userId])'},{id:"sqli-raw-query",pattern:/\.raw\s*\(\s*['"`].*\+|\.raw\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"high",title:"SQL Injection via Raw Query",description:"Raw SQL query with potential user input interpolation",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Avoid raw queries with user input; use ORM methods or parameterized queries"},{id:"sqli-exec",pattern:/exec(?:ute)?(?:Sql|Query)?\s*\([^)]*\+[^)]*\)/gi,category:"injection",severity:"critical",title:"SQL Injection via Dynamic Execution",description:"Dynamic SQL execution with string concatenation detected",owaspId:"A03:2021",cweId:"CWE-89",remediation:"Never concatenate user input into SQL queries"}],Ec=[{id:"xss-innerhtml",pattern:/\.innerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via innerHTML Assignment",description:"Direct innerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Use textContent for text, or sanitize HTML with DOMPurify before innerHTML assignment",fixExample:"element.textContent = userInput; // or DOMPurify.sanitize(userInput)"},{id:"xss-document-write",pattern:/document\.write\s*\([^)]+\)/g,category:"xss",severity:"high",title:"XSS via document.write",description:"document.write() can execute scripts from untrusted data",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Avoid document.write(); use DOM manipulation methods instead",fixExample:"document.body.appendChild(document.createTextNode(text))"},{id:"xss-dangerously-set",pattern:/dangerouslySetInnerHTML\s*=\s*\{/g,category:"xss",severity:"medium",title:"React dangerouslySetInnerHTML Usage",description:"dangerouslySetInnerHTML bypasses React XSS protections",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize HTML content with DOMPurify before using dangerouslySetInnerHTML",fixExample:"dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}"},{id:"xss-eval",pattern:/eval\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via eval()",description:"eval() executes arbitrary code and is a major security risk",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Never use eval(); use JSON.parse() for JSON data or safer alternatives",fixExample:"JSON.parse(jsonString) // instead of eval(jsonString)"},{id:"xss-new-function",pattern:/new\s+Function\s*\([^)]+\)/g,category:"xss",severity:"critical",title:"Code Injection via Function Constructor",description:"Function constructor can execute arbitrary code like eval()",owaspId:"A03:2021",cweId:"CWE-95",remediation:"Avoid the Function constructor; use predefined functions instead"},{id:"xss-outerhtml",pattern:/\.outerHTML\s*=\s*[^'"`;\n]+/g,category:"xss",severity:"high",title:"XSS via outerHTML Assignment",description:"Direct outerHTML assignment with potentially unsanitized content",owaspId:"A03:2021",cweId:"CWE-79",remediation:"Sanitize content before outerHTML assignment"}],xc=[{id:"secret-aws-access-key",pattern:/['"`]AKIA[0-9A-Z]{16}['"`]/g,category:"sensitive-data",severity:"critical",title:"AWS Access Key Detected",description:"Hardcoded AWS Access Key ID found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or AWS Secrets Manager for credentials",fixExample:"const accessKey = process.env.AWS_ACCESS_KEY_ID"},{id:"secret-aws-secret-key",pattern:/['"`][A-Za-z0-9/+=]{40}['"`]/g,category:"sensitive-data",severity:"critical",title:"Potential AWS Secret Key Detected",description:"Potential hardcoded AWS Secret Access Key found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store secrets in environment variables or secrets manager"},{id:"secret-openai-key",pattern:/['"`]sk-[a-zA-Z0-9]{48,}['"`]/g,category:"sensitive-data",severity:"critical",title:"OpenAI API Key Detected",description:"Hardcoded OpenAI API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.OPENAI_API_KEY"},{id:"secret-generic-password",pattern:/password\s*[:=]\s*['"`][^'"`]{4,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded Password Detected",description:"Hardcoded password found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Never hardcode passwords; use environment variables or secrets manager",fixExample:"const password = process.env.DB_PASSWORD"},{id:"secret-api-key",pattern:/api[_-]?key\s*[:=]\s*['"`][a-zA-Z0-9_\-]{16,}['"`]/gi,category:"sensitive-data",severity:"high",title:"Hardcoded API Key Detected",description:"Hardcoded API key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for API keys",fixExample:"const apiKey = process.env.API_KEY"},{id:"secret-jwt",pattern:/['"`]eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+['"`]/g,category:"sensitive-data",severity:"high",title:"Hardcoded JWT Token Detected",description:"Hardcoded JWT token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Generate JWT tokens dynamically; never hardcode them"},{id:"secret-private-key",pattern:/-----BEGIN\s+(RSA|EC|OPENSSH|DSA)?\s*PRIVATE\s+KEY-----/g,category:"sensitive-data",severity:"critical",title:"Private Key Detected",description:"Private key found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Store private keys in secure key management systems, not in code"},{id:"secret-github-token",pattern:/['"`]ghp_[a-zA-Z0-9]{36}['"`]|['"`]github_pat_[a-zA-Z0-9]{22}_[a-zA-Z0-9]{59}['"`]/g,category:"sensitive-data",severity:"critical",title:"GitHub Token Detected",description:"Hardcoded GitHub personal access token found",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or GitHub Actions secrets"},{id:"secret-slack-token",pattern:/['"`]xox[baprs]-[0-9]{10,13}-[0-9]{10,13}[a-zA-Z0-9-]*['"`]/g,category:"sensitive-data",severity:"high",title:"Slack Token Detected",description:"Hardcoded Slack token found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables for Slack tokens"},{id:"secret-generic-assignment",pattern:/\b\w*(?:SECRET|secret)(?:_KEY|_key|Key)?\s*[:=]\s*['"`][^'"`]{4,}['"`]/g,category:"sensitive-data",severity:"high",title:"Generic Secret Assignment Detected",description:"Hardcoded secret assignment (SECRET_KEY, JWT_SECRET, APP_SECRET, etc.) found in source code",owaspId:"A02:2021",cweId:"CWE-798",remediation:"Use environment variables or a secrets manager instead of hardcoding secrets",fixExample:"const secretKey = process.env.SECRET_KEY"}],Pc=[{id:"path-traversal-readfile",pattern:/(?:readFile|readFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Read",description:"File read operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths; use path.resolve() and check against base directory",fixExample:"const safePath = path.resolve(baseDir, path.basename(userInput))"},{id:"path-traversal-pattern",pattern:/\.\.\/.*\.\.\//g,category:"access-control",severity:"medium",title:"Path Traversal Pattern Detected",description:"Suspicious path traversal pattern (../) found in code",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate paths and ensure they resolve within expected directories"},{id:"path-traversal-writefile",pattern:/(?:writeFile|writeFileSync)\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via File Write",description:"File write operation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate file paths before writing; ensure path is within allowed directory"},{id:"path-traversal-createstream",pattern:/createReadStream\s*\([^)]*\+/g,category:"access-control",severity:"high",title:"Path Traversal via Stream",description:"Stream creation with concatenated path may allow directory traversal",owaspId:"A01:2021",cweId:"CWE-22",remediation:"Validate and sanitize file paths before creating streams"}],kc=[{id:"cmd-injection-exec",pattern:/exec\s*\([^)]*\+[^)]*\)|exec\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via exec()",description:"Shell command execution with unsanitized input",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use execFile() with argument array instead of exec() with string concatenation",fixExample:'execFile("command", [arg1, arg2], callback)'},{id:"cmd-injection-spawn",pattern:/spawn\s*\(\s*[^,]+\+|spawn\s*\(\s*`[^`]*\$\{/g,category:"injection",severity:"critical",title:"Command Injection via spawn()",description:"Process spawn with potentially unsanitized command",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Use spawn with command and args array; validate inputs",fixExample:'spawn("command", [sanitizedArg1, sanitizedArg2])'},{id:"cmd-injection-shell-true",pattern:/spawn\s*\([^)]+,\s*\{[^}]*shell\s*:\s*true/g,category:"injection",severity:"high",title:"Dangerous Shell Option in spawn()",description:"spawn() with shell: true can enable command injection",owaspId:"A03:2021",cweId:"CWE-78",remediation:"Avoid shell: true option; use direct command execution"}],Ic=[{id:"misc-cors-wildcard",pattern:/cors\s*\(\s*\{[^}]*origin\s*:\s*['"]\*['"]/gi,category:"security-misconfiguration",severity:"medium",title:"Permissive CORS Configuration",description:"CORS allows all origins (*) which may expose sensitive data",owaspId:"A05:2021",cweId:"CWE-942",remediation:"Restrict CORS to specific trusted origins",fixExample:'cors({ origin: ["https://trusted-domain.com"] })'},{id:"misc-debug-enabled",pattern:/debug\s*[:=]\s*true|DEBUG\s*[:=]\s*['"]?true['"]?/gi,category:"security-misconfiguration",severity:"low",title:"Debug Mode Enabled",description:"Debug mode may expose sensitive information in production",owaspId:"A05:2021",cweId:"CWE-489",remediation:"Disable debug mode in production environments"},{id:"misc-ssl-disabled",pattern:/rejectUnauthorized\s*:\s*false|NODE_TLS_REJECT_UNAUTHORIZED\s*=\s*['"]?0['"]?/g,category:"security-misconfiguration",severity:"high",title:"TLS Certificate Validation Disabled",description:"Disabling TLS certificate validation exposes to MITM attacks",owaspId:"A05:2021",cweId:"CWE-295",remediation:"Always enable TLS certificate validation in production"},{id:"misc-helmet-missing",pattern:/app\.use\s*\(\s*express\s*\(\s*\)\s*\)/g,category:"security-misconfiguration",severity:"low",title:"Express App Without Security Headers",description:"Express app initialized without helmet or security headers",owaspId:"A05:2021",cweId:"CWE-693",remediation:"Use helmet middleware for security headers",fixExample:"app.use(helmet())"}],Dc=[{id:"deser-yaml-load",pattern:/yaml\.load\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe YAML Deserialization",description:"yaml.load() can execute arbitrary code from untrusted YAML",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use yaml.safeLoad() or schema-constrained loading",fixExample:"yaml.load(content, { schema: yaml.SAFE_SCHEMA })"},{id:"deser-serialize-js",pattern:/serialize\s*\([^)]+\)|unserialize\s*\([^)]+\)/g,category:"insecure-deserialization",severity:"high",title:"Unsafe Serialization Function",description:"Node serialize/unserialize functions can execute arbitrary code",owaspId:"A08:2021",cweId:"CWE-502",remediation:"Use JSON.parse/stringify for serialization"}],Mc=[{id:"auth-weak-jwt-secret",pattern:/jwt\.sign\s*\([^)]+,\s*['"][a-zA-Z0-9]{1,16}['"]/g,category:"broken-auth",severity:"high",title:"Weak JWT Secret",description:"JWT signed with a weak or short secret key",owaspId:"A07:2021",cweId:"CWE-327",remediation:"Use a strong, randomly generated secret of at least 256 bits"},{id:"auth-no-algorithm",pattern:/jwt\.verify\s*\([^)]+\)\s*(?!.*algorithm)/g,category:"broken-auth",severity:"medium",title:"JWT Without Algorithm Specification",description:"JWT verification without explicit algorithm can be exploited",owaspId:"A07:2021",cweId:"CWE-347",remediation:"Always specify the expected algorithm in JWT verification",fixExample:'jwt.verify(token, secret, { algorithms: ["HS256"] })'}],qs=[...Ac,...Ec,...xc,...Pc,...kc,...Ic,...Dc,...Mc],Ni=[{id:"owasp-top-10",name:"OWASP Top 10",description:"OWASP Top 10 most critical security risks",ruleCount:45,categories:["injection","broken-auth","sensitive-data","xxe","access-control","security-misconfiguration","xss","insecure-deserialization","vulnerable-components","insufficient-logging"]},{id:"cwe-sans-25",name:"CWE/SANS Top 25",description:"Most dangerous software errors",ruleCount:38,categories:["injection","xss","access-control","sensitive-data","broken-auth"]},{id:"nodejs-security",name:"Node.js Security",description:"Node.js specific security rules",ruleCount:25,categories:["injection","xss","sensitive-data","security-misconfiguration"]},{id:"typescript-security",name:"TypeScript Security",description:"TypeScript specific security rules",ruleCount:20,categories:["injection","xss","sensitive-data"]}];A();H();A();H();import{execFile as sy}from"child_process";import{promisify as ay}from"util";import*as zd from"path";var Fc=ay(sy);async function Vi(){try{return await Fc("semgrep",["--version"],{timeout:5e3}),!0}catch{return!1}}async function Vd(){try{let{stdout:u}=await Fc("semgrep",["--version"],{timeout:5e3});return u.trim()}catch{return null}}async function oy(u){let t={target:u.target||".",config:u.config||"auto",exclude:u.exclude||["node_modules",".git","dist","build","coverage"],maxFileSize:u.maxFileSize||5e6,timeout:u.timeout||300,verbose:u.verbose||!1};if(!await Vi())return{success:!1,findings:[],errors:["Semgrep is not installed. Install with: pip install semgrep"]};try{let r=["scan",`--config=${t.config}`,"--json",t.verbose?"--verbose":"--quiet",`--max-target-bytes=${t.maxFileSize}`];for(let o of t.exclude)r.push(`--exclude=${o}`);r.push(t.target);let i=(t.timeout??300)*1e3,{stdout:n,stderr:s}=await Fc("semgrep",r,{timeout:i,maxBuffer:50*1024*1024,cwd:zd.isAbsolute(t.target)?void 0:process.cwd()}),a=_d(n);return s&&t.verbose&&a.errors.push(s),a.version=await Vd()||void 0,a}catch(r){let i=r;if(i.stdout)try{let n=_d(i.stdout);return n.version=await Vd()||void 0,n}catch{}return{success:!1,findings:[],errors:[i.message??String(r)]}}}function _d(u){try{let t=E(u),e=t.results||t.findings||[],r=t.errors?.map(i=>i.message||String(i))||[];return{success:!0,findings:e.map(i=>({check_id:i.check_id||i.rule_id||"unknown",path:i.path,start:{line:i.start?.line||1,col:i.start?.col||1},end:{line:i.end?.line||i.start?.line||1,col:i.end?.col||1},extra:{message:i.extra?.message||i.message||"Security issue detected",severity:i.extra?.severity||i.severity||"WARNING",lines:i.extra?.lines||"",metadata:{cwe:i.extra?.metadata?.cwe||i.metadata?.cwe,owasp:i.extra?.metadata?.owasp||i.metadata?.owasp,category:i.extra?.metadata?.category||i.metadata?.category,description:i.extra?.metadata?.description||i.metadata?.description,fix:i.extra?.metadata?.fix||i.extra?.fix,references:i.extra?.metadata?.references||i.metadata?.references,confidence:i.extra?.metadata?.confidence||i.metadata?.confidence}}})),errors:r}}catch(t){return{success:!1,findings:[],errors:[`Failed to parse semgrep output: ${T(t)}`]}}}async function Gs(u,t,e){let r={"owasp-top-10":"p/owasp-top-ten","cwe-sans-25":"p/cwe-top-25","nodejs-security":"p/nodejs","typescript-security":"p/typescript","javascript-security":"p/javascript","react-security":"p/react","express-security":"p/express",secrets:"p/secrets","sql-injection":"p/sql-injection",xss:"p/xss","command-injection":"p/command-injection","path-traversal":"p/path-traversal"},i=t.map(n=>r[n]||`p/${n}`).join(",");return oy({...e,target:u,config:i||"auto"})}function cy(u){return{ERROR:"high",WARNING:"medium",INFO:"low"}[u]||"medium"}function Hs(u){return u.map(t=>({id:t.check_id,title:t.check_id.split(".").pop()||t.check_id,description:t.extra.message,severity:cy(t.extra.severity),file:t.path,line:t.start.line,column:t.start.col,snippet:t.extra.lines,cweId:t.extra.metadata?.cwe?.[0],owaspCategory:t.extra.metadata?.owasp?.[0],remediation:t.extra.metadata?.fix||"Review and fix the identified security issue",references:t.extra.metadata?.references||[]}))}var ly=R.create("security-compliance/sast-scanner"),wr=class{config;memory;llmRouter;activeScans;constructor(t,e,r,i){this.config=t,this.memory=e,this.llmRouter=r,this.activeScans=i||new Map}async scanFiles(t){return this.scanWithRules(t,this.config.defaultRuleSets)}async scanWithRules(t,e){let r=v();try{if(t.length===0)return p(new Error("No files provided for scanning"));this.activeScans.set(r,"running");let i=Date.now(),n=Ni.filter(h=>e.includes(h.id));if(n.length===0)return p(new Error(`No valid rule sets found: ${e.join(", ")}`));let[s,a]=await Promise.all([this.runPatternScanning(t,n),this.runSemgrepScanning(t,e)]),o=this.mergeVulnerabilities(s.vulnerabilities,a),c=s.linesScanned,l=Date.now()-i,d=this.calculateSummary(o,t.length,l),m=n.reduce((h,b)=>h+b.ruleCount,0),g={filesScanned:t.length,linesScanned:c,rulesApplied:m+(a.length>0?a.length:0)};return await this.storeScanResults(r,"sast",o,d),this.activeScans.set(r,"completed"),f({scanId:r,vulnerabilities:o,summary:d,coverage:g})}catch(i){return this.activeScans.set(r,"failed"),p(y(i))}}async runPatternScanning(t,e){let r=[],i=0;for(let n of t){let s=await this.analyzeFile(n,e);r.push(...s.vulnerabilities),i+=s.linesScanned}return{vulnerabilities:r,linesScanned:i}}async runSemgrepScanning(t,e){if(!this.config.enableSemgrep)return[];try{if(!await Vi())return[];let i=this.resolveTargetDirectory(t),n=await Gs(i,e);return!n.success||n.findings.length===0?[]:Hs(n.findings).map(a=>({id:v(),cveId:void 0,title:a.title,description:`[semgrep] ${a.description}`,severity:a.severity,category:this.mapSemgrepCategory(a.owaspCategory),location:{file:a.file,line:a.line,column:a.column,snippet:a.snippet},remediation:{description:a.remediation,estimatedEffort:"moderate",automatable:!1},references:a.references}))}catch{return[]}}resolveTargetDirectory(t){if(t.length===0)return".";if(t.length===1)return t[0].directory||".";let e=t.map(a=>a.directory||"."),r=e[0],i=r.length;for(let a=1;a<e.length;a++){let o=e[a],c=Math.min(i,o.length),l=0;for(;l<c&&r[l]===o[l];)l++;i=l}let n=r.substring(0,i),s=n.lastIndexOf("/");return s>0?n.substring(0,s):n||"."}mapSemgrepCategory(t){if(!t)return"injection";let e={A01:"access-control",A02:"sensitive-data",A03:"injection",A04:"insecure-deserialization",A05:"security-misconfiguration",A06:"vulnerable-components",A07:"broken-auth",A08:"insecure-deserialization",A09:"insufficient-logging",A10:"xxe"};for(let[r,i]of Object.entries(e))if(t.startsWith(r))return i;return"injection"}mergeVulnerabilities(t,e){if(e.length===0)return t;if(t.length===0)return e;let r=new Set(t.map(n=>`${n.location.file}:${n.location.line??0}:${n.category}`)),i=e.filter(n=>!r.has(`${n.location.file}:${n.location.line??0}:${n.category}`));return[...t,...i]}async getAvailableRuleSets(){let t=await this.memory.get("security:custom-rule-sets");return[...Ni,...t||[]]}async checkFalsePositive(t){try{if(!this.config.enableFalsePositiveDetection)return f({isFalsePositive:!1,confidence:0,reason:"False positive detection is disabled"});let e=await this.analyzeFalsePositive(t);return await this.memory.set(`security:fp-check:${t.id}`,{vulnerability:t,analysis:e},{namespace:"security-compliance",ttl:86400*30}),f(e)}catch(e){return p(y(e))}}async analyzeFile(t,e){let r=[],i=t.value,n=t.extension,s,a;try{s=await(await import("fs/promises")).readFile(i,"utf-8"),a=s.split(`
2893
2893
  `)}catch{return{vulnerabilities:[],linesScanned:0}}let o=a.length;if(!["ts","tsx","js","jsx","mjs","cjs"].includes(n))return{vulnerabilities:[],linesScanned:o};let l=new Set(e.flatMap(m=>m.categories)),d=qs.filter(m=>l.has(m.category));for(let m of d){let g=this.findPatternMatches(s,a,m);for(let h of g)this.isInComment(s,h.index)||this.isInDocumentation(h.snippet)||this.hasNosecAnnotation(a,h.line)||r.push(this.createVulnerabilityFromPattern(m,i,h))}return{vulnerabilities:r,linesScanned:o}}findPatternMatches(t,e,r){let i=[],n=new RegExp(r.pattern.source,r.pattern.flags),s;for(;(s=n.exec(t))!==null;){let a=s.index,{line:o,column:c}=this.getLineAndColumn(t,a),l=[],d=Math.max(0,o-2),m=Math.min(e.length-1,o+1);for(let h=d;h<=m;h++)l.push(e[h]);let g=l.join(`
2894
2894
  `);i.push({index:a,line:o+1,column:c+1,snippet:g})}return i}getLineAndColumn(t,e){let i=t.substring(0,e).split(`
2895
2895
  `),n=i.length-1,s=i[i.length-1].length;return{line:n,column:s}}isInComment(t,e){let r=t.substring(0,e),i=r.lastIndexOf(`
@@ -2921,7 +2921,7 @@ Provide detailed remediation advice specific to this code.`}],model:r,maxTokens:
2921
2921
  `),K=z.length,Ce=z[z.length-1].length+1,Y=S[K-1]||"";if(Y.trimStart().startsWith("//")||Y.trimStart().startsWith("*")||Y.includes("// nosec")||Y.includes("// security-ignore"))continue;let G=Math.max(0,K-2),ne=Math.min(S.length,K+1),X=S.slice(G,ne).join(`
2922
2922
  `),zm={file:b,line:K,column:Ce,snippet:X},Bm={description:k.remediation,fixExample:k.fixExample,estimatedEffort:k.severity==="critical"?"moderate":"minor",automatable:k.severity==="low"||k.severity==="medium"};i.push({id:v(),cveId:void 0,title:k.title,description:`${k.description} [${k.cweId}]`,severity:k.severity,category:k.category,location:zm,remediation:Bm,references:[`https://cwe.mitre.org/data/definitions/${k.cweId.replace("CWE-","")}.html`]})}}}catch{}}}catch(g){Cy.error("SAST scan failed:",g instanceof Error?g:void 0)}let a=Date.now()-r,o=0,c=0,l=0,d=0,m=0;for(let g of i)switch(g.severity){case"critical":o++;break;case"high":c++;break;case"medium":l++;break;case"low":d++;break;case"informational":m++;break}return{scanId:e,vulnerabilities:i,summary:{critical:o,high:c,medium:l,low:d,informational:m,totalFiles:n,scanDurationMs:a},coverage:{filesScanned:n,linesScanned:s,rulesApplied:12}}}M();A();var Ry=R.create("security-compliance/security-auditor-dast");async function Zd(u){let t=v(),e=Date.now(),r=[],i=0;try{let d;try{d=new URL(u)}catch{return{scanId:t,targetUrl:u,vulnerabilities:[{id:v(),title:"Invalid Target URL",description:"The provided target URL is not valid",severity:"informational",category:"security-misconfiguration",location:{file:u},remediation:{description:"Provide a valid URL",estimatedEffort:"trivial",automatable:!1},references:[]}],summary:{critical:0,high:0,medium:0,low:0,informational:1,totalFiles:0,scanDurationMs:Date.now()-e},crawledUrls:0}}let m=new AbortController,g=setTimeout(()=>m.abort(),3e4);try{let h=await fetch(u,{method:"GET",headers:{"User-Agent":"AgenticQE-SecurityScanner/3.0",Accept:"text/html,application/json,*/*"},signal:m.signal,redirect:"follow"});clearTimeout(g),i=1;let b=h.headers,w=[{header:"strict-transport-security",title:"Missing HTTP Strict Transport Security (HSTS)",description:"HSTS header is missing, allowing downgrade attacks",severity:"medium",remediation:"Add Strict-Transport-Security header with appropriate max-age"},{header:"x-content-type-options",title:"Missing X-Content-Type-Options Header",description:"X-Content-Type-Options header is missing, allowing MIME sniffing attacks",severity:"low",remediation:"Add X-Content-Type-Options: nosniff header"},{header:"x-frame-options",title:"Missing X-Frame-Options Header",description:"X-Frame-Options header is missing, allowing clickjacking attacks",severity:"medium",remediation:"Add X-Frame-Options: DENY or SAMEORIGIN header"},{header:"content-security-policy",title:"Missing Content Security Policy",description:"CSP header is missing, increasing XSS attack surface",severity:"medium",remediation:"Implement a Content-Security-Policy header"},{header:"x-xss-protection",title:"Missing X-XSS-Protection Header",description:"X-XSS-Protection header is missing (legacy XSS filter)",severity:"low",remediation:"Add X-XSS-Protection: 1; mode=block header"}];for(let P of w)b.get(P.header)||r.push({id:v(),title:P.title,description:P.description,severity:P.severity,category:"security-misconfiguration",location:{file:u,snippet:`Response Headers: ${P.header} not present`},remediation:{description:P.remediation,estimatedEffort:"minor",automatable:!0},references:["https://owasp.org/www-project-secure-headers/"]});let C=b.get("set-cookie");C&&(C.toLowerCase().includes("secure")||r.push({id:v(),title:"Cookie Without Secure Flag",description:"Session cookie is set without the Secure flag",severity:"medium",category:"sensitive-data",location:{file:u,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add Secure flag to cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/controls/SecureCookieAttribute"]}),C.toLowerCase().includes("httponly")||r.push({id:v(),title:"Cookie Without HttpOnly Flag",description:"Session cookie is set without the HttpOnly flag, making it accessible to JavaScript",severity:"medium",category:"sensitive-data",location:{file:u,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add HttpOnly flag to session cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/HttpOnly"]}),C.toLowerCase().includes("samesite")||r.push({id:v(),title:"Cookie Without SameSite Attribute",description:"Cookie is set without the SameSite attribute, potentially vulnerable to CSRF",severity:"low",category:"broken-auth",location:{file:u,snippet:`Set-Cookie: ${C.substring(0,50)}...`},remediation:{description:"Add SameSite=Strict or SameSite=Lax to cookies",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-community/SameSite"]}));let S=b.get("server");S&&/[0-9]+\.[0-9]+/.test(S)&&r.push({id:v(),title:"Server Version Disclosure",description:`Server header reveals version information: ${S}`,severity:"low",category:"security-misconfiguration",location:{file:u,snippet:`Server: ${S}`},remediation:{description:"Remove or obfuscate server version information",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}),d.protocol==="http:"&&r.push({id:v(),title:"Insecure HTTP Protocol",description:"Target is using HTTP instead of HTTPS, exposing data in transit",severity:"high",category:"sensitive-data",location:{file:u},remediation:{description:"Use HTTPS with valid TLS certificate",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]});let k=[{path:"/.git/config",vuln:"Git Repository Exposed",severity:"high"},{path:"/.env",vuln:"Environment File Exposed",severity:"critical"},{path:"/phpinfo.php",vuln:"PHP Info Exposed",severity:"medium"},{path:"/wp-config.php.bak",vuln:"WordPress Config Backup Exposed",severity:"critical"}];for(let P of k)try{let O=new URL(P.path,d.origin).toString(),z=await fetch(O,{method:"GET",signal:AbortSignal.timeout(5e3)});if(z.ok&&z.status===200){let K=await z.text();K.length>10&&!K.toLowerCase().includes("not found")&&(i++,r.push({id:v(),title:P.vuln,description:`Sensitive file found at ${P.path}`,severity:P.severity,category:"sensitive-data",location:{file:O},remediation:{description:"Remove or restrict access to sensitive files",estimatedEffort:"trivial",automatable:!0},references:["https://owasp.org/www-project-web-security-testing-guide/"]}))}}catch{}}catch(h){clearTimeout(g);let b=T(h);(b.includes("certificate")||b.includes("SSL")||b.includes("TLS"))&&r.push({id:v(),title:"TLS/SSL Certificate Issue",description:`Certificate error: ${b}`,severity:"high",category:"security-misconfiguration",location:{file:u},remediation:{description:"Fix TLS certificate configuration",estimatedEffort:"moderate",automatable:!1},references:["https://owasp.org/www-project-web-security-testing-guide/"]})}}catch(d){Ry.error("DAST scan failed:",d instanceof Error?d:void 0)}let n=Date.now()-e,s=0,a=0,o=0,c=0,l=0;for(let d of r)switch(d.severity){case"critical":s++;break;case"high":a++;break;case"medium":o++;break;case"low":c++;break;case"informational":l++;break}return{scanId:t,targetUrl:u,vulnerabilities:r,summary:{critical:s,high:a,medium:o,low:c,informational:l,totalFiles:1,scanDurationMs:n},crawledUrls:i}}M();import*as em from"fs/promises";var Ty=R.create("security-compliance/security-auditor-secrets");function Ay(){return[{name:"AWS Access Key ID",type:"api-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"AWS Secret Access Key",type:"api-key",regex:/(?:aws[_-]?secret[_-]?access[_-]?key|AWS_SECRET_ACCESS_KEY)['"]?\s*[:=]\s*['"]?([A-Za-z0-9/+=]{40})['"]?/gi,entropyThreshold:4},{name:"GitHub Personal Access Token",type:"token",regex:/ghp_[A-Za-z0-9]{36}/g},{name:"GitHub OAuth Access Token",type:"token",regex:/gho_[A-Za-z0-9]{36}/g},{name:"GitHub App Token",type:"token",regex:/(?:ghu|ghs)_[A-Za-z0-9]{36}/g},{name:"Generic API Key",type:"api-key",regex:/(?:api[_-]?key|apikey|api_secret)['"]?\s*[:=]\s*['"]([A-Za-z0-9_\-]{20,})['"]?/gi,entropyThreshold:3.5},{name:"OpenAI API Key",type:"api-key",regex:/sk-[A-Za-z0-9]{48}/g},{name:"Stripe Secret Key",type:"api-key",regex:/sk_live_[A-Za-z0-9]{24,}/g},{name:"Stripe Publishable Key",type:"api-key",regex:/pk_live_[A-Za-z0-9]{24,}/g},{name:"RSA Private Key",type:"private-key",regex:/-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----/gi},{name:"PGP Private Key",type:"private-key",regex:/-----BEGIN\s+PGP\s+PRIVATE\s+KEY\s+BLOCK-----/gi},{name:"SSH Private Key",type:"private-key",regex:/-----BEGIN\s+(?:OPENSSH|DSA|EC)?\s*PRIVATE\s+KEY-----/gi},{name:"Password Assignment",type:"password",regex:/(?:password|passwd|pwd|secret)['"]?\s*[:=]\s*['"]([^'"\s]{8,})['"]?/gi,entropyThreshold:3},{name:"Database Connection String",type:"password",regex:/(?:mongodb|postgres|mysql|redis):\/\/[^:]+:[^@]+@[^\s'"]+/gi},{name:"JWT Token",type:"token",regex:/eyJ[A-Za-z0-9_-]*\.eyJ[A-Za-z0-9_-]*\.[A-Za-z0-9_-]*/g,entropyThreshold:4},{name:"Slack Token",type:"token",regex:/xox[baprs]-[A-Za-z0-9-]{10,}/g},{name:"Google API Key",type:"api-key",regex:/AIza[A-Za-z0-9_-]{35}/g},{name:"Twilio API Key",type:"api-key",regex:/SK[A-Za-z0-9]{32}/g},{name:"SendGrid API Key",type:"api-key",regex:/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/g},{name:"X.509 Certificate",type:"certificate",regex:/-----BEGIN\s+CERTIFICATE-----/gi}]}function Ey(u){if(!u||u.length===0)return 0;let t={};for(let i of u)t[i]=(t[i]||0)+1;let e=0,r=u.length;for(let i in t){let n=t[i]/r;e-=n*Math.log2(n)}return e}function xy(u,t,e){let n=Math.max(0,t-20),s=Math.min(u.length,t+e+10),a=u.substring(n,s),o=t-n,c=a.substring(o,o+e);if(c.length>8){let l=c.substring(0,4)+"..."+c.substring(c.length-4);a=a.substring(0,o)+l+a.substring(o+e)}return n>0&&(a="..."+a),s<u.length&&(a=a+"..."),a}function Py(u,t){switch(u){case"api-key":return t.length>=20&&/[a-z]/.test(t)&&/[A-Z0-9]/.test(t);case"token":return t.length>=20;case"password":return!["password","secret","changeme","12345678","qwerty"].includes(t.toLowerCase());case"private-key":return!0;case"certificate":return!0;default:return!0}}async function Hc(u){let t=[];try{let r=(await em.readFile(u.value,"utf-8")).split(`
2923
2923
  `),i=Ay();for(let n=0;n<r.length;n++){let s=r[n],a=n+1;for(let o of i){o.regex.lastIndex=0;let c;for(;(c=o.regex.exec(s))!==null;){let l=c[1]||c[0],d=Ey(l);if(o.entropyThreshold&&d<o.entropyThreshold)continue;let m=xy(s,c.index,l.length),g={file:u.value,line:a,column:c.index+1,snippet:m};t.push({type:o.type,location:g,entropy:d,isValid:Py(o.type,l)})}}}}catch(e){Ty.error(`Failed to scan file for secrets: ${u.value}`,e instanceof Error?e:void 0)}return t}function tm(u,t,e,r){let i=0,n=0;if(u&&(i+=Wc(u.summary)*.35,n+=.35),t&&(i+=Wc(t.summary)*.25,n+=.25),e&&(i+=Wc(e.summary)*.25,n+=.25),r){let a=r.secretsFound.length>0?.9:.1;i+=a*.15,n+=.15}let s=n>0?i/n:0;return{value:Math.min(1,s),percentage:s*100,level:s>=.8?"critical":s>=.6?"high":s>=.3?"medium":"low"}}function Wc(u){let t={critical:1,high:.7,medium:.4,low:.1,informational:.02};if(u.critical+u.high+u.medium+u.low+u.informational===0)return 0;let r=u.critical*t.critical+u.high*t.high+u.medium*t.medium+u.low*t.low+u.informational*t.informational;return Math.min(1,r/10)}function rm(u,t,e,r){let i=[];return u&&u.summary.critical>0&&i.push(`Address ${u.summary.critical} critical vulnerabilities found in static analysis`),t&&t.summary.high>0&&i.push(`Fix ${t.summary.high} high-severity issues found in dynamic testing`),e&&e.outdatedPackages.length>5&&i.push(`Update ${e.outdatedPackages.length} outdated dependencies`),r&&r.secretsFound.length>0&&i.push(`Remove ${r.secretsFound.length} exposed secrets and rotate credentials`),i.length===0&&i.push("Security posture is good. Continue regular scanning."),i}function jc(u,t){if(!u)return 0;let e=0;return u.sastResults&&(e+=u.sastResults.summary[t]),u.dastResults&&(e+=u.dastResults.summary[t]),u.dependencyResults&&(e+=u.dependencyResults.summary[t]),e}function Rr(u){if(!u)return 0;let t=0;return u.sastResults&&(t+=u.sastResults.vulnerabilities.length),u.dastResults&&(t+=u.dastResults.vulnerabilities.length),u.dependencyResults&&(t+=u.dependencyResults.vulnerabilities.length),t}function im(u,t){if(!u||!t)return"stable";let e=Rr(u),r=Rr(t);return e<r*.9?"improving":e>r*1.1?"declining":"stable"}function nm(u,t,e){let r=100;return r-=u*20,r-=t*10,r-=e*2,Math.max(0,Math.min(100,r))}function sm(u,t,e){let r=[];return u>0&&r.push("Immediately address all critical vulnerabilities"),t>3&&r.push("Prioritize fixing high-severity issues"),e<50&&(r.push("Consider a comprehensive security review"),r.push("Implement automated security scanning in CI/CD")),e>=80&&(r.push("Maintain current security practices"),r.push("Consider penetration testing for deeper analysis")),r}function am(u){let t=u.remediation.estimatedEffort;return u.severity==="critical"?"immediate":u.severity==="high"?t==="trivial"||t==="minor"?"immediate":"shortTerm":u.severity==="medium"?t==="major"?"longTerm":"mediumTerm":u.severity==="low"||u.severity==="informational"?"longTerm":"accepted"}var Ze=R.create("security-compliance/security-auditor"),Bt=class{constructor(t,e={}){this.memory=t;this.config={...Gc,...e}}memory;config;async scanDependencies(t){try{let e=t.value,r=this.detectEcosystem(e);if(!r)return p(new Error(`Unknown manifest format: ${e}`));let i=[],n=[],s=await this.parseDependencies(e,r);for(let o of s){let c=await this.checkDependencyVulnerabilities(o,r);i.push(...c);let l=await this.checkOutdated(o);l&&n.push(l)}let a=this.createDependencySummary(i,s.length);return await this.memory.set(`security:deps:${t.filename}`,{vulnerabilities:i,outdatedPackages:n,summary:a},{namespace:"security-compliance",ttl:86400}),f({vulnerabilities:i,outdatedPackages:n,summary:a})}catch(e){return p(y(e))}}async checkPackage(t,e,r){try{let i=await this.queryVulnerabilityDatabase(t,e,r),n=await this.getLatestVersion(t,r),s=await this.checkDeprecation(t,r);return f({name:t,version:e,vulnerabilities:i,latestVersion:n,isDeprecated:s})}catch(i){return p(y(i))}}async getUpgradeRecommendations(t){try{let e=[],r=new Map;for(let i of t){let n=i.location.dependency;if(n){let s=`${n.ecosystem}:${n.name}`,a=r.get(s)||[];a.push(i),r.set(s,a)}}for(let[i,n]of r){let[s,a]=i.split(":"),o=n[0].location.dependency?.version||"unknown",c=await this.getLatestVersion(a,s),l=n.filter(d=>d.id).map(d=>d.id);e.push({package:a,fromVersion:o,toVersion:c,fixesVulnerabilities:l,breakingChanges:this.hasBreakingChanges(o,c)})}return e.sort((i,n)=>n.fixesVulnerabilities.length-i.fixesVulnerabilities.length),f(e)}catch(e){return p(y(e))}}async runAudit(t){let e=v(),r=new Date;try{let i,n,s,a;t.includeSAST&&(i=await Xd(d=>this.findSourceFiles(d),d=>this.shouldExclude(d))),t.includeDAST&&t.targetUrl&&(n=await Zd(t.targetUrl)),t.includeDependencies&&(s=await this.performDependencyScan()),t.includeSecrets&&(a=await this.performSecretScan());let o=tm(i,n,s,a),c=rm(i,n,s,a),l={auditId:e,timestamp:r,sastResults:i,dastResults:n,dependencyResults:s,secretScanResults:a,overallRiskScore:o,recommendations:c};return await this.memory.set(`security:audit:${e}`,l,{namespace:"security-compliance",persist:!0}),f(l)}catch(i){return p(y(i))}}async scanSecrets(t){try{let e=[],r=0;for(let i of t){if(this.shouldExclude(i.value))continue;r++;let n=await Hc(i);e.push(...n)}return f({secretsFound:e,filesScanned:r})}catch(e){return p(y(e))}}async getSecurityPosture(){try{let t=await this.getRecentAudits(),e=t[0],r=t[1],i=jc(e,"critical"),n=jc(e,"high"),s=Rr(e),a=im(e,r),o=nm(i,n,s),c=sm(i,n,o);return f({overallScore:o,trend:a,criticalIssues:i,highIssues:n,openVulnerabilities:s,resolvedLastWeek:await this.countResolvedLastWeek(),averageResolutionTime:await this.calculateAverageResolutionTime(),lastAuditDate:e?.timestamp??new Date,recommendations:c})}catch(t){return p(y(t))}}async triageVulnerabilities(t){try{let e={immediate:[],shortTerm:[],mediumTerm:[],longTerm:[],accepted:[]};for(let i of t){let n=am(i);e[n].push(i)}let r=["critical","high","medium","low","informational"];for(let i of Object.values(e))i.sort((n,s)=>r.indexOf(n.severity)-r.indexOf(s.severity));return f(e)}catch(e){return p(y(e))}}detectEcosystem(t){return t.includes("package.json")?"npm":t.includes("requirements.txt")||t.includes("Pipfile")?"pip":t.includes("pom.xml")||t.includes("build.gradle")?"maven":t.includes("Cargo.toml")?"cargo":t.includes(".csproj")||t.includes("packages.config")?"nuget":null}async parseDependencies(t,e){let r=[];try{if(e==="npm"){let i=await Hi.readFile(t,"utf-8"),n=E(i),s={...n.dependencies,...n.devDependencies,...n.peerDependencies,...n.optionalDependencies};for(let[a,o]of Object.entries(s)){let c=this.cleanVersionSpec(o);r.push({name:a,version:c,ecosystem:"npm"})}}else if(e==="pip"){let n=(await Hi.readFile(t,"utf-8")).split(`
2924
- `);for(let s of n){let a=s.trim();if(!a||a.startsWith("#"))continue;let o=a.match(/^([a-zA-Z0-9_-]+)(?:[=<>~!]+(.+))?$/);o&&r.push({name:o[1],version:o[2]||"latest",ecosystem:"pip"})}}}catch(i){Ze.error(`Failed to parse dependencies from ${t}:`,i instanceof Error?i:void 0)}return r}cleanVersionSpec(t){return t.replace(/^[\^~>=<]+/,"").trim()}async checkDependencyVulnerabilities(t,e){let r=[];try{let i=this.mapToOSVEcosystem(e),n={package:{name:t.name,ecosystem:i},version:t.version},s=await qc("https://api.osv.dev/v1/query",n);if(s.ok&&s.data.vulns&&s.data.vulns.length>0)for(let a of s.data.vulns){let o=this.mapOSVVulnerability(a,t);r.push(o)}}catch(i){Ze.error(`Failed to check vulnerabilities for ${t.name}@${t.version}:`,i instanceof Error?i:void 0)}return r}mapToOSVEcosystem(t){return{npm:"npm",pip:"PyPI",maven:"Maven",nuget:"NuGet",cargo:"crates.io"}[t]}mapOSVVulnerability(t,e){let r=t.aliases?.find(c=>c.startsWith("CVE-")),i=this.mapOSVSeverity(t.severity),n=this.extractFixedVersion(t),s=t.references?.map(c=>c.url)||[],a={file:"package.json",dependency:e},o={description:n?`Upgrade ${e.name} to version ${n} or higher`:`Review and address vulnerability in ${e.name}`,fixExample:n?`"${e.name}": "^${n}"`:void 0,estimatedEffort:n?"trivial":"moderate",automatable:!!n};return{id:v(),cveId:r,title:t.summary||`Vulnerability in ${e.name}`,description:t.details||t.summary||"No description available",severity:i,category:this.categorizeVulnerability(t),location:a,remediation:o,references:s}}mapOSVSeverity(t){if(!t||t.length===0)return"medium";let e=t.find(r=>r.type==="CVSS_V3"||r.type==="CVSS_V2");if(e){let r=parseFloat(e.score);if(r>=9)return"critical";if(r>=7)return"high";if(r>=4)return"medium";if(r>0)return"low"}return"medium"}extractFixedVersion(t){if(t.affected){for(let e of t.affected)if(e.ranges){for(let r of e.ranges)if(r.events){let i=r.events.find(n=>n.fixed);if(i?.fixed)return i.fixed}}}}categorizeVulnerability(t){let e=(t.summary||"").toLowerCase(),r=(t.details||"").toLowerCase(),i=`${e} ${r}`;return i.includes("injection")||i.includes("sql")?"injection":i.includes("xss")||i.includes("cross-site scripting")?"xss":i.includes("authentication")||i.includes("auth bypass")?"broken-auth":i.includes("sensitive data")||i.includes("exposure")?"sensitive-data":i.includes("xxe")||i.includes("xml external")?"xxe":i.includes("access control")||i.includes("authorization")?"access-control":i.includes("deseriali")?"insecure-deserialization":(i.includes("prototype pollution")||i.includes("dependency"),"vulnerable-components")}async checkOutdated(t){let e=await this.getLatestVersion(t.name,t.ecosystem);return e!==t.version?{name:t.name,currentVersion:t.version,latestVersion:e,updateType:this.determineUpdateType(t.version,e)}:null}async queryVulnerabilityDatabase(t,e,r){let i={name:t,version:e,ecosystem:r};return this.checkDependencyVulnerabilities(i,r)}async getLatestVersion(t,e){try{if(e==="npm"){let r=await Gi(`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`);if(r.ok&&r.data.version)return r.data.version}else if(e==="pip"){let r=await Gi(`https://pypi.org/pypi/${encodeURIComponent(t)}/json`);if(r.ok&&r.data.info?.version)return r.data.info.version}}catch(r){Ze.error(`Failed to get latest version for ${t}:`,r instanceof Error?r:void 0)}return"unknown"}async checkDeprecation(t,e){try{if(e==="npm"){let r=await Gi(`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`);if(r.ok&&r.data.deprecated)return!0}}catch(r){Ze.error(`Failed to check deprecation for ${t}:`,r instanceof Error?r:void 0)}return!1}determineUpdateType(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number);return i[0]>r[0]?"major":i[1]>r[1]?"minor":"patch"}hasBreakingChanges(t,e){let r=parseInt(t.split(".")[0]);return parseInt(e.split(".")[0])>r}createDependencySummary(t,e){let r=0,i=0,n=0,s=0,a=0;for(let o of t)switch(o.severity){case"critical":r++;break;case"high":i++;break;case"medium":n++;break;case"low":s++;break;case"informational":a++;break}return{critical:r,high:i,medium:n,low:s,informational:a,totalFiles:e,scanDurationMs:0}}shouldExclude(t){return this.config.excludePatterns.some(e=>e.startsWith("*")?t.endsWith(e.slice(1)):t.includes(e))}async performDependencyScan(){let t=Date.now(),e=[],r=[];try{let i=Wi.join(process.cwd(),"package.json"),n=await this.parseDependencies(i,"npm");for(let o of n){let c=await this.checkDependencyVulnerabilities(o,o.ecosystem);e.push(...c);let l=await this.checkOutdated(o);l&&r.push(l)}let s=Date.now()-t,a=this.createDependencySummary(e,n.length);return{vulnerabilities:e,outdatedPackages:r,summary:{...a,scanDurationMs:s}}}catch(i){return Ze.error("Dependency scan failed:",i instanceof Error?i:void 0),{vulnerabilities:[],outdatedPackages:[],summary:{critical:0,high:0,medium:0,low:0,informational:0,totalFiles:0,scanDurationMs:Date.now()-t}}}}async performSecretScan(){let t=[],e=0;try{let r=await this.findSourceFiles(process.cwd());for(let i of r){if(this.shouldExclude(i))continue;e++;let s=await Hc({value:i});t.push(...s)}}catch(r){Ze.error("Secret scan failed:",r instanceof Error?r:void 0)}return{secretsFound:t,filesScanned:e}}async findSourceFiles(t,e=[]){let r=[".ts",".js",".tsx",".jsx",".json",".env",".yaml",".yml",".config"];try{let i=await Hi.readdir(t,{withFileTypes:!0});for(let n of i){let s=Wi.join(t,n.name);if(!this.shouldExclude(s)){if(n.isDirectory())await this.findSourceFiles(s,e);else if(n.isFile()){let a=Wi.extname(n.name).toLowerCase();(r.includes(a)||n.name.startsWith(".env"))&&e.push(s)}}}}catch{Ze.debug("Directory read error:")}return e}async getRecentAudits(){let t=await this.memory.search("security:audit:*",10),e=[];for(let r of t){let i=await this.memory.get(r);i&&e.push(i)}return e.sort((r,i)=>new Date(i.timestamp).getTime()-new Date(r.timestamp).getTime())}async countResolvedLastWeek(){try{let t=await this.getRecentAudits();if(t.length<2)return 0;let e=new Date(Date.now()-10080*60*1e3),r=t.filter(o=>new Date(o.timestamp)>=e);if(r.length<2)return 0;let i=r[r.length-1],n=r[0],s=Rr(i),a=Rr(n);return Math.max(0,s-a)}catch(t){return Ze.error("Failed to count resolved vulnerabilities:",t instanceof Error?t:void 0),0}}async calculateAverageResolutionTime(){try{let t=await this.getRecentAudits();if(t.length<2)return 72;let e=new Map,r=[],i=[...t].reverse();for(let s of i){let a=new Set;s.sastResults&&s.sastResults.vulnerabilities.forEach(o=>a.add(o.id)),s.dastResults&&s.dastResults.vulnerabilities.forEach(o=>a.add(o.id)),s.dependencyResults&&s.dependencyResults.vulnerabilities.forEach(o=>a.add(o.id));for(let o of a)e.has(o)||e.set(o,s.timestamp);for(let[o,c]of e)if(!a.has(o)){let l=(s.timestamp.getTime()-c.getTime())/36e5;r.push(l),e.delete(o)}}if(r.length===0)return 72;let n=r.reduce((s,a)=>s+a,0);return Math.round(n/r.length)}catch(t){return Ze.error("Failed to calculate average resolution time:",t instanceof Error?t:void 0),72}}};A();var ky={customStandards:[],strictMode:!1,includeRecommended:!0,evidenceRetentionDays:365},Iy={id:"gdpr",name:"General Data Protection Regulation",version:"2018",rules:[{id:"gdpr-art5-accuracy",title:"Data Accuracy",description:"Personal data must be accurate and kept up to date",category:"data-quality",severity:"required",checkType:"manual"},{id:"gdpr-art17-erasure",title:"Right to Erasure",description:"Data subjects have the right to request deletion of their data",category:"data-rights",severity:"required",checkType:"static"},{id:"gdpr-art25-privacy-design",title:"Privacy by Design",description:"Data protection must be built into systems from the start",category:"architecture",severity:"required",checkType:"static"},{id:"gdpr-art32-security",title:"Security of Processing",description:"Appropriate security measures must protect personal data",category:"security",severity:"required",checkType:"static"},{id:"gdpr-art33-breach-notification",title:"Breach Notification",description:"Data breaches must be reported within 72 hours",category:"incident-response",severity:"required",checkType:"manual"}]},Dy={id:"hipaa",name:"Health Insurance Portability and Accountability Act",version:"1996-amended",rules:[{id:"hipaa-164.312-access",title:"Access Control",description:"Implement technical policies for ePHI access",category:"access-control",severity:"required",checkType:"static"},{id:"hipaa-164.312-audit",title:"Audit Controls",description:"Implement hardware, software, and procedural audit mechanisms",category:"audit",severity:"required",checkType:"static"},{id:"hipaa-164.312-integrity",title:"Integrity Controls",description:"Protect ePHI from improper alteration or destruction",category:"data-integrity",severity:"required",checkType:"static"},{id:"hipaa-164.312-transmission",title:"Transmission Security",description:"Protect ePHI during electronic transmission",category:"encryption",severity:"required",checkType:"static"},{id:"hipaa-164.314-baa",title:"Business Associate Agreements",description:"Ensure contracts with business associates protect PHI",category:"contracts",severity:"required",checkType:"manual"}]},My={id:"soc2",name:"SOC 2 Type II",version:"2017",rules:[{id:"soc2-cc6.1",title:"Logical Access Security",description:"Security software, infrastructure, and architectures are implemented",category:"security",severity:"required",checkType:"static"},{id:"soc2-cc6.2",title:"Access Controls",description:"Registration and authorization of new users",category:"access-control",severity:"required",checkType:"static"},{id:"soc2-cc6.6",title:"Encryption",description:"Logical access security measures to protect data",category:"encryption",severity:"required",checkType:"static"},{id:"soc2-cc7.1",title:"System Monitoring",description:"Detect and respond to security incidents",category:"monitoring",severity:"required",checkType:"static"},{id:"soc2-cc8.1",title:"Change Management",description:"Changes to infrastructure are authorized and tested",category:"change-management",severity:"required",checkType:"manual"}]},Fy={id:"pci-dss",name:"Payment Card Industry Data Security Standard",version:"4.0",rules:[{id:"pci-req1",title:"Network Security Controls",description:"Install and maintain network security controls",category:"network-security",severity:"required",checkType:"static"},{id:"pci-req3",title:"Protect Account Data",description:"Protect stored account data",category:"data-protection",severity:"required",checkType:"static"},{id:"pci-req4",title:"Encrypt Transmissions",description:"Protect cardholder data with strong cryptography during transmission",category:"encryption",severity:"required",checkType:"static"},{id:"pci-req6",title:"Secure Development",description:"Develop and maintain secure systems and software",category:"secure-sdlc",severity:"required",checkType:"static"},{id:"pci-req10",title:"Log and Monitor Access",description:"Log and monitor all access to system components",category:"logging",severity:"required",checkType:"static"}]},Ly=[Iy,Dy,My,Fy],qt=class{constructor(t,e={}){this.memory=t;this.config={...ky,...e},this.patternAnalyzer=Bc(),this.standards=new Map;for(let r of Ly)this.standards.set(r.id,r);for(let r of this.config.customStandards)this.standards.set(r.id,r)}memory;config;standards;patternAnalyzer;async validate(t,e){try{let r=[],i=[],n=[],s=this.config.includeRecommended?t.rules:t.rules.filter(l=>l.severity==="required");for(let l of s){if(l.checkType==="manual"){n.push(l.id);continue}let d=await this.checkRule(l,e);d.passed?i.push(l.id):r.push(...d.violations)}let a=s.length-n.length,o=a>0?Math.round(i.length/a*100):100,c={standardId:t.id,standardName:t.name,violations:r,passedRules:i,skippedRules:n,complianceScore:o,generatedAt:new Date};return await this.storeReport(c),f(c)}catch(r){return p(y(r))}}async getAvailableStandards(){return Array.from(this.standards.values())}async analyzeGaps(t,e){try{let r=[],i=[],n=new Set(t.violations.map(l=>l.ruleId)),s=new Set(t.passedRules);for(let l of e.rules)n.has(l.id)?r.push({ruleId:l.id,currentStatus:"failed",effort:this.estimateEffort(l),impact:l.severity==="required"?"high":"medium"}):s.has(l.id)||r.push({ruleId:l.id,currentStatus:"not-implemented",effort:this.estimateEffort(l),impact:l.severity==="required"?"high":"low"});let a=[...r].sort((l,d)=>{let m={high:0,medium:1,low:2},g={trivial:0,minor:1,moderate:2,major:3},h=m[l.impact]*10+g[l.effort],b=m[d.impact]*10+g[d.effort];return h-b});for(let l=0;l<a.length;l++){let d=a[l],m=e.rules.find(g=>g.id===d.ruleId);i.push({id:v(),description:`Implement ${m?.title||d.ruleId}`,affectedRules:[d.ruleId],effort:d.effort,priority:l+1})}let o=100,c=t.complianceScore;return f({currentScore:c,targetScore:o,gaps:r,prioritizedActions:i})}catch(r){return p(y(r))}}async validateMultiple(t,e){try{let r=[],i=[];for(let a of t){let o=await this.validate(a,e);o.success&&r.push(o.value)}let n=new Map;for(let a of r)for(let o of a.violations){let c=`${o.location.file}:${o.location.line}`;n.set(c,(n.get(c)||0)+1)}for(let a of r)for(let o of a.violations){let c=`${o.location.file}:${o.location.line}`;(n.get(c)||0)>1&&(i.some(l=>l.location.file===o.location.file&&l.location.line===o.location.line)||i.push(o))}let s=r.length>0?Math.round(r.reduce((a,o)=>a+o.complianceScore,0)/r.length):0;return f({reports:r,overallScore:s,crossCuttingViolations:i})}catch(r){return p(y(r))}}async checkDataHandling(t,e){try{let r=new Map,i=[],n=[];for(let s of e)r.set(s,[]);for(let s of t){let a=await this.scanFileForDataTypes(s,e);for(let o of a){let c=r.get(o.type)||[];c.push(o.location),r.set(o.type,c);let l=this.checkDataTypeViolation(o);l&&i.push(l)}}for(let[s,a]of r)a.length>0&&n.push(...this.getDataTypeRecommendations(s,a.length));return f({dataTypesFound:r,violations:i,recommendations:[...new Set(n)]})}catch(r){return p(y(r))}}async generateEvidence(t,e){try{let r=this.standards.get(t);if(!r)return p(new Error(`Unknown standard: ${t}`));let i=await this.validate(r,e);if(!i.success)return p(i.error);let n=i.value,s=[];for(let o of r.rules){let c=n.passedRules.includes(o.id)?"implemented":n.skippedRules.includes(o.id)?"partial":"not-implemented";s.push({controlId:o.id,status:c,evidence:await this.collectEvidence(o,e),lastVerified:new Date})}let a={standardId:t,controls:s,generatedAt:new Date,validUntil:new Date(Date.now()+this.config.evidenceRetentionDays*24*60*60*1e3)};return await this.memory.set(`compliance:evidence:${t}:${Date.now()}`,a,{namespace:"security-compliance",persist:!0}),f(a)}catch(r){return p(y(r))}}async checkRule(t,e){let r=[],i=await this.getFilesFromContext(e);switch(t.category){case"encryption":r.push(...await this.checkEncryption(t,e,i));break;case"access-control":r.push(...await this.checkAccessControl(t,e,i));break;case"audit":case"logging":r.push(...await this.checkLogging(t,e,i));break;case"data-protection":case"data-quality":r.push(...await this.checkDataProtection(t,e,i));break;case"security":r.push(...await this.checkSecurityControls(t,e,i));break;default:break}return{passed:r.length===0,violations:r}}async getFilesFromContext(t){let e=[],r=t.projectRoot.value;if(t.includePatterns.length===0)return[];for(let i of t.includePatterns)t.excludePatterns.some(s=>i.includes(s)||s.includes(i))||e.push(`${r}/${i}`);return e}async checkEncryption(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeEncryption(r);for(let s of n.weakCrypto)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Weak or deprecated cryptographic algorithm detected",remediation:"Use strong encryption algorithms (AES-256, SHA-256 or higher)"});for(let s of n.unencryptedDataHandling)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive data handled without encryption verification",remediation:"Ensure data is encrypted before processing sensitive information"});return i}async checkAccessControl(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeAccessControl(r);for(let s of n.unprotectedRoutes)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive endpoint potentially missing authorization middleware",remediation:"Add authorization check before sensitive operations"});for(let s of n.hardcodedCredentials)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Hardcoded credentials detected",remediation:"Use environment variables or secure secret management"});return i}async checkLogging(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeLogging(r);for(let s of n.sensitiveOperationsWithoutLogging)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive operation without audit logging",remediation:"Add audit log entry for data modification operations"});for(let s of n.sensitiveDataInLogs)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive data being logged",remediation:"Remove or mask sensitive data before logging"});return i}async checkDataProtection(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeDataProtection(r);for(let s of n.unmaskedPii)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"PII field without masking or encryption decorator",remediation:"Apply data protection decorators to sensitive fields"});for(let s of n.missingValidation)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Data fields without input validation",remediation:"Add input validation for all data fields, especially PII"});return i}async checkSecurityControls(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeSecurityControls(r);for(let s of n.missingControls)i.push({ruleId:t.id,ruleName:t.title,location:{file:"project-wide",line:0,snippet:`Missing: ${s}`},details:`Security control not detected: ${s}`,remediation:`Implement ${s} to enhance security posture`});for(let s of n.vulnerabilities)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Security vulnerability detected",remediation:"Review and fix the security issue"});return i}estimateEffort(t){let e=["architecture","data-rights","incident-response"],r=["access-control","encryption","change-management"];return e.includes(t.category)?"major":r.includes(t.category)||t.checkType==="manual"?"moderate":"minor"}async scanFileForDataTypes(t,e){let r=[],i=await this.patternAnalyzer.scanForDataTypes([t.value],e);for(let n of e){let s=i.get(n)||[];for(let a of s)r.push({type:n,location:{file:a.file,line:a.line,context:a.snippet||this.getDataTypeContext(n)}})}return r}getDataTypeContext(t){return{pii:"User personal information field",phi:"Health-related data field",financial:"Payment/financial data field",credentials:"Authentication credential field",biometric:"Biometric data field"}[t]}checkDataTypeViolation(t){let e=t.location.context.toLowerCase(),i=[/encrypt/i,/hash/i,/mask/i,/redact/i,/validate/i,/sanitize/i,/bcrypt/i,/argon2/i,/aes/i].some(a=>a.test(e)),s=[/console\.(log|debug|info)/i,/JSON\.stringify/i,/\.toString\(\)/i,/plaintext/i,/unencrypted/i].some(a=>a.test(e));if(!i||s){let a={pii:"gdpr-art32-security",phi:"hipaa-164.312-transmission",financial:"pci-req3",credentials:"soc2-cc6.6",biometric:"gdpr-art9-special"},o={file:t.location.file,line:t.location.line,snippet:t.location.context},c=s?"Potentially exposed in logs or serialization":"No protective measures detected";return{ruleId:a[t.type],ruleName:`${t.type.toUpperCase()} Data Protection`,location:o,details:`${t.type.toUpperCase()} data found: ${c}`,remediation:`Apply appropriate security controls for ${t.type} data`}}return null}getDataTypeRecommendations(t,e){let r=`Found ${e} ${t.toUpperCase()} data locations`;return{pii:[r,"Implement data minimization principles","Ensure consent mechanisms are in place","Add data retention policies"],phi:[r,"Verify HIPAA safeguards are implemented","Ensure business associate agreements are in place","Implement minimum necessary access"],financial:[r,"Verify PCI-DSS compliance for payment data","Implement tokenization where possible","Ensure proper key management"],credentials:[r,"Use secure credential storage (vaults)","Implement credential rotation","Avoid hardcoded credentials"],biometric:[r,"Implement enhanced protection measures","Obtain explicit consent","Consider data localization requirements"]}[t]}async collectEvidence(t,e){let r=[],i=await this.getFilesFromContext(e);if(t.checkType==="static"&&i.length>0){switch(t.category){case"encryption":{let n=await this.patternAnalyzer.analyzeEncryption(i);n.hasEncryption&&r.push(`Encryption detected: ${n.encryptionLibraries.join(", ")||"standard crypto"}`),n.weakCrypto.length>0&&r.push(`Weak crypto found in ${n.weakCrypto.length} location(s)`),r.push(`Unencrypted data handling: ${n.unencryptedDataHandling.length} instance(s)`);break}case"access_control":{let n=await this.patternAnalyzer.analyzeAccessControl(i);r.push(`Auth middleware: ${n.hasAuthMiddleware?"present":"not found"}`),r.push(`Unprotected routes: ${n.unprotectedRoutes.length}`),r.push(`Hardcoded credentials: ${n.hardcodedCredentials.length}`);break}case"logging":{let n=await this.patternAnalyzer.analyzeLogging(i);r.push(`Audit logging: ${n.hasAuditLogging?"implemented":"not found"}`),r.push(`Sensitive data in logs: ${n.sensitiveDataInLogs.length} instance(s)`);break}case"data_protection":{let n=await this.patternAnalyzer.analyzeDataProtection(i);r.push(`PII fields detected: ${n.piiFields.length}`),r.push(`Unmasked PII: ${n.unmaskedPii.length} instance(s)`),r.push(`Missing validation: ${n.missingValidation.length} field(s)`);break}default:r.push(`Static analysis completed for ${t.category}`),r.push(`Code patterns reviewed: ${t.title}`)}r.push(`Files analyzed: ${i.length}`)}else t.checkType==="dynamic"?(r.push(`Dynamic check required for: ${t.title}`),r.push("Evidence collection pending dynamic analysis")):t.checkType==="manual"&&(r.push(`Manual verification required for: ${t.title}`),r.push(`Review scope: ${e.projectRoot.value}`));return r.push(`Rule ${t.id} verified at ${new Date().toISOString()}`),r}async storeReport(t){await this.memory.set(`compliance:report:${t.standardId}:${Date.now()}`,t,{namespace:"security-compliance",persist:!0})}};var $y={stateSize:10,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0},ua=class extends ae{qNetwork;targetNetwork;replayBufferClass;dqnConfig;updateCount=0;actions=[];constructor(t={}){super("dqn","value-based"),this.dqnConfig={...$y,...t},this.initializeActions(),this.qNetwork=new q({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new Ke(this.config.replayBufferSize,!1)}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.targetNetwork.forward(e),i=this.argmax(r),n=this.actions[i];return{action:n,confidence:.7,value:r[i],reasoning:`DQN: ${n.type}`}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.dqnConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize),r=0;for(let i of e){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a=this.actionToIndex(i.action),o=this.qNetwork.forward(n),c;if(this.dqnConfig.doubleDQN&&!i.done){let d=this.qNetwork.forward(s),m=this.argmax(d),g=this.targetNetwork.forward(s);c=i.reward+this.config.discountFactor*g[m]}else{let d=this.targetNetwork.forward(s);c=i.reward+this.config.discountFactor*Math.max(...d)*(i.done?0:1)}let l=new Float32Array(o.length);for(let d=0;d<l.length;d++)l[d]=d===a?c:o[d];r+=Math.abs(this.qNetwork.train(n,l,new fe))}return this.updateCount++,this.updateCount%this.dqnConfig.targetUpdateFreq===0&&(this.targetNetwork=this.qNetwork.clone()),{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural DQN for Parallel Execution Scheduling",capabilities:["Experience replay","Target network","Double DQN"],hyperparameters:{stateSize:this.dqnConfig.stateSize,actionSize:this.dqnConfig.actionSize,hiddenLayers:this.dqnConfig.hiddenLayers.join(",")},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.dqnConfig.stateSize);for(;e.length<this.dqnConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"parallelize",value:2},{type:"parallelize",value:4},{type:"parallelize",value:8},{type:"sequential",value:1},{type:"skip",value:0}],this.dqnConfig.actionSize=this.actions.length,this.qNetwork=new q({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone()}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),targetNetwork:this.targetNetwork.getParameters(),dqnConfig:this.dqnConfig,updateCount:this.updateCount}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.targetNetwork&&this.targetNetwork.setParameters(t.targetNetwork),t.dqnConfig&&(this.dqnConfig={...this.dqnConfig,...t.dqnConfig}),typeof t.updateCount=="number"&&(this.updateCount=t.updateCount),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new q({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var Oy={maxConcurrentWorkflows:3,defaultTimeout:3e5,publishEvents:!0,autoTriageVulnerabilities:!0,riskThreshold:.7,enableDQN:!0,enableFlashAttention:!0,enableConsensus:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},te=R.create("security-compliance"),ji=class extends Q{constructor(e,r,i,n={}){let s={...Oy,...n};super(e,"security-compliance",s,{verifyFindingTypes:["security-vulnerability","compliance-violation","credential-exposure"],...s.consensusMixinConfig});this.memory=r;this.agentCoordinator=i;this.securityGovernanceMixin=iu(this.domainName),this.securityScanner=new $e(r),this.securityAuditor=new Bt(r),this.complianceValidator=new qt(r)}memory;agentCoordinator;securityScanner;securityAuditor;complianceValidator;dqnAlgorithm;flashAttention;rlInitialized=!1;consensusEngine;securityGovernanceMixin;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enableDQN||this.config.enableFlashAttention||this.config.enableConsensus)&&await this.initializeRLIntegrations()}async initializeRLIntegrations(){try{if(this.config.enableDQN&&(this.dqnAlgorithm=new ua({stateSize:8,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0})),this.config.enableFlashAttention){let e="test-similarity";this.flashAttention=await Ie(e,{dim:384,strategy:"flash",numHeads:8})}if(this.config.enableConsensus){let r=kt(!0).getAll();r.length>0?(this.consensusEngine=ui({strategy:"weighted",models:r,engineConfig:{minModels:Math.min(2,r.length),defaultModelTimeout:6e4,...this.config.consensusEngineConfig}}),te.info(`Multi-Model Consensus initialized with ${r.length} providers`)):te.warn("No model providers available for consensus verification")}this.rlInitialized=!0}catch(e){throw te.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){await this.saveWorkflowState()}getActiveWorkflows(){return super.getActiveWorkflows()}async runSecurityAudit(e){let r=v();try{if(this.startWorkflow(r,"audit"),this.detectAuthCodeInScope(e)&&this.securityGovernanceMixin.isGovernanceEnabled()&&!(await this.securityGovernanceMixin.validateSecurityScanRequired(r,!0,void 0)).allowed&&this.securityGovernanceMixin.isStrictMode()&&te.info("Security audit for auth code registered with governance"),this.minCutMixin.shouldPauseOperations())return te.warn("Security audit paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Security audit paused: topology is in critical state"));if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&te.warn("Topology degraded, using conservative audit strategy"),!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn security audit agents"));let n=await this.spawnSecurityAuditAgent(r,e);if(!n.success)return this.failWorkflow(r,n.error.message),p(n.error);this.addAgentToWorkflow(r,n.value);let s=e.tests||[];this.config.enableDQN&&this.dqnAlgorithm&&s.length>0&&(s=await this.prioritizeSecurityTests(e,s));let a={...e},o=await this.securityAuditor.runAudit(a);if(o.success){this.completeWorkflow(r);let c=this.extractVulnerabilitiesFromReport(o.value);this.config.enableFlashAttention&&this.flashAttention&&c.length>0&&await this.enhanceVulnerabilityAnalysis(c),this.config.enableDQN&&this.dqnAlgorithm&&await this.trainDQNWithAuditFeedback(e,o.value),this.config.publishEvents&&await this.publishSecurityAuditCompleted(o.value)}else this.failWorkflow(r,o.error.message);return await this.agentCoordinator.stop(n.value),o}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async runSecurityScan(e,r){let i=v();try{if(this.startWorkflow(i,"scan"),this.minCutMixin.shouldPauseOperations())return te.warn("Security scan paused: topology is in critical state"),this.failWorkflow(i,"Topology is in critical state"),p(new Error("Security scan paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&te.warn("Topology degraded, proceeding with conservative scan strategy");let n;return r==="sast"?n=await this.securityScanner.scanFiles(e):r==="dast"?n=await this.securityScanner.scanUrl(e[0]?.value??""):n=await this.securityScanner.scanFiles(e),n.success?this.completeWorkflow(i):this.failWorkflow(i,n.error.message),n}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async runComplianceValidation(e,r){let i=v();try{if(this.startWorkflow(i,"compliance"),this.minCutMixin.shouldPauseOperations())return te.warn("Compliance validation paused: topology is in critical state"),this.failWorkflow(i,"Topology is in critical state"),p(new Error("Compliance validation paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&te.warn("Topology degraded, proceeding with compliance validation");let s=(await this.complianceValidator.getAvailableStandards()).find(o=>o.id===e);if(!s)return p(new Error(`Unknown compliance standard: ${e}`));let a=await this.complianceValidator.validate(s,r);return a.success?(this.completeWorkflow(i),this.config.publishEvents&&await this.publishComplianceValidationCompleted(a.value)):this.failWorkflow(i,a.error.message),a}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async assessSecurityPosture(){let e=v();try{if(this.startWorkflow(e,"posture"),this.minCutMixin.shouldPauseOperations())return te.warn("Security posture assessment paused: topology is in critical state"),this.failWorkflow(e,"Topology is in critical state"),p(new Error("Security posture assessment paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&te.warn("Topology degraded, proceeding with security posture assessment");let r=await this.securityAuditor.getSecurityPosture();if(r.success){this.completeWorkflow(e);let i={overallScore:r.value.overallScore,trend:r.value.trend,criticalVulnerabilities:r.value.criticalIssues,complianceStatus:new Map,lastAuditDate:r.value.lastAuditDate};return f(i)}else return this.failWorkflow(e,r.error.message),r}catch(r){let i=y(r);return this.failWorkflow(e,i.message),{success:!1,error:i}}}async runComplianceCheck(e){let r={projectRoot:he.create("."),includePatterns:["**/*.ts","**/*.js"],excludePatterns:["node_modules/**"]};return this.runComplianceValidation(e,r)}async getSecurityPosture(){return this.assessSecurityPosture()}async prioritizeSecurityTests(e,r){if(!this.dqnAlgorithm||!this.rlInitialized)return r;try{let i=await Promise.all(r.map(async n=>{let s={id:`test-${n}`,features:this.extractSecurityTestFeatures(e,n)},a=await this.dqnAlgorithm.predict(s);return{test:n,score:a.value||0}}));return i.sort((n,s)=>s.score-n.score),i.map(n=>n.test)}catch(i){return te.error("Failed to prioritize security tests:",i instanceof Error?i:void 0),r}}async trainDQNWithAuditFeedback(e,r){if(!(!this.dqnAlgorithm||!this.rlInitialized))try{let i=this.extractVulnerabilitiesFromReport(r),n={id:`audit-${r.auditId}-${Date.now()}`,features:this.extractAuditFeatures(e)},s={type:"run-audit",value:i.length},a=this.calculateAuditReward(r),o={state:n,action:s,reward:a,nextState:n,done:!0,timestamp:new Date};await this.dqnAlgorithm.train(o),te.info(`Trained security audit with reward: ${a.toFixed(3)}`)}catch(i){te.error("Failed to train DQN:",i instanceof Error?i:void 0)}}calculateAuditReward(e){let r=this.extractVulnerabilitiesFromReport(e);if(r.length===0)return .5;let i=.5,n=r.filter(a=>a.severity==="critical").length;i+=Math.min(.3,n*.1);let s=r.filter(a=>a.severity==="high").length;return i+=Math.min(.2,s*.05),i+=(e.overallRiskScore?.value??0)*.1,Math.max(0,Math.min(1,i))}extractSecurityTestFeatures(e,r){let i=e.targetUrl??"";return[i.includes("/api")?1:0,i.startsWith("http")?1:0,e.includeSAST?1:0,r.includes("auth")?1:0,r.includes("sql")?1:0,r.includes("xss")?1:0,r.includes("injection")?1:0,r.length/100]}extractAuditFeatures(e){let r=e.depth??"standard",i=r==="deep"?1:r==="standard"?.5:.25;return[e.includeSAST?1:0,e.includeDAST?1:0,i,(e.scanTypes?.length??0)/4,e.includeDependencies?1:0,e.includeSecrets?1:0,(e.complianceFrameworks?.length??0)/5,e.targetUrl?1:0]}async enhanceVulnerabilityAnalysis(e){if(!(!this.flashAttention||!this.rlInitialized||e.length===0))try{let r=e.map(l=>this.createVulnerabilityEmbedding(l)),i=r.length,n=r[0].length,s=new Float32Array(i*n),a=new Float32Array(i*n),o=new Float32Array(i*n);for(let l=0;l<i;l++)s.set(r[l],l*n),a.set(r[l],l*n),o.set(r[l],l*n);let c=await this.flashAttention.computeFlashAttention(s,a,o,i,n);for(let l=0;l<e.length;l++){let d=Array.from(c.slice(l*n,(l+1)*n));r[l].reduce((g,h,b)=>g+h*d[b],0)>.7&&te.info(`High self-attention for vulnerability ${e[l].id}`)}}catch(r){te.error("Failed to enhance vulnerability analysis:",r instanceof Error?r:void 0)}}createVulnerabilityEmbedding(e){let r=[],i=this.hashCode(e.category);r.push(i%1e3/1e3);let n={critical:1,high:.75,medium:.5,low:.25,informational:.1};r.push(n[e.severity]||.5);let s=this.hashCode(e.title);r.push(s%1e3/1e3),r.push(Math.min(1,e.description.length/500));let a=e.cveId?this.hashCode(e.cveId):0;r.push(a%1e3/1e3);let o=this.hashCode(e.description.slice(0,200));for(let c=r.length;c<384;c++)r.push(o*(c+1)%1e4/1e4);return r.slice(0,384)}hashCode(e){let r=0;for(let i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r=r|0;return Math.abs(r)}async spawnSecurityAuditAgent(e,r){let i={name:`security-auditor-${e.slice(0,8)}`,domain:"security-compliance",type:"auditor",capabilities:["security-audit","vulnerability-scanning","compliance-check"],config:{workflowId:e,targetUrl:r.targetUrl,depth:r.depth}};return this.agentCoordinator.spawn(i)}extractVulnerabilitiesFromReport(e){let r=[];return e.sastResults?.vulnerabilities&&r.push(...e.sastResults.vulnerabilities),e.dastResults?.vulnerabilities&&r.push(...e.dastResults.vulnerabilities),e.dependencyResults?.vulnerabilities&&r.push(...e.dependencyResults.vulnerabilities),r}async publishSecurityAuditCompleted(e){let r=this.extractVulnerabilitiesFromReport(e),i=await this.verifyHighSeverityFindings(r);for(let n of i){let s={vulnId:n.id,cve:n.cveId,severity:n.severity,file:n.location.file,line:n.location.line,description:n.description,remediation:n.remediation.description},a=D(Ma.SecurityAuditCompleted,"security-compliance",s);await this.eventBus.publish(a)}}async verifyHighSeverityFindings(e){if(!this.config.enableConsensus)return e;if(!this.isConsensusAvailable())return this.consensusEngine?this.verifyHighSeverityFindingsLegacy(e):e;let r=[],i=e.filter(a=>a.severity==="critical"||a.severity==="high"),n=e.filter(a=>a.severity!=="critical"&&a.severity!=="high");r.push(...n);for(let a of i)try{let o=V({id:a.id,type:"security-vulnerability",confidence:.8,description:`${a.title}: ${a.description}`,payload:{vulnerability:a,location:a.location},detectedBy:"security-scanner",severity:a.severity,context:{domain:this.domainName,cveId:a.cveId,category:a.category}});if(!this.consensusMixin.requiresConsensus(o)){r.push(a);continue}let c=await this.consensusMixin.verifyFinding(o);c.success&&c.value.verdict==="verified"?(te.info(`Consensus VERIFIED: ${a.title} (confidence: ${(c.value.confidence*100).toFixed(1)}%)`),r.push(a)):c.success&&c.value.verdict==="disputed"?(te.info(`Consensus DISPUTED: ${a.title} - including with lower confidence`),r.push(a)):te.info(`Consensus REJECTED: ${a.title} - likely false positive`)}catch{te.warn(`Consensus error verifying ${a.title}, including by default:`),r.push(a)}let s=i.length-r.filter(a=>a.severity==="critical"||a.severity==="high").length;return s>0&&te.info(`Consensus filtered out ${s} likely false positive(s)`),r}async verifyHighSeverityFindingsLegacy(e){if(!this.consensusEngine)return e;let r=[],i=e.filter(s=>s.severity==="critical"||s.severity==="high"),n=e.filter(s=>s.severity!=="critical"&&s.severity!=="high");r.push(...n);for(let s of i)try{let a={id:s.id,type:s.category,description:s.description,category:s.category,severity:s.severity,location:{file:s.location.file,line:s.location.line,column:s.location.column},evidence:[{type:"code-snippet",content:s.location.snippet||s.description}],cveId:s.cveId,remediation:s.remediation.description,detectedAt:new Date,detectedBy:"security-scanner"},o=await this.consensusEngine.verify(a);(o.success&&o.value.verdict==="verified"||o.success&&o.value.verdict==="disputed")&&r.push(s)}catch{r.push(s)}return r}async publishComplianceValidationCompleted(e){let r={standard:e.standardId,passed:e.complianceScore>=.8,violations:e.violations.length,findings:e.violations.map(n=>n.details).slice(0,10)},i=D(Ma.ComplianceValidated,"security-compliance",r);await this.eventBus.publish(i)}detectAuthCodeInScope(e){let r=[/auth/i,/login/i,/password/i,/token/i,/session/i,/oauth/i,/jwt/i,/credential/i,/identity/i];if(e.targetUrl){for(let i of r)if(i.test(e.targetUrl))return!0}if(e.scanTypes){let i=["authentication","authorization","session-management"];for(let n of e.scanTypes)if(i.includes(n.toLowerCase()))return!0}if(e.complianceFrameworks){let i=["soc2","pci-dss","hipaa","iso27001"];for(let n of e.complianceFrameworks)if(i.includes(n.toLowerCase()))return!0}return!1}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}async handleTestRunCompleted(e){}async handleImpactAnalysis(e){}async loadWorkflowState(){let e=await this.memory.get("security-compliance:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("security-compliance:coordinator:workflows",e,{namespace:"security-compliance",persist:!0})}getHealthyRoutingDomains(){return this.minCutMixin.getHealthyRoutingDomains()}};A();var da=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;securityScanner=null;securityAuditor=null;complianceValidator=null;pluginConfig;get name(){return"security-compliance"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runSecurityAudit:this.runSecurityAudit.bind(this),getSecurityPosture:this.getSecurityPosture.bind(this),runSASTScan:this.runSASTScan.bind(this),runDASTScan:this.runDASTScan.bind(this),triageVulnerabilities:this.triageVulnerabilities.bind(this),runComplianceCheck:this.runComplianceCheck.bind(this),getAvailableStandards:this.getAvailableStandards.bind(this),analyzeComplianceGaps:this.analyzeComplianceGaps.bind(this),getCoordinator:()=>this.coordinator,getSecurityScanner:()=>this.securityScanner,getSecurityAuditor:()=>this.securityAuditor,getComplianceValidator:()=>this.complianceValidator}}getTaskHandlers(){return new Map([["security-audit",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.target??e.targetUrl;return r?this.coordinator.runSecurityAudit({includeSAST:e.includeSAST??!0,includeDAST:e.includeDAST??!1,includeDependencies:e.includeDependencies??!0,includeSecrets:e.includeSecrets??!0,targetUrl:r}):p(new Error("Invalid security-audit payload: missing target"))}],["compliance-check",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.standardId;return r?this.coordinator.runComplianceCheck(r):p(new Error("Invalid compliance-check payload: missing standardId"))}],["sast-scan",async e=>{if(!this.securityScanner)return p(new Error("Security scanner not initialized"));let r=e.files;return!r||r.length===0?p(new Error("Invalid sast-scan payload: missing files")):this.securityScanner.scanFiles(r)}],["dast-scan",async e=>{if(!this.securityScanner)return p(new Error("Security scanner not initialized"));let r=e.targetUrl;return r?this.securityScanner.scanUrl(r):p(new Error("Invalid dast-scan payload: missing targetUrl"))}],["triage-vulnerabilities",async e=>{if(!this.securityAuditor)return p(new Error("Security auditor not initialized"));let r=e.vulnerabilities;return!r||r.length===0?p(new Error("Invalid triage-vulnerabilities payload: missing vulnerabilities")):this.securityAuditor.triageVulnerabilities(r)}]])}async onInitialize(){this.securityScanner=new $e(this.memory,this.pluginConfig.securityScanner),this.securityAuditor=new Bt(this.memory,this.pluginConfig.securityAuditor),this.complianceValidator=new qt(this.memory,this.pluginConfig.complianceValidator),this.coordinator=new ji(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.securityScanner=null,this.securityAuditor=null,this.complianceValidator=null}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.KnowledgeGraphUpdated",this.handleKnowledgeGraphUpdate.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"code-intelligence.KnowledgeGraphUpdated":await this.handleKnowledgeGraphUpdate(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;default:break}}async runSecurityAudit(e){this.ensureInitialized();try{let r=await this.coordinator.runSecurityAudit(e);return r.success?this.trackSuccessfulOperation("audit"):this.trackFailedOperation("audit",r.error),r}catch(r){return this.handleError(r)}}async getSecurityPosture(){this.ensureInitialized();try{return await this.coordinator.getSecurityPosture()}catch(e){return this.handleError(e)}}async runSASTScan(e){this.ensureInitialized();try{let r=await this.securityScanner.scanFiles(e);return r.success?this.trackSuccessfulOperation("sast-scan"):this.trackFailedOperation("sast-scan",r.error),r}catch(r){return this.handleError(r)}}async runDASTScan(e){this.ensureInitialized();try{let r=await this.securityScanner.scanUrl(e);return r.success?this.trackSuccessfulOperation("dast-scan"):this.trackFailedOperation("dast-scan",r.error),r}catch(r){return this.handleError(r)}}async triageVulnerabilities(e){this.ensureInitialized();try{let r=await this.securityAuditor.triageVulnerabilities(e);return r.success?{success:!0,value:{immediate:r.value.immediate,shortTerm:r.value.shortTerm}}:{success:!1,error:r.error}}catch(r){return this.handleError(r)}}async runComplianceCheck(e){this.ensureInitialized();try{let r=await this.coordinator.runComplianceCheck(e);return r.success?this.trackSuccessfulOperation("compliance-check"):this.trackFailedOperation("compliance-check",r.error),r}catch(r){return this.handleError(r)}}async getAvailableStandards(){return this.ensureInitialized(),this.complianceValidator.getAvailableStandards()}async analyzeComplianceGaps(e,r){this.ensureInitialized();try{return await this.complianceValidator.analyzeGaps(e,r)}catch(i){return this.handleError(i)}}async handleKnowledgeGraphUpdate(e){let r=e.payload;await this.memory.set(`security:code-update:${Date.now()}`,{filesIndexed:r.filesIndexed,timestamp:new Date},{namespace:"security-compliance",ttl:3600})}async handleQualityGateEvaluated(e){let r=e.payload,i=r.checks.filter(n=>n.name.toLowerCase().includes("security"));i.length>0&&await this.memory.set(`security:gate-results:${r.gateId}`,{securityChecks:i,passed:r.passed},{namespace:"security-compliance",persist:!0})}async handleTestRunCompleted(e){}ensureInitialized(){if(!this._initialized)throw new Error("SecurityCompliancePlugin is not initialized");if(!this.coordinator||!this.securityScanner||!this.securityAuditor||!this.complianceValidator)throw new Error("SecurityCompliancePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date}),this.memory.set(`security:operation:${e}:${Date.now()}`,{operation:e,success:!0,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]}),this.memory.set(`security:operation:${e}:${Date.now()}`,{operation:e,success:!1,error:r.message,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}};function Uc(u,t,e,r){return new da(u,t,e,r)}M();A();M();A();H();var Ny={strictMode:!0,validateExamples:!0,maxSchemaDepth:Nn.MAX_SCHEMA_DEPTH,cacheValidations:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:Vn.MAX_TOKENS},Vy=R.create("contract-testing/contract-validator"),Tr=class{config;memory;llmRouter;validationCache=new Map;MAX_CACHED_VALIDATIONS=Nn.MAX_CACHED_VALIDATIONS;CACHE_TTL_MS=Nn.CACHE_TTL_MS;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...Ny,...e}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}async analyzeContractWithLLM(t){if(!this.isLLMAnalysisAvailable())return null;try{let e=t.consumers.map(i=>i.name).join(", ");return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this API contract for potential issues:
2924
+ `);for(let s of n){let a=s.trim();if(!a||a.startsWith("#"))continue;let o=a.match(/^([a-zA-Z0-9_-]+)(?:[=<>~!]+(.+))?$/);o&&r.push({name:o[1],version:o[2]||"latest",ecosystem:"pip"})}}}catch(i){Ze.error(`Failed to parse dependencies from ${t}:`,i instanceof Error?i:void 0)}return r}cleanVersionSpec(t){return t.replace(/^[\^~>=<]+/,"").trim()}async checkDependencyVulnerabilities(t,e){let r=[];try{let i=this.mapToOSVEcosystem(e),n={package:{name:t.name,ecosystem:i},version:t.version},s=await qc("https://api.osv.dev/v1/query",n);if(s.ok&&s.data.vulns&&s.data.vulns.length>0)for(let a of s.data.vulns){let o=this.mapOSVVulnerability(a,t);r.push(o)}}catch(i){Ze.error(`Failed to check vulnerabilities for ${t.name}@${t.version}:`,i instanceof Error?i:void 0)}return r}mapToOSVEcosystem(t){return{npm:"npm",pip:"PyPI",maven:"Maven",nuget:"NuGet",cargo:"crates.io"}[t]}mapOSVVulnerability(t,e){let r=t.aliases?.find(c=>c.startsWith("CVE-")),i=this.mapOSVSeverity(t.severity),n=this.extractFixedVersion(t),s=t.references?.map(c=>c.url)||[],a={file:"package.json",dependency:e},o={description:n?`Upgrade ${e.name} to version ${n} or higher`:`Review and address vulnerability in ${e.name}`,fixExample:n?`"${e.name}": "^${n}"`:void 0,estimatedEffort:n?"trivial":"moderate",automatable:!!n};return{id:v(),cveId:r,title:t.summary||`Vulnerability in ${e.name}`,description:t.details||t.summary||"No description available",severity:i,category:this.categorizeVulnerability(t),location:a,remediation:o,references:s}}mapOSVSeverity(t){if(!t||t.length===0)return"medium";let e=t.find(r=>r.type==="CVSS_V3"||r.type==="CVSS_V2");if(e){let r=parseFloat(e.score);if(r>=9)return"critical";if(r>=7)return"high";if(r>=4)return"medium";if(r>0)return"low"}return"medium"}extractFixedVersion(t){if(t.affected){for(let e of t.affected)if(e.ranges){for(let r of e.ranges)if(r.events){let i=r.events.find(n=>n.fixed);if(i?.fixed)return i.fixed}}}}categorizeVulnerability(t){let e=(t.summary||"").toLowerCase(),r=(t.details||"").toLowerCase(),i=`${e} ${r}`;return i.includes("injection")||i.includes("sql")?"injection":i.includes("xss")||i.includes("cross-site scripting")?"xss":i.includes("authentication")||i.includes("auth bypass")?"broken-auth":i.includes("sensitive data")||i.includes("exposure")?"sensitive-data":i.includes("xxe")||i.includes("xml external")?"xxe":i.includes("access control")||i.includes("authorization")?"access-control":i.includes("deseriali")?"insecure-deserialization":(i.includes("prototype pollution")||i.includes("dependency"),"vulnerable-components")}async checkOutdated(t){let e=await this.getLatestVersion(t.name,t.ecosystem);return e!==t.version?{name:t.name,currentVersion:t.version,latestVersion:e,updateType:this.determineUpdateType(t.version,e)}:null}async queryVulnerabilityDatabase(t,e,r){let i={name:t,version:e,ecosystem:r};return this.checkDependencyVulnerabilities(i,r)}async getLatestVersion(t,e){try{if(e==="npm"){let r=await Gi(`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`);if(r.ok&&r.data.version)return r.data.version}else if(e==="pip"){let r=await Gi(`https://pypi.org/pypi/${encodeURIComponent(t)}/json`);if(r.ok&&r.data.info?.version)return r.data.info.version}}catch(r){Ze.error(`Failed to get latest version for ${t}:`,r instanceof Error?r:void 0)}return"unknown"}async checkDeprecation(t,e){try{if(e==="npm"){let r=await Gi(`https://registry.npmjs.org/${encodeURIComponent(t)}/latest`);if(r.ok&&r.data.deprecated)return!0}}catch(r){Ze.error(`Failed to check deprecation for ${t}:`,r instanceof Error?r:void 0)}return!1}determineUpdateType(t,e){let r=t.split(".").map(Number),i=e.split(".").map(Number);return i[0]>r[0]?"major":i[1]>r[1]?"minor":"patch"}hasBreakingChanges(t,e){let r=parseInt(t.split(".")[0]);return parseInt(e.split(".")[0])>r}createDependencySummary(t,e){let r=0,i=0,n=0,s=0,a=0;for(let o of t)switch(o.severity){case"critical":r++;break;case"high":i++;break;case"medium":n++;break;case"low":s++;break;case"informational":a++;break}return{critical:r,high:i,medium:n,low:s,informational:a,totalFiles:e,scanDurationMs:0}}shouldExclude(t){return this.config.excludePatterns.some(e=>e.startsWith("*")?t.endsWith(e.slice(1)):t.includes(e))}async performDependencyScan(){let t=Date.now(),e=[],r=[];try{let i=Wi.join(process.cwd(),"package.json"),n=await this.parseDependencies(i,"npm");for(let o of n){let c=await this.checkDependencyVulnerabilities(o,o.ecosystem);e.push(...c);let l=await this.checkOutdated(o);l&&r.push(l)}let s=Date.now()-t,a=this.createDependencySummary(e,n.length);return{vulnerabilities:e,outdatedPackages:r,summary:{...a,scanDurationMs:s}}}catch(i){return Ze.error("Dependency scan failed:",i instanceof Error?i:void 0),{vulnerabilities:[],outdatedPackages:[],summary:{critical:0,high:0,medium:0,low:0,informational:0,totalFiles:0,scanDurationMs:Date.now()-t}}}}async performSecretScan(){let t=[],e=0;try{let r=await this.findSourceFiles(process.cwd());for(let i of r){if(this.shouldExclude(i))continue;e++;let s=await Hc({value:i});t.push(...s)}}catch(r){Ze.error("Secret scan failed:",r instanceof Error?r:void 0)}return{secretsFound:t,filesScanned:e}}async findSourceFiles(t,e=[]){let r=[".ts",".js",".tsx",".jsx",".json",".env",".yaml",".yml",".config"];try{let i=await Hi.readdir(t,{withFileTypes:!0});for(let n of i){let s=Wi.join(t,n.name);if(!this.shouldExclude(s)){if(n.isDirectory())await this.findSourceFiles(s,e);else if(n.isFile()){let a=Wi.extname(n.name).toLowerCase();(r.includes(a)||n.name.startsWith(".env"))&&e.push(s)}}}}catch{Ze.debug("Directory read error:")}return e}async getRecentAudits(){let t=await this.memory.search("security:audit:*",10),e=[];for(let r of t){let i=await this.memory.get(r);i&&e.push(i)}return e.sort((r,i)=>new Date(i.timestamp).getTime()-new Date(r.timestamp).getTime())}async countResolvedLastWeek(){try{let t=await this.getRecentAudits();if(t.length<2)return 0;let e=new Date(Date.now()-10080*60*1e3),r=t.filter(o=>new Date(o.timestamp)>=e);if(r.length<2)return 0;let i=r[r.length-1],n=r[0],s=Rr(i),a=Rr(n);return Math.max(0,s-a)}catch(t){return Ze.error("Failed to count resolved vulnerabilities:",t instanceof Error?t:void 0),0}}async calculateAverageResolutionTime(){try{let t=await this.getRecentAudits();if(t.length<2)return 72;let e=new Map,r=[],i=[...t].reverse();for(let s of i){let a=new Set;s.sastResults&&s.sastResults.vulnerabilities.forEach(o=>a.add(o.id)),s.dastResults&&s.dastResults.vulnerabilities.forEach(o=>a.add(o.id)),s.dependencyResults&&s.dependencyResults.vulnerabilities.forEach(o=>a.add(o.id));for(let o of a)e.has(o)||e.set(o,s.timestamp);for(let[o,c]of e)if(!a.has(o)){let l=(s.timestamp.getTime()-c.getTime())/36e5;r.push(l),e.delete(o)}}if(r.length===0)return 72;let n=r.reduce((s,a)=>s+a,0);return Math.round(n/r.length)}catch(t){return Ze.error("Failed to calculate average resolution time:",t instanceof Error?t:void 0),72}}};A();var ky={customStandards:[],strictMode:!1,includeRecommended:!0,evidenceRetentionDays:365},Iy={id:"gdpr",name:"General Data Protection Regulation",version:"2018",rules:[{id:"gdpr-art5-accuracy",title:"Data Accuracy",description:"Personal data must be accurate and kept up to date",category:"data-quality",severity:"required",checkType:"manual"},{id:"gdpr-art17-erasure",title:"Right to Erasure",description:"Data subjects have the right to request deletion of their data",category:"data-rights",severity:"required",checkType:"static"},{id:"gdpr-art25-privacy-design",title:"Privacy by Design",description:"Data protection must be built into systems from the start",category:"architecture",severity:"required",checkType:"static"},{id:"gdpr-art32-security",title:"Security of Processing",description:"Appropriate security measures must protect personal data",category:"security",severity:"required",checkType:"static"},{id:"gdpr-art33-breach-notification",title:"Breach Notification",description:"Data breaches must be reported within 72 hours",category:"incident-response",severity:"required",checkType:"manual"}]},Dy={id:"hipaa",name:"Health Insurance Portability and Accountability Act",version:"1996-amended",rules:[{id:"hipaa-164.312-access",title:"Access Control",description:"Implement technical policies for ePHI access",category:"access-control",severity:"required",checkType:"static"},{id:"hipaa-164.312-audit",title:"Audit Controls",description:"Implement hardware, software, and procedural audit mechanisms",category:"audit",severity:"required",checkType:"static"},{id:"hipaa-164.312-integrity",title:"Integrity Controls",description:"Protect ePHI from improper alteration or destruction",category:"data-integrity",severity:"required",checkType:"static"},{id:"hipaa-164.312-transmission",title:"Transmission Security",description:"Protect ePHI during electronic transmission",category:"encryption",severity:"required",checkType:"static"},{id:"hipaa-164.314-baa",title:"Business Associate Agreements",description:"Ensure contracts with business associates protect PHI",category:"contracts",severity:"required",checkType:"manual"}]},My={id:"soc2",name:"SOC 2 Type II",version:"2017",rules:[{id:"soc2-cc6.1",title:"Logical Access Security",description:"Security software, infrastructure, and architectures are implemented",category:"security",severity:"required",checkType:"static"},{id:"soc2-cc6.2",title:"Access Controls",description:"Registration and authorization of new users",category:"access-control",severity:"required",checkType:"static"},{id:"soc2-cc6.6",title:"Encryption",description:"Logical access security measures to protect data",category:"encryption",severity:"required",checkType:"static"},{id:"soc2-cc7.1",title:"System Monitoring",description:"Detect and respond to security incidents",category:"monitoring",severity:"required",checkType:"static"},{id:"soc2-cc8.1",title:"Change Management",description:"Changes to infrastructure are authorized and tested",category:"change-management",severity:"required",checkType:"manual"}]},Fy={id:"pci-dss",name:"Payment Card Industry Data Security Standard",version:"4.0",rules:[{id:"pci-req1",title:"Network Security Controls",description:"Install and maintain network security controls",category:"network-security",severity:"required",checkType:"static"},{id:"pci-req3",title:"Protect Account Data",description:"Protect stored account data",category:"data-protection",severity:"required",checkType:"static"},{id:"pci-req4",title:"Encrypt Transmissions",description:"Protect cardholder data with strong cryptography during transmission",category:"encryption",severity:"required",checkType:"static"},{id:"pci-req6",title:"Secure Development",description:"Develop and maintain secure systems and software",category:"secure-sdlc",severity:"required",checkType:"static"},{id:"pci-req10",title:"Log and Monitor Access",description:"Log and monitor all access to system components",category:"logging",severity:"required",checkType:"static"}]},Ly=[Iy,Dy,My,Fy],qt=class{constructor(t,e={}){this.memory=t;this.config={...ky,...e},this.patternAnalyzer=Bc(),this.standards=new Map;for(let r of Ly)this.standards.set(r.id,r);for(let r of this.config.customStandards)this.standards.set(r.id,r)}memory;config;standards;patternAnalyzer;async validate(t,e){try{let r=[],i=[],n=[],s=this.config.includeRecommended?t.rules:t.rules.filter(l=>l.severity==="required");for(let l of s){if(l.checkType==="manual"){n.push(l.id);continue}let d=await this.checkRule(l,e);d.passed?i.push(l.id):r.push(...d.violations)}let a=s.length-n.length,o=a>0?Math.round(i.length/a*100):100,c={standardId:t.id,standardName:t.name,violations:r,passedRules:i,skippedRules:n,complianceScore:o,generatedAt:new Date};return await this.storeReport(c),f(c)}catch(r){return p(y(r))}}async getAvailableStandards(){return Array.from(this.standards.values())}async analyzeGaps(t,e){try{let r=[],i=[],n=new Set(t.violations.map(l=>l.ruleId)),s=new Set(t.passedRules);for(let l of e.rules)n.has(l.id)?r.push({ruleId:l.id,currentStatus:"failed",effort:this.estimateEffort(l),impact:l.severity==="required"?"high":"medium"}):s.has(l.id)||r.push({ruleId:l.id,currentStatus:"not-implemented",effort:this.estimateEffort(l),impact:l.severity==="required"?"high":"low"});let a=[...r].sort((l,d)=>{let m={high:0,medium:1,low:2},g={trivial:0,minor:1,moderate:2,major:3},h=m[l.impact]*10+g[l.effort],b=m[d.impact]*10+g[d.effort];return h-b});for(let l=0;l<a.length;l++){let d=a[l],m=e.rules.find(g=>g.id===d.ruleId);i.push({id:v(),description:`Implement ${m?.title||d.ruleId}`,affectedRules:[d.ruleId],effort:d.effort,priority:l+1})}let o=100,c=t.complianceScore;return f({currentScore:c,targetScore:o,gaps:r,prioritizedActions:i})}catch(r){return p(y(r))}}async validateMultiple(t,e){try{let r=[],i=[];for(let a of t){let o=await this.validate(a,e);o.success&&r.push(o.value)}let n=new Map;for(let a of r)for(let o of a.violations){let c=`${o.location.file}:${o.location.line}`;n.set(c,(n.get(c)||0)+1)}for(let a of r)for(let o of a.violations){let c=`${o.location.file}:${o.location.line}`;(n.get(c)||0)>1&&(i.some(l=>l.location.file===o.location.file&&l.location.line===o.location.line)||i.push(o))}let s=r.length>0?Math.round(r.reduce((a,o)=>a+o.complianceScore,0)/r.length):0;return f({reports:r,overallScore:s,crossCuttingViolations:i})}catch(r){return p(y(r))}}async checkDataHandling(t,e){try{let r=new Map,i=[],n=[];for(let s of e)r.set(s,[]);for(let s of t){let a=await this.scanFileForDataTypes(s,e);for(let o of a){let c=r.get(o.type)||[];c.push(o.location),r.set(o.type,c);let l=this.checkDataTypeViolation(o);l&&i.push(l)}}for(let[s,a]of r)a.length>0&&n.push(...this.getDataTypeRecommendations(s,a.length));return f({dataTypesFound:r,violations:i,recommendations:[...new Set(n)]})}catch(r){return p(y(r))}}async generateEvidence(t,e){try{let r=this.standards.get(t);if(!r)return p(new Error(`Unknown standard: ${t}`));let i=await this.validate(r,e);if(!i.success)return p(i.error);let n=i.value,s=[];for(let o of r.rules){let c=n.passedRules.includes(o.id)?"implemented":n.skippedRules.includes(o.id)?"partial":"not-implemented";s.push({controlId:o.id,status:c,evidence:await this.collectEvidence(o,e),lastVerified:new Date})}let a={standardId:t,controls:s,generatedAt:new Date,validUntil:new Date(Date.now()+this.config.evidenceRetentionDays*24*60*60*1e3)};return await this.memory.set(`compliance:evidence:${t}:${Date.now()}`,a,{namespace:"security-compliance",persist:!0}),f(a)}catch(r){return p(y(r))}}async checkRule(t,e){let r=[],i=await this.getFilesFromContext(e);switch(t.category){case"encryption":r.push(...await this.checkEncryption(t,e,i));break;case"access-control":r.push(...await this.checkAccessControl(t,e,i));break;case"audit":case"logging":r.push(...await this.checkLogging(t,e,i));break;case"data-protection":case"data-quality":r.push(...await this.checkDataProtection(t,e,i));break;case"security":r.push(...await this.checkSecurityControls(t,e,i));break;default:break}return{passed:r.length===0,violations:r}}async getFilesFromContext(t){let e=[],r=t.projectRoot.value;if(t.includePatterns.length===0)return[];for(let i of t.includePatterns)t.excludePatterns.some(s=>i.includes(s)||s.includes(i))||e.push(`${r}/${i}`);return e}async checkEncryption(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeEncryption(r);for(let s of n.weakCrypto)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Weak or deprecated cryptographic algorithm detected",remediation:"Use strong encryption algorithms (AES-256, SHA-256 or higher)"});for(let s of n.unencryptedDataHandling)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive data handled without encryption verification",remediation:"Ensure data is encrypted before processing sensitive information"});return i}async checkAccessControl(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeAccessControl(r);for(let s of n.unprotectedRoutes)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive endpoint potentially missing authorization middleware",remediation:"Add authorization check before sensitive operations"});for(let s of n.hardcodedCredentials)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Hardcoded credentials detected",remediation:"Use environment variables or secure secret management"});return i}async checkLogging(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeLogging(r);for(let s of n.sensitiveOperationsWithoutLogging)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive operation without audit logging",remediation:"Add audit log entry for data modification operations"});for(let s of n.sensitiveDataInLogs)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Sensitive data being logged",remediation:"Remove or mask sensitive data before logging"});return i}async checkDataProtection(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeDataProtection(r);for(let s of n.unmaskedPii)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"PII field without masking or encryption decorator",remediation:"Apply data protection decorators to sensitive fields"});for(let s of n.missingValidation)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Data fields without input validation",remediation:"Add input validation for all data fields, especially PII"});return i}async checkSecurityControls(t,e,r){let i=[];if(r.length===0)return i;let n=await this.patternAnalyzer.analyzeSecurityControls(r);for(let s of n.missingControls)i.push({ruleId:t.id,ruleName:t.title,location:{file:"project-wide",line:0,snippet:`Missing: ${s}`},details:`Security control not detected: ${s}`,remediation:`Implement ${s} to enhance security posture`});for(let s of n.vulnerabilities)i.push({ruleId:t.id,ruleName:t.title,location:{file:s.file,line:s.line,snippet:s.snippet},details:"Security vulnerability detected",remediation:"Review and fix the security issue"});return i}estimateEffort(t){let e=["architecture","data-rights","incident-response"],r=["access-control","encryption","change-management"];return e.includes(t.category)?"major":r.includes(t.category)||t.checkType==="manual"?"moderate":"minor"}async scanFileForDataTypes(t,e){let r=[],i=await this.patternAnalyzer.scanForDataTypes([t.value],e);for(let n of e){let s=i.get(n)||[];for(let a of s)r.push({type:n,location:{file:a.file,line:a.line,context:a.snippet||this.getDataTypeContext(n)}})}return r}getDataTypeContext(t){return{pii:"User personal information field",phi:"Health-related data field",financial:"Payment/financial data field",credentials:"Authentication credential field",biometric:"Biometric data field"}[t]}checkDataTypeViolation(t){let e=t.location.context.toLowerCase(),i=[/encrypt/i,/hash/i,/mask/i,/redact/i,/validate/i,/sanitize/i,/bcrypt/i,/argon2/i,/aes/i].some(a=>a.test(e)),s=[/console\.(log|debug|info)/i,/JSON\.stringify/i,/\.toString\(\)/i,/plaintext/i,/unencrypted/i].some(a=>a.test(e));if(!i||s){let a={pii:"gdpr-art32-security",phi:"hipaa-164.312-transmission",financial:"pci-req3",credentials:"soc2-cc6.6",biometric:"gdpr-art9-special"},o={file:t.location.file,line:t.location.line,snippet:t.location.context},c=s?"Potentially exposed in logs or serialization":"No protective measures detected";return{ruleId:a[t.type],ruleName:`${t.type.toUpperCase()} Data Protection`,location:o,details:`${t.type.toUpperCase()} data found: ${c}`,remediation:`Apply appropriate security controls for ${t.type} data`}}return null}getDataTypeRecommendations(t,e){let r=`Found ${e} ${t.toUpperCase()} data locations`;return{pii:[r,"Implement data minimization principles","Ensure consent mechanisms are in place","Add data retention policies"],phi:[r,"Verify HIPAA safeguards are implemented","Ensure business associate agreements are in place","Implement minimum necessary access"],financial:[r,"Verify PCI-DSS compliance for payment data","Implement tokenization where possible","Ensure proper key management"],credentials:[r,"Use secure credential storage (vaults)","Implement credential rotation","Avoid hardcoded credentials"],biometric:[r,"Implement enhanced protection measures","Obtain explicit consent","Consider data localization requirements"]}[t]}async collectEvidence(t,e){let r=[],i=await this.getFilesFromContext(e);if(t.checkType==="static"&&i.length>0){switch(t.category){case"encryption":{let n=await this.patternAnalyzer.analyzeEncryption(i);n.hasEncryption&&r.push(`Encryption detected: ${n.encryptionLibraries.join(", ")||"standard crypto"}`),n.weakCrypto.length>0&&r.push(`Weak crypto found in ${n.weakCrypto.length} location(s)`),r.push(`Unencrypted data handling: ${n.unencryptedDataHandling.length} instance(s)`);break}case"access_control":{let n=await this.patternAnalyzer.analyzeAccessControl(i);r.push(`Auth middleware: ${n.hasAuthMiddleware?"present":"not found"}`),r.push(`Unprotected routes: ${n.unprotectedRoutes.length}`),r.push(`Hardcoded credentials: ${n.hardcodedCredentials.length}`);break}case"logging":{let n=await this.patternAnalyzer.analyzeLogging(i);r.push(`Audit logging: ${n.hasAuditLogging?"implemented":"not found"}`),r.push(`Sensitive data in logs: ${n.sensitiveDataInLogs.length} instance(s)`);break}case"data_protection":{let n=await this.patternAnalyzer.analyzeDataProtection(i);r.push(`PII fields detected: ${n.piiFields.length}`),r.push(`Unmasked PII: ${n.unmaskedPii.length} instance(s)`),r.push(`Missing validation: ${n.missingValidation.length} field(s)`);break}default:r.push(`Static analysis completed for ${t.category}`),r.push(`Code patterns reviewed: ${t.title}`)}r.push(`Files analyzed: ${i.length}`)}else t.checkType==="dynamic"?(r.push(`Dynamic check required for: ${t.title}`),r.push("Evidence collection pending dynamic analysis")):t.checkType==="manual"&&(r.push(`Manual verification required for: ${t.title}`),r.push(`Review scope: ${e.projectRoot.value}`));return r.push(`Rule ${t.id} verified at ${new Date().toISOString()}`),r}async storeReport(t){await this.memory.set(`compliance:report:${t.standardId}:${Date.now()}`,t,{namespace:"security-compliance",persist:!0})}};var $y={stateSize:10,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0},ua=class extends ae{qNetwork;targetNetwork;replayBufferClass;dqnConfig;updateCount=0;actions=[];constructor(t={}){super("dqn","value-based"),this.dqnConfig={...$y,...t},this.initializeActions(),this.qNetwork=new q({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass=new Ke(this.config.replayBufferSize,!1)}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.targetNetwork.forward(e),i=this.argmax(r),n=this.actions[i];return{action:n,confidence:.7,value:r[i],reasoning:`DQN: ${n.type}`}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.dqnConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize),r=0;for(let i of e){let n=this.prepareState(i.state),s=this.prepareState(i.nextState),a=this.actionToIndex(i.action),o=this.qNetwork.forward(n),c;if(this.dqnConfig.doubleDQN&&!i.done){let d=this.qNetwork.forward(s),m=this.argmax(d),g=this.targetNetwork.forward(s);c=i.reward+this.config.discountFactor*g[m]}else{let d=this.targetNetwork.forward(s);c=i.reward+this.config.discountFactor*Math.max(...d)*(i.done?0:1)}let l=new Float32Array(o.length);for(let d=0;d<l.length;d++)l[d]=d===a?c:o[d];r+=Math.abs(this.qNetwork.train(n,l,new fe))}return this.updateCount++,this.updateCount%this.dqnConfig.targetUpdateFreq===0&&(this.targetNetwork=this.qNetwork.clone()),{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural DQN for Parallel Execution Scheduling",capabilities:["Experience replay","Target network","Double DQN"],hyperparameters:{stateSize:this.dqnConfig.stateSize,actionSize:this.dqnConfig.actionSize,hiddenLayers:this.dqnConfig.hiddenLayers.join(",")},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.dqnConfig.stateSize);for(;e.length<this.dqnConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"parallelize",value:2},{type:"parallelize",value:4},{type:"parallelize",value:8},{type:"sequential",value:1},{type:"skip",value:0}],this.dqnConfig.actionSize=this.actions.length,this.qNetwork=new q({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone()}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),targetNetwork:this.targetNetwork.getParameters(),dqnConfig:this.dqnConfig,updateCount:this.updateCount}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.targetNetwork&&this.targetNetwork.setParameters(t.targetNetwork),t.dqnConfig&&(this.dqnConfig={...this.dqnConfig,...t.dqnConfig}),typeof t.updateCount=="number"&&(this.updateCount=t.updateCount),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new q({layerSizes:[this.dqnConfig.stateSize,...this.dqnConfig.hiddenLayers,this.dqnConfig.actionSize],activations:Array(this.dqnConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.targetNetwork=this.qNetwork.clone(),this.replayBufferClass.clear(),this.updateCount=0}};var Oy={maxConcurrentWorkflows:3,defaultTimeout:3e5,publishEvents:!0,autoTriageVulnerabilities:!0,riskThreshold:.7,enableDQN:!0,enableFlashAttention:!0,enableConsensus:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},re=R.create("security-compliance"),ji=class extends Q{constructor(e,r,i,n={}){let s={...Oy,...n};super(e,"security-compliance",s,{verifyFindingTypes:["security-vulnerability","compliance-violation","credential-exposure"],...s.consensusMixinConfig});this.memory=r;this.agentCoordinator=i;this.securityGovernanceMixin=iu(this.domainName),this.securityScanner=new $e(r),this.securityAuditor=new Bt(r),this.complianceValidator=new qt(r)}memory;agentCoordinator;securityScanner;securityAuditor;complianceValidator;dqnAlgorithm;flashAttention;rlInitialized=!1;consensusEngine;securityGovernanceMixin;async onInitialize(){this.subscribeToEvents(),await this.loadWorkflowState(),(this.config.enableDQN||this.config.enableFlashAttention||this.config.enableConsensus)&&await this.initializeRLIntegrations()}async initializeRLIntegrations(){try{if(this.config.enableDQN&&(this.dqnAlgorithm=new ua({stateSize:8,actionSize:5,hiddenLayers:[128,128],targetUpdateFreq:100,minReplaySize:100,doubleDQN:!0})),this.config.enableFlashAttention){let e="test-similarity";this.flashAttention=await Ie(e,{dim:384,strategy:"flash",numHeads:8})}if(this.config.enableConsensus){let r=kt(!0).getAll();r.length>0?(this.consensusEngine=ui({strategy:"weighted",models:r,engineConfig:{minModels:Math.min(2,r.length),defaultModelTimeout:6e4,...this.config.consensusEngineConfig}}),re.info(`Multi-Model Consensus initialized with ${r.length} providers`)):re.warn("No model providers available for consensus verification")}this.rlInitialized=!0}catch(e){throw re.error("Failed to initialize RL integrations:",e instanceof Error?e:void 0),e}}async onDispose(){await this.saveWorkflowState()}getActiveWorkflows(){return super.getActiveWorkflows()}async runSecurityAudit(e){let r=v();try{if(this.startWorkflow(r,"audit"),this.detectAuthCodeInScope(e)&&this.securityGovernanceMixin.isGovernanceEnabled()&&!(await this.securityGovernanceMixin.validateSecurityScanRequired(r,!0,void 0)).allowed&&this.securityGovernanceMixin.isStrictMode()&&re.info("Security audit for auth code registered with governance"),this.minCutMixin.shouldPauseOperations())return re.warn("Security audit paused: topology is in critical state"),this.failWorkflow(r,"Topology is in critical state"),p(new Error("Security audit paused: topology is in critical state"));if(this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&re.warn("Topology degraded, using conservative audit strategy"),!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn security audit agents"));let n=await this.spawnSecurityAuditAgent(r,e);if(!n.success)return this.failWorkflow(r,n.error.message),p(n.error);this.addAgentToWorkflow(r,n.value);let s=e.tests||[];this.config.enableDQN&&this.dqnAlgorithm&&s.length>0&&(s=await this.prioritizeSecurityTests(e,s));let a={...e},o=await this.securityAuditor.runAudit(a);if(o.success){this.completeWorkflow(r);let c=this.extractVulnerabilitiesFromReport(o.value);this.config.enableFlashAttention&&this.flashAttention&&c.length>0&&await this.enhanceVulnerabilityAnalysis(c),this.config.enableDQN&&this.dqnAlgorithm&&await this.trainDQNWithAuditFeedback(e,o.value),this.config.publishEvents&&await this.publishSecurityAuditCompleted(o.value)}else this.failWorkflow(r,o.error.message);return await this.agentCoordinator.stop(n.value),o}catch(i){let n=y(i);return this.failWorkflow(r,n.message),{success:!1,error:n}}}async runSecurityScan(e,r){let i=v();try{if(this.startWorkflow(i,"scan"),this.minCutMixin.shouldPauseOperations())return re.warn("Security scan paused: topology is in critical state"),this.failWorkflow(i,"Topology is in critical state"),p(new Error("Security scan paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&re.warn("Topology degraded, proceeding with conservative scan strategy");let n;return r==="sast"?n=await this.securityScanner.scanFiles(e):r==="dast"?n=await this.securityScanner.scanUrl(e[0]?.value??""):n=await this.securityScanner.scanFiles(e),n.success?this.completeWorkflow(i):this.failWorkflow(i,n.error.message),n}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async runComplianceValidation(e,r){let i=v();try{if(this.startWorkflow(i,"compliance"),this.minCutMixin.shouldPauseOperations())return re.warn("Compliance validation paused: topology is in critical state"),this.failWorkflow(i,"Topology is in critical state"),p(new Error("Compliance validation paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&re.warn("Topology degraded, proceeding with compliance validation");let s=(await this.complianceValidator.getAvailableStandards()).find(o=>o.id===e);if(!s)return p(new Error(`Unknown compliance standard: ${e}`));let a=await this.complianceValidator.validate(s,r);return a.success?(this.completeWorkflow(i),this.config.publishEvents&&await this.publishComplianceValidationCompleted(a.value)):this.failWorkflow(i,a.error.message),a}catch(n){let s=y(n);return this.failWorkflow(i,s.message),{success:!1,error:s}}}async assessSecurityPosture(){let e=v();try{if(this.startWorkflow(e,"posture"),this.minCutMixin.shouldPauseOperations())return re.warn("Security posture assessment paused: topology is in critical state"),this.failWorkflow(e,"Topology is in critical state"),p(new Error("Security posture assessment paused: topology is in critical state"));this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&re.warn("Topology degraded, proceeding with security posture assessment");let r=await this.securityAuditor.getSecurityPosture();if(r.success){this.completeWorkflow(e);let i={overallScore:r.value.overallScore,trend:r.value.trend,criticalVulnerabilities:r.value.criticalIssues,complianceStatus:new Map,lastAuditDate:r.value.lastAuditDate};return f(i)}else return this.failWorkflow(e,r.error.message),r}catch(r){let i=y(r);return this.failWorkflow(e,i.message),{success:!1,error:i}}}async runComplianceCheck(e){let r={projectRoot:he.create("."),includePatterns:["**/*.ts","**/*.js"],excludePatterns:["node_modules/**"]};return this.runComplianceValidation(e,r)}async getSecurityPosture(){return this.assessSecurityPosture()}async prioritizeSecurityTests(e,r){if(!this.dqnAlgorithm||!this.rlInitialized)return r;try{let i=await Promise.all(r.map(async n=>{let s={id:`test-${n}`,features:this.extractSecurityTestFeatures(e,n)},a=await this.dqnAlgorithm.predict(s);return{test:n,score:a.value||0}}));return i.sort((n,s)=>s.score-n.score),i.map(n=>n.test)}catch(i){return re.error("Failed to prioritize security tests:",i instanceof Error?i:void 0),r}}async trainDQNWithAuditFeedback(e,r){if(!(!this.dqnAlgorithm||!this.rlInitialized))try{let i=this.extractVulnerabilitiesFromReport(r),n={id:`audit-${r.auditId}-${Date.now()}`,features:this.extractAuditFeatures(e)},s={type:"run-audit",value:i.length},a=this.calculateAuditReward(r),o={state:n,action:s,reward:a,nextState:n,done:!0,timestamp:new Date};await this.dqnAlgorithm.train(o),re.info(`Trained security audit with reward: ${a.toFixed(3)}`)}catch(i){re.error("Failed to train DQN:",i instanceof Error?i:void 0)}}calculateAuditReward(e){let r=this.extractVulnerabilitiesFromReport(e);if(r.length===0)return .5;let i=.5,n=r.filter(a=>a.severity==="critical").length;i+=Math.min(.3,n*.1);let s=r.filter(a=>a.severity==="high").length;return i+=Math.min(.2,s*.05),i+=(e.overallRiskScore?.value??0)*.1,Math.max(0,Math.min(1,i))}extractSecurityTestFeatures(e,r){let i=e.targetUrl??"";return[i.includes("/api")?1:0,i.startsWith("http")?1:0,e.includeSAST?1:0,r.includes("auth")?1:0,r.includes("sql")?1:0,r.includes("xss")?1:0,r.includes("injection")?1:0,r.length/100]}extractAuditFeatures(e){let r=e.depth??"standard",i=r==="deep"?1:r==="standard"?.5:.25;return[e.includeSAST?1:0,e.includeDAST?1:0,i,(e.scanTypes?.length??0)/4,e.includeDependencies?1:0,e.includeSecrets?1:0,(e.complianceFrameworks?.length??0)/5,e.targetUrl?1:0]}async enhanceVulnerabilityAnalysis(e){if(!(!this.flashAttention||!this.rlInitialized||e.length===0))try{let r=e.map(l=>this.createVulnerabilityEmbedding(l)),i=r.length,n=r[0].length,s=new Float32Array(i*n),a=new Float32Array(i*n),o=new Float32Array(i*n);for(let l=0;l<i;l++)s.set(r[l],l*n),a.set(r[l],l*n),o.set(r[l],l*n);let c=await this.flashAttention.computeFlashAttention(s,a,o,i,n);for(let l=0;l<e.length;l++){let d=Array.from(c.slice(l*n,(l+1)*n));r[l].reduce((g,h,b)=>g+h*d[b],0)>.7&&re.info(`High self-attention for vulnerability ${e[l].id}`)}}catch(r){re.error("Failed to enhance vulnerability analysis:",r instanceof Error?r:void 0)}}createVulnerabilityEmbedding(e){let r=[],i=this.hashCode(e.category);r.push(i%1e3/1e3);let n={critical:1,high:.75,medium:.5,low:.25,informational:.1};r.push(n[e.severity]||.5);let s=this.hashCode(e.title);r.push(s%1e3/1e3),r.push(Math.min(1,e.description.length/500));let a=e.cveId?this.hashCode(e.cveId):0;r.push(a%1e3/1e3);let o=this.hashCode(e.description.slice(0,200));for(let c=r.length;c<384;c++)r.push(o*(c+1)%1e4/1e4);return r.slice(0,384)}hashCode(e){let r=0;for(let i=0;i<e.length;i++)r=(r<<5)-r+e.charCodeAt(i),r=r|0;return Math.abs(r)}async spawnSecurityAuditAgent(e,r){let i={name:`security-auditor-${e.slice(0,8)}`,domain:"security-compliance",type:"auditor",capabilities:["security-audit","vulnerability-scanning","compliance-check"],config:{workflowId:e,targetUrl:r.targetUrl,depth:r.depth}};return this.agentCoordinator.spawn(i)}extractVulnerabilitiesFromReport(e){let r=[];return e.sastResults?.vulnerabilities&&r.push(...e.sastResults.vulnerabilities),e.dastResults?.vulnerabilities&&r.push(...e.dastResults.vulnerabilities),e.dependencyResults?.vulnerabilities&&r.push(...e.dependencyResults.vulnerabilities),r}async publishSecurityAuditCompleted(e){let r=this.extractVulnerabilitiesFromReport(e),i=await this.verifyHighSeverityFindings(r);for(let n of i){let s={vulnId:n.id,cve:n.cveId,severity:n.severity,file:n.location.file,line:n.location.line,description:n.description,remediation:n.remediation.description},a=D(Ma.SecurityAuditCompleted,"security-compliance",s);await this.eventBus.publish(a)}}async verifyHighSeverityFindings(e){if(!this.config.enableConsensus)return e;if(!this.isConsensusAvailable())return this.consensusEngine?this.verifyHighSeverityFindingsLegacy(e):e;let r=[],i=e.filter(a=>a.severity==="critical"||a.severity==="high"),n=e.filter(a=>a.severity!=="critical"&&a.severity!=="high");r.push(...n);for(let a of i)try{let o=V({id:a.id,type:"security-vulnerability",confidence:.8,description:`${a.title}: ${a.description}`,payload:{vulnerability:a,location:a.location},detectedBy:"security-scanner",severity:a.severity,context:{domain:this.domainName,cveId:a.cveId,category:a.category}});if(!this.consensusMixin.requiresConsensus(o)){r.push(a);continue}let c=await this.consensusMixin.verifyFinding(o);c.success&&c.value.verdict==="verified"?(re.info(`Consensus VERIFIED: ${a.title} (confidence: ${(c.value.confidence*100).toFixed(1)}%)`),r.push(a)):c.success&&c.value.verdict==="disputed"?(re.info(`Consensus DISPUTED: ${a.title} - including with lower confidence`),r.push(a)):re.info(`Consensus REJECTED: ${a.title} - likely false positive`)}catch{re.warn(`Consensus error verifying ${a.title}, including by default:`),r.push(a)}let s=i.length-r.filter(a=>a.severity==="critical"||a.severity==="high").length;return s>0&&re.info(`Consensus filtered out ${s} likely false positive(s)`),r}async verifyHighSeverityFindingsLegacy(e){if(!this.consensusEngine)return e;let r=[],i=e.filter(s=>s.severity==="critical"||s.severity==="high"),n=e.filter(s=>s.severity!=="critical"&&s.severity!=="high");r.push(...n);for(let s of i)try{let a={id:s.id,type:s.category,description:s.description,category:s.category,severity:s.severity,location:{file:s.location.file,line:s.location.line,column:s.location.column},evidence:[{type:"code-snippet",content:s.location.snippet||s.description}],cveId:s.cveId,remediation:s.remediation.description,detectedAt:new Date,detectedBy:"security-scanner"},o=await this.consensusEngine.verify(a);(o.success&&o.value.verdict==="verified"||o.success&&o.value.verdict==="disputed")&&r.push(s)}catch{r.push(s)}return r}async publishComplianceValidationCompleted(e){let r={standard:e.standardId,passed:e.complianceScore>=.8,violations:e.violations.length,findings:e.violations.map(n=>n.details).slice(0,10)},i=D(Ma.ComplianceValidated,"security-compliance",r);await this.eventBus.publish(i)}detectAuthCodeInScope(e){let r=[/auth/i,/login/i,/password/i,/token/i,/session/i,/oauth/i,/jwt/i,/credential/i,/identity/i];if(e.targetUrl){for(let i of r)if(i.test(e.targetUrl))return!0}if(e.scanTypes){let i=["authentication","authorization","session-management"];for(let n of e.scanTypes)if(i.includes(n.toLowerCase()))return!0}if(e.complianceFrameworks){let i=["soc2","pci-dss","hipaa","iso27001"];for(let n of e.complianceFrameworks)if(i.includes(n.toLowerCase()))return!0}return!1}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}async handleTestRunCompleted(e){}async handleImpactAnalysis(e){}async loadWorkflowState(){let e=await this.memory.get("security-compliance:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("security-compliance:coordinator:workflows",e,{namespace:"security-compliance",persist:!0})}getHealthyRoutingDomains(){return this.minCutMixin.getHealthyRoutingDomains()}};A();var da=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;securityScanner=null;securityAuditor=null;complianceValidator=null;pluginConfig;get name(){return"security-compliance"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runSecurityAudit:this.runSecurityAudit.bind(this),getSecurityPosture:this.getSecurityPosture.bind(this),runSASTScan:this.runSASTScan.bind(this),runDASTScan:this.runDASTScan.bind(this),triageVulnerabilities:this.triageVulnerabilities.bind(this),runComplianceCheck:this.runComplianceCheck.bind(this),getAvailableStandards:this.getAvailableStandards.bind(this),analyzeComplianceGaps:this.analyzeComplianceGaps.bind(this),getCoordinator:()=>this.coordinator,getSecurityScanner:()=>this.securityScanner,getSecurityAuditor:()=>this.securityAuditor,getComplianceValidator:()=>this.complianceValidator}}getTaskHandlers(){return new Map([["security-audit",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.target??e.targetUrl;return r?this.coordinator.runSecurityAudit({includeSAST:e.includeSAST??!0,includeDAST:e.includeDAST??!1,includeDependencies:e.includeDependencies??!0,includeSecrets:e.includeSecrets??!0,targetUrl:r}):p(new Error("Invalid security-audit payload: missing target"))}],["compliance-check",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.standardId;return r?this.coordinator.runComplianceCheck(r):p(new Error("Invalid compliance-check payload: missing standardId"))}],["sast-scan",async e=>{if(!this.securityScanner)return p(new Error("Security scanner not initialized"));let r=e.files;return!r||r.length===0?p(new Error("Invalid sast-scan payload: missing files")):this.securityScanner.scanFiles(r)}],["dast-scan",async e=>{if(!this.securityScanner)return p(new Error("Security scanner not initialized"));let r=e.targetUrl;return r?this.securityScanner.scanUrl(r):p(new Error("Invalid dast-scan payload: missing targetUrl"))}],["triage-vulnerabilities",async e=>{if(!this.securityAuditor)return p(new Error("Security auditor not initialized"));let r=e.vulnerabilities;return!r||r.length===0?p(new Error("Invalid triage-vulnerabilities payload: missing vulnerabilities")):this.securityAuditor.triageVulnerabilities(r)}]])}async onInitialize(){this.securityScanner=new $e(this.memory,this.pluginConfig.securityScanner),this.securityAuditor=new Bt(this.memory,this.pluginConfig.securityAuditor),this.complianceValidator=new qt(this.memory,this.pluginConfig.complianceValidator),this.coordinator=new ji(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.securityScanner=null,this.securityAuditor=null,this.complianceValidator=null}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.KnowledgeGraphUpdated",this.handleKnowledgeGraphUpdate.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"code-intelligence.KnowledgeGraphUpdated":await this.handleKnowledgeGraphUpdate(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;default:break}}async runSecurityAudit(e){this.ensureInitialized();try{let r=await this.coordinator.runSecurityAudit(e);return r.success?this.trackSuccessfulOperation("audit"):this.trackFailedOperation("audit",r.error),r}catch(r){return this.handleError(r)}}async getSecurityPosture(){this.ensureInitialized();try{return await this.coordinator.getSecurityPosture()}catch(e){return this.handleError(e)}}async runSASTScan(e){this.ensureInitialized();try{let r=await this.securityScanner.scanFiles(e);return r.success?this.trackSuccessfulOperation("sast-scan"):this.trackFailedOperation("sast-scan",r.error),r}catch(r){return this.handleError(r)}}async runDASTScan(e){this.ensureInitialized();try{let r=await this.securityScanner.scanUrl(e);return r.success?this.trackSuccessfulOperation("dast-scan"):this.trackFailedOperation("dast-scan",r.error),r}catch(r){return this.handleError(r)}}async triageVulnerabilities(e){this.ensureInitialized();try{let r=await this.securityAuditor.triageVulnerabilities(e);return r.success?{success:!0,value:{immediate:r.value.immediate,shortTerm:r.value.shortTerm}}:{success:!1,error:r.error}}catch(r){return this.handleError(r)}}async runComplianceCheck(e){this.ensureInitialized();try{let r=await this.coordinator.runComplianceCheck(e);return r.success?this.trackSuccessfulOperation("compliance-check"):this.trackFailedOperation("compliance-check",r.error),r}catch(r){return this.handleError(r)}}async getAvailableStandards(){return this.ensureInitialized(),this.complianceValidator.getAvailableStandards()}async analyzeComplianceGaps(e,r){this.ensureInitialized();try{return await this.complianceValidator.analyzeGaps(e,r)}catch(i){return this.handleError(i)}}async handleKnowledgeGraphUpdate(e){let r=e.payload;await this.memory.set(`security:code-update:${Date.now()}`,{filesIndexed:r.filesIndexed,timestamp:new Date},{namespace:"security-compliance",ttl:3600})}async handleQualityGateEvaluated(e){let r=e.payload,i=r.checks.filter(n=>n.name.toLowerCase().includes("security"));i.length>0&&await this.memory.set(`security:gate-results:${r.gateId}`,{securityChecks:i,passed:r.passed},{namespace:"security-compliance",persist:!0})}async handleTestRunCompleted(e){}ensureInitialized(){if(!this._initialized)throw new Error("SecurityCompliancePlugin is not initialized");if(!this.coordinator||!this.securityScanner||!this.securityAuditor||!this.complianceValidator)throw new Error("SecurityCompliancePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date}),this.memory.set(`security:operation:${e}:${Date.now()}`,{operation:e,success:!0,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]}),this.memory.set(`security:operation:${e}:${Date.now()}`,{operation:e,success:!1,error:r.message,timestamp:new Date},{namespace:"security-compliance",ttl:86400})}};function Uc(u,t,e,r){return new da(u,t,e,r)}M();A();M();A();H();var Ny={strictMode:!0,validateExamples:!0,maxSchemaDepth:Nn.MAX_SCHEMA_DEPTH,cacheValidations:!0,enableLLMAnalysis:!0,llmModelTier:2,llmMaxTokens:Vn.MAX_TOKENS},Vy=R.create("contract-testing/contract-validator"),Tr=class{config;memory;llmRouter;validationCache=new Map;MAX_CACHED_VALIDATIONS=Nn.MAX_CACHED_VALIDATIONS;CACHE_TTL_MS=Nn.CACHE_TTL_MS;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...Ny,...e}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}async analyzeContractWithLLM(t){if(!this.isLLMAnalysisAvailable())return null;try{let e=t.consumers.map(i=>i.name).join(", ");return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this API contract for potential issues:
2925
2925
  Provider: ${t.provider.name}
2926
2926
  Consumers: ${e}
2927
2927
  Version: ${t.version.toString()}
@@ -2936,7 +2936,7 @@ Provide:
2936
2936
  `),i=null,n=null,s=0;for(let a=0;a<r.length;a++){let o=r[a].trim();if(o.startsWith("#")||o==="")continue;if(o.match(/^schema\s*\{?/)){let d=o;if(!o.includes("}"))for(let b=a+1;b<r.length&&(d+=" "+r[b].trim(),!r[b].includes("}"));b++);let m=d.match(/query\s*:\s*(\w+)/),g=d.match(/mutation\s*:\s*(\w+)/),h=d.match(/subscription\s*:\s*(\w+)/);m&&(e.queryType=m[1]),g&&(e.mutationType=g[1]),h&&(e.subscriptionType=h[1]);continue}let l=o.match(/^(type|input|interface|enum)\s+(\w+)(?:\s+implements\s+(\w+))?\s*\{?/);if(l){n=l[1],i=l[2],e.types[i]={kind:n,fields:{},implements:l[3]||null},i==="Query"&&!e.queryType&&(e.queryType="Query"),i==="Mutation"&&!e.mutationType&&(e.mutationType="Mutation"),i==="Subscription"&&!e.subscriptionType&&(e.subscriptionType="Subscription"),o.includes("{")&&s++;continue}if(o.includes("{")&&s++,o.includes("}")){s--,s===0&&(i=null,n=null);continue}if(i&&n!=="enum"){let d=o.match(/^(\w+)(?:\s*\(([^)]*)\))?\s*:\s*(.+?)(?:\s*@.*)?$/);if(d){let m=d[1],g=d[2],b={type:d[3].trim(),arguments:{}};if(g){let w=g.matchAll(/(\w+)\s*:\s*([^,\)]+)/g);for(let C of w)b.arguments[C[1]]={type:C[2].trim()}}e.types[i].fields[m]=b}}if(i&&n==="enum"){let d=o.match(/^(\w+)(?:\s*@.*)?$/);d&&(e.types[i].fields[d[1]]={type:"EnumValue"})}}return!e.queryType&&Object.keys(e.types).length>0&&(e.types.Query||e.errors.push("GraphQL schema must define a Query type or schema definition")),e}parseGraphQLOperation(t){let e={type:"query",name:null,fields:[],variableDefinitions:{},errors:[]},r=t.replace(/#[^\n]*/g,"").trim(),i=r.match(/^(query|mutation|subscription)(?:\s+(\w+))?\s*(?:\(([^)]*)\))?\s*\{/);if(i){if(e.type=i[1],e.name=i[2]||null,i[3]){let s=i[3].matchAll(/\$(\w+)\s*:\s*([^,\)!]+)(!)?/g);for(let a of s)e.variableDefinitions[a[1]]={type:a[2].trim(),required:!!a[3]}}}else if(r.startsWith("{"))e.type="query";else if(!r.includes("{"))return e.errors.push("Invalid GraphQL operation: missing selection set"),e;let n=r.match(/\{([\s\S]*)\}/);return n?(e.fields=this.parseGraphQLSelectionSet(n[1]),e):(e.errors.push("Invalid GraphQL operation: could not parse selection set"),e)}parseGraphQLSelectionSet(t){let e=[],r=0,i="",n=0;for(;n<t.length;){let s=t[n];if(s==="{")r++,i+=s;else if(s==="}")r--,i+=s;else if((s===`
2937
2937
  `||s===" "||s===",")&&r===0){if(i.trim()){let a=this.parseGraphQLField(i.trim());a&&e.push(a)}i=""}else i+=s;n++}if(i.trim()){let s=this.parseGraphQLField(i.trim());s&&e.push(s)}return e}parseGraphQLField(t){let e=t.match(/^(\w+)\s*:\s*(.+)$/),r=t,i;e&&!e[2].includes("(")&&!e[2].includes("{")||e&&(e[2].match(/^\w/)||e[2].includes("("))&&(i=e[1],r=e[2]);let n=r.match(/^(\w+)(?:\s*\(([^)]*)\))?(?:\s*\{([\s\S]*)\})?$/);if(!n){let a=r.match(/^(\w+)(?:\s*\(([^)]*)\))?/);return a?{name:a[1],alias:i,arguments:a[2]?this.parseGraphQLArguments(a[2]):void 0}:null}let s={name:n[1],alias:i};return n[2]&&(s.arguments=this.parseGraphQLArguments(n[2])),n[3]&&(s.selections=this.parseGraphQLSelectionSet(n[3])),s}parseGraphQLArguments(t){let e={},r=t.matchAll(/(\w+)\s*:\s*([^,\)]+)/g);for(let i of r){let n=i[2].trim();n.startsWith("$")?e[i[1]]={_variable:n.substring(1)}:n.startsWith('"')||n.startsWith("'")?e[i[1]]=n.slice(1,-1):n==="true"?e[i[1]]=!0:n==="false"?e[i[1]]=!1:n==="null"?e[i[1]]=null:isNaN(Number(n))?e[i[1]]=n:e[i[1]]=Number(n)}return e}getRootTypeForOperation(t,e){switch(t){case"query":return e.queryType;case"mutation":return e.mutationType;case"subscription":return e.subscriptionType;default:return null}}unwrapGraphQLType(t){return t.replace(/[\[\]!]/g,"").trim()}validateGraphQLSelections(t,e,r,i,n){let s=r.types[e];if(!s){["String","Int","Float","Boolean","ID"].includes(e)&&t.length>0&&n.push({path:i,keyword:"selection",message:`Cannot select fields on scalar type '${e}'`,params:{type:e}});return}for(let a of t){let o=s.fields[a.name];if(!o)n.push({path:`${i}.${a.name}`,keyword:"field",message:`Field '${a.name}' does not exist on type '${e}'`,params:{field:a.name,type:e}});else if(a.selections&&a.selections.length>0){let c=this.unwrapGraphQLType(o.type);this.validateGraphQLSelections(a.selections,c,r,`${i}.${a.name}`,n)}}}validateGraphQLVariableType(t,e,r,i){let n=this.unwrapGraphQLType(e),s=e.endsWith("!"),a=e.includes("[");if(t==null){s&&i.push({path:r,keyword:"type",message:`Variable cannot be null (expected ${e})`,params:{expectedType:e}});return}if(a){Array.isArray(t)||i.push({path:r,keyword:"type",message:`Expected array for type ${e}`,params:{expectedType:e,actualType:typeof t}});return}switch(n){case"String":case"ID":typeof t!="string"&&i.push({path:r,keyword:"type",message:`Expected string for type ${n}`,params:{expectedType:n,actualType:typeof t}});break;case"Int":(typeof t!="number"||!Number.isInteger(t))&&i.push({path:r,keyword:"type",message:"Expected integer for type Int",params:{expectedType:"Int",actualType:typeof t}});break;case"Float":typeof t!="number"&&i.push({path:r,keyword:"type",message:"Expected number for type Float",params:{expectedType:"Float",actualType:typeof t}});break;case"Boolean":typeof t!="boolean"&&i.push({path:r,keyword:"type",message:"Expected boolean for type Boolean",params:{expectedType:"Boolean",actualType:typeof t}});break;default:typeof t!="object"&&i.push({path:r,keyword:"type",message:`Expected object for type ${n}`,params:{expectedType:n,actualType:typeof t}})}}basicTypeValidation(t,e,r,i,n=0){if(n>this.config.maxSchemaDepth){i.push({path:r,keyword:"maxDepth",message:"Maximum schema depth exceeded",params:{maxDepth:this.config.maxSchemaDepth}});return}let s=e.type;if(!s)return;let a=this.getJsonType(t);if(s==="object"&&a==="object"){let o=e.properties||{},c=e.required||[],l=t;for(let d of c)d in l||i.push({path:r?`${r}.${d}`:d,keyword:"required",message:`Required property '${d}' is missing`,params:{missingProperty:d}});for(let[d,m]of Object.entries(o))d in l&&this.basicTypeValidation(l[d],m,r?`${r}.${d}`:d,i,n+1)}else if(s==="array"&&a==="array"){let o=e.items,c=t;if(this.validateArrayConstraints(c,e,r,i),o)for(let l=0;l<c.length;l++)this.basicTypeValidation(c[l],o,`${r}[${l}]`,i,n+1)}else s==="string"&&a==="string"?this.validateStringConstraints(t,e,r,i):(s==="number"||s==="integer")&&(a==="number"||a==="integer")?this.validateNumberConstraints(t,e,r,i):s!==a&&(s==="number"&&a==="integer"||i.push({path:r,keyword:"type",message:`Expected type '${s}' but got '${a}'`,params:{expectedType:s,actualType:a}}));if(e.enum){let o=e.enum;o.some(c=>JSON.stringify(c)===JSON.stringify(t))||i.push({path:r,keyword:"enum",message:`Value must be one of: ${o.map(c=>JSON.stringify(c)).join(", ")}`,params:{allowedValues:o}})}}validateStringConstraints(t,e,r,i){let n=e.minLength,s=e.maxLength,a=e.pattern;if(n!==void 0&&t.length<n&&i.push({path:r,keyword:"minLength",message:`String must be at least ${n} characters`,params:{limit:n,actual:t.length}}),s!==void 0&&t.length>s&&i.push({path:r,keyword:"maxLength",message:`String must be at most ${s} characters`,params:{limit:s,actual:t.length}}),a){let o=Vr(a);o&&!o.test(t)&&i.push({path:r,keyword:"pattern",message:`String must match pattern: ${a}`,params:{pattern:a}})}}validateNumberConstraints(t,e,r,i){let n=e.minimum,s=e.maximum,a=e.exclusiveMinimum,o=e.exclusiveMaximum,c=e.multipleOf;n!==void 0&&t<n&&i.push({path:r,keyword:"minimum",message:`Number must be >= ${n}`,params:{limit:n,actual:t}}),s!==void 0&&t>s&&i.push({path:r,keyword:"maximum",message:`Number must be <= ${s}`,params:{limit:s,actual:t}}),a!==void 0&&t<=a&&i.push({path:r,keyword:"exclusiveMinimum",message:`Number must be > ${a}`,params:{limit:a,actual:t}}),o!==void 0&&t>=o&&i.push({path:r,keyword:"exclusiveMaximum",message:`Number must be < ${o}`,params:{limit:o,actual:t}}),c!==void 0&&t%c!==0&&i.push({path:r,keyword:"multipleOf",message:`Number must be a multiple of ${c}`,params:{multipleOf:c,actual:t}})}validateArrayConstraints(t,e,r,i){let n=e.minItems,s=e.maxItems,a=e.uniqueItems;if(n!==void 0&&t.length<n&&i.push({path:r,keyword:"minItems",message:`Array must have at least ${n} items`,params:{limit:n,actual:t.length}}),s!==void 0&&t.length>s&&i.push({path:r,keyword:"maxItems",message:`Array must have at most ${s} items`,params:{limit:s,actual:t.length}}),a){let o=new Set;for(let c=0;c<t.length;c++){let l=JSON.stringify(t[c]);if(o.has(l)){i.push({path:`${r}[${c}]`,keyword:"uniqueItems",message:"Array items must be unique",params:{duplicateIndex:c}});break}o.add(l)}}}getJsonType(t){return t===null?"null":Array.isArray(t)?"array":typeof t=="number"?Number.isInteger(t)?"integer":"number":typeof t}validateOpenAPI3Structure(t,e,r){if(!t.info)e.push({path:"info",message:"OpenAPI 3.x requires info object",code:"REQUIRED_FIELD"});else{let i=t.info;i.title||e.push({path:"info.title",message:"API title is required",code:"REQUIRED_FIELD"}),i.version||e.push({path:"info.version",message:"API version is required",code:"REQUIRED_FIELD"})}t.paths||r.push("No paths defined in OpenAPI specification")}validateSwagger2Structure(t,e,r){t.info||e.push({path:"info",message:"Swagger 2 requires info object",code:"REQUIRED_FIELD"}),t.paths||r.push("No paths defined in Swagger specification"),!t.host&&!t.basePath&&r.push("No host or basePath defined in Swagger specification")}async storeValidationHistory(t,e){let r=`contract-testing:validation:${t}:${Date.now()}`;await this.memory.set(r,e,{namespace:"contract-testing",ttl:86400*30})}cacheValidation(t,e){if(this.validationCache.size>=this.MAX_CACHED_VALIDATIONS){let r=this.validationCache.keys().next().value;r&&this.validationCache.delete(r)}this.validationCache.set(t,{...e,cachedAt:Date.now()})}cleanupCache(){let t=Date.now(),e=0;for(let[r,i]of this.validationCache)t-(i.cachedAt||0)>this.CACHE_TTL_MS&&(this.validationCache.delete(r),e++);return e}destroy(){this.validationCache.clear()}};A();H();var _y={strictEnumValidation:!0,allowOptionalToRequired:!1,trackDeprecations:!0,maxMigrationSteps:50},Ar=class{constructor(t,e={}){this.memory=t;this.config={..._y,...e}}memory;config;async compareVersions(t,e){try{let r=[],i=[],n=[];await this.compareEndpoints(t.endpoints,e.endpoints,t.consumers.map(a=>a.name),r,i),await this.compareSchemas(t.schemas,e.schemas,t.consumers.map(a=>a.name),r,i),this.config.trackDeprecations&&this.detectDeprecations(t,e,n);let s={isCompatible:r.length===0,breakingChanges:r,nonBreakingChanges:i,deprecations:n};return await this.storeComparisonResult(t,e,s),f(s)}catch(r){return p(y(r))}}async isBackwardCompatible(t,e){let r=await this.compareVersions(t,e);return r.success?f(r.value.breakingChanges.length===0):r}async getBreakingChanges(t,e){let r=await this.compareVersions(t,e);return r.success?f(r.value.breakingChanges):r}async generateMigrationGuide(t){try{if(t.length===0)return f({fromVersion:"unknown",toVersion:"unknown",steps:[],estimatedEffort:"trivial"});let e=[],r=1,i=t.filter(m=>m.type==="removed-endpoint"),n=t.filter(m=>m.type==="type-change"),s=t.filter(m=>m.type==="required-field-added"),a=t.filter(m=>m.type==="removed-field"),o=t.filter(m=>m.type==="enum-value-removed"),c=t.filter(m=>m.type==="response-code-change");for(let m of s)e.push(this.createMigrationStep(r++,m,"required-field"));for(let m of n)e.push(this.createMigrationStep(r++,m,"type-change"));for(let m of o)e.push(this.createMigrationStep(r++,m,"enum-change"));for(let m of a)e.push(this.createMigrationStep(r++,m,"removed-field"));for(let m of c)e.push(this.createMigrationStep(r++,m,"response-code"));for(let m of i)e.push(this.createMigrationStep(r++,m,"removed-endpoint"));let l=e.slice(0,this.config.maxMigrationSteps),d=this.estimateEffort(t);return f({fromVersion:"previous",toVersion:"current",steps:l,estimatedEffort:d})}catch(e){return p(y(e))}}async compareEndpoints(t,e,r,i,n){let s=this.buildEndpointMap(t),a=this.buildEndpointMap(e),o=Array.from(s.entries());for(let[l,d]of o)a.has(l)||i.push({type:"removed-endpoint",location:`${d.method} ${d.path}`,description:`Endpoint ${d.method} ${d.path} has been removed`,impact:"high",affectedConsumers:r,migrationPath:"Find alternative endpoint or remove usage"});let c=Array.from(a.entries());for(let[l,d]of c)s.has(l)||n.push({type:"added-endpoint",location:`${d.method} ${d.path}`,description:`New endpoint ${d.method} ${d.path} added`});for(let[l,d]of o){let m=a.get(l);m&&await this.compareEndpointDetails(d,m,r,i,n)}}async compareEndpointDetails(t,e,r,i,n){let s=`${t.method} ${t.path}`;t.requestSchema!==e.requestSchema&&i.push({type:"type-change",location:`${s} request`,description:`Request schema changed from '${t.requestSchema||"none"}' to '${e.requestSchema||"none"}'`,impact:"high",affectedConsumers:r}),t.responseSchema!==e.responseSchema&&i.push({type:"type-change",location:`${s} response`,description:`Response schema changed from '${t.responseSchema||"none"}' to '${e.responseSchema||"none"}'`,impact:"medium",affectedConsumers:r});let a=new Set(t.examples.map(l=>l.statusCode)),o=new Set(e.examples.map(l=>l.statusCode)),c=Array.from(a);for(let l of c)o.has(l)||i.push({type:"response-code-change",location:`${s} status ${l}`,description:`Status code ${l} is no longer documented`,impact:"low",affectedConsumers:r})}async compareSchemas(t,e,r,i,n){let s=new Map(t.map(d=>[d.id,d])),a=new Map(e.map(d=>[d.id,d])),o=Array.from(s.keys());for(let d of o)a.has(d)||i.push({type:"removed-field",location:`schema:${d}`,description:`Schema '${d}' has been removed`,impact:"high",affectedConsumers:r});let c=Array.from(a.keys());for(let d of c)s.has(d)||n.push({type:"added-field",location:`schema:${d}`,description:`New schema '${d}' added`});let l=Array.from(s.entries());for(let[d,m]of l){let g=a.get(d);g&&await this.compareSchemaContent(m,g,r,i,n)}}async compareSchemaContent(t,e,r,i,n){if(!(t.type!=="json-schema"||e.type!=="json-schema"))try{let s=E(t.content),a=E(e.content),o=s.properties||{},c=a.properties||{},l=s.required||[],d=a.required||[];for(let m of Object.keys(o))m in c||i.push({type:"removed-field",location:`schema:${t.id}.${m}`,description:`Property '${m}' has been removed from schema '${t.id}'`,impact:"high",affectedConsumers:r});for(let m of Object.keys(c))m in o||n.push({type:"added-field",location:`schema:${e.id}.${m}`,description:`Property '${m}' added to schema '${e.id}'`});for(let m of d)l.includes(m)||(m in o?this.config.allowOptionalToRequired||i.push({type:"required-field-added",location:`schema:${e.id}.${m}`,description:`Property '${m}' changed from optional to required in schema '${e.id}'`,impact:"high",affectedConsumers:r}):m in c&&i.push({type:"required-field-added",location:`schema:${e.id}.${m}`,description:`New required property '${m}' added to schema '${e.id}'`,impact:"high",affectedConsumers:r}));for(let m of Object.keys(o))if(m in c){let g=o[m],h=c[m];if(g.type!==h.type&&i.push({type:"type-change",location:`schema:${t.id}.${m}`,description:`Type of '${m}' changed from '${g.type}' to '${h.type}'`,impact:"high",affectedConsumers:r}),this.config.strictEnumValidation){let b=g.enum,w=h.enum;if(b&&w){for(let C of b)w.includes(C)||i.push({type:"enum-value-removed",location:`schema:${t.id}.${m}`,description:`Enum value '${C}' removed from '${m}'`,impact:"medium",affectedConsumers:r});for(let C of w)b.includes(C)||n.push({type:"added-enum-value",location:`schema:${e.id}.${m}`,description:`Enum value '${C}' added to '${m}'`})}}}}catch{}}detectDeprecations(t,e,r){let i=this.buildEndpointMap(t.endpoints),n=this.buildEndpointMap(e.endpoints);for(let[s,a]of i)n.get(s)||r.push({location:`${a.method} ${a.path}`,reason:"Endpoint has been removed in the new version",removalVersion:e.version.toString()});for(let s of e.schemas)this.detectSchemaDeprecations(s,r,e.version);for(let s of e.endpoints)if(s.path.includes("/deprecated/")&&r.push({location:`${s.method} ${s.path}`,reason:"Endpoint path indicates deprecation"}),s.responseSchema){let a=e.schemas.find(o=>o.name===s.responseSchema);a&&this.detectSchemaDeprecations(a,r,e.version,`${s.method} ${s.path}`)}}detectSchemaDeprecations(t,e,r,i){try{let n=typeof t.content=="string"?E(t.content):t.content;this.scanObjectForDeprecations(n,t.name,e,r,i)}catch{}}scanObjectForDeprecations(t,e,r,i,n){if(!t||typeof t!="object")return;let s=t;if(s.deprecated===!0){let a=n?`${n} -> ${e}`:e;r.push({location:a,reason:typeof s.description=="string"?s.description:"Field marked as deprecated",removalVersion:typeof s.removalVersion=="string"?s.removalVersion:void 0,replacement:typeof s.replacement=="string"?s.replacement:void 0})}if(s["x-deprecated"]===!0){let a=n?`${n} -> ${e}`:e;r.push({location:a,reason:typeof s["x-deprecated-message"]=="string"?s["x-deprecated-message"]:"Element marked as deprecated via x-deprecated",removalVersion:i.toString()})}if(s.properties&&typeof s.properties=="object"){let a=s.properties;for(let[o,c]of Object.entries(a))this.scanObjectForDeprecations(c,`${e}.${o}`,r,i,n)}s.items&&typeof s.items=="object"&&this.scanObjectForDeprecations(s.items,`${e}[]`,r,i,n)}buildEndpointMap(t){let e=new Map;for(let r of t){let i=`${r.method}:${r.path}`;e.set(i,r)}return e}createMigrationStep(t,e,r){let i,n,s=!1;switch(r){case"required-field":i=`Add required field: ${e.description}`,n=`// Add the new required field to your request/data objects
2938
2938
  // Location: ${e.location}`,s=!1;break;case"type-change":i=`Update type: ${e.description}`,n=`// Update the type at ${e.location}
2939
- // Follow the new type specification`,s=!1;break;case"enum-change":i=`Update enum usage: ${e.description}`,n=`// Remove usage of deprecated enum value at ${e.location}`,s=!0;break;case"removed-field":i=`Remove field usage: ${e.description}`,n=`// Remove references to ${e.location}`,s=!0;break;case"response-code":i=`Update response handling: ${e.description}`,n=`// Update error handling for ${e.location}`,s=!1;break;case"removed-endpoint":i=`Migrate from removed endpoint: ${e.description}`,n=e.migrationPath?`// ${e.migrationPath}`:`// Find alternative for ${e.location}`,s=!1;break;default:i=e.description,n=void 0,s=!1}return{order:t,description:i,codeChanges:n,automated:s}}estimateEffort(t){if(t.length===0)return"trivial";let e=t.filter(i=>i.impact==="high").length,r=t.filter(i=>i.impact==="medium").length;return e>5||t.length>10?"major":e>2||r>5?"moderate":e>0||t.length>3?"minor":"trivial"}async storeComparisonResult(t,e,r){let i=`contract-testing:comparison:${t.id}:${t.version.toString()}:${e.version.toString()}`;await this.memory.set(i,{oldVersion:t.version.toString(),newVersion:e.version.toString(),isCompatible:r.isCompatible,breakingChangeCount:r.breakingChanges.length,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400*90})}};var zy={stateSize:10,actionSize:4,hiddenLayers:[128,128],minReplaySize:100},ma=class extends ae{qNetwork;replayBufferClass;sarsaConfig;actions=[];constructor(t={}){super("sarsa","value-based"),this.sarsaConfig={...zy,...t},this.initializeActions(),this.qNetwork=new q({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.replayBufferClass=new Ke(this.config.replayBufferSize,!1)}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.qNetwork.forward(e),i=this.argmax(r),n=this.actions[i];return{action:n,confidence:.7,value:r[i],reasoning:`SARSA: ${n.type}`}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.sarsaConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize),r=0;for(let i=0;i<e.length;i++){let n=e[i],s=e[i+1],a=this.prepareState(n.state),o=this.actionToIndex(n.action),c=this.qNetwork.forward(a),l=c[o],d=0;if(s&&!n.done){let h=this.prepareState(s.state),b=this.actionToIndex(s.action);d=this.qNetwork.forward(h)[b]}let m=n.reward+this.config.discountFactor*d,g=new Float32Array(c.length);for(let h=0;h<g.length;h++)g[h]=h===o?m:c[h];r+=Math.abs(this.qNetwork.train(a,g,new fe))}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural SARSA for Defect Prediction Sequencing",capabilities:["On-policy learning","Neural Q-network"],hyperparameters:{stateSize:this.sarsaConfig.stateSize,actionSize:this.sarsaConfig.actionSize,hiddenLayers:this.sarsaConfig.hiddenLayers.join(",")},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.sarsaConfig.stateSize);for(;e.length<this.sarsaConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"predict-high",value:1},{type:"predict-low",value:0},{type:"sequence-early",value:"high-risk"},{type:"sequence-late",value:"low-risk"}],this.sarsaConfig.actionSize=this.actions.length,this.qNetwork=new q({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate})}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),sarsaConfig:this.sarsaConfig}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.sarsaConfig&&(this.sarsaConfig={...this.sarsaConfig,...t.sarsaConfig}),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new q({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.replayBufferClass.clear()}};qe();H();var pa={ContractVerified:"contract-testing.ContractVerified",BreakingChangeDetected:"contract-testing.BreakingChangeDetected",ContractPublished:"contract-testing.ContractPublished",ConsumerContractCreated:"contract-testing.ConsumerContractCreated",VerificationFailed:"contract-testing.VerificationFailed"},By={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},Z=R.create("contract-testing"),ga=class extends Q{constructor(e,r,i,n={}){let s={...By,...n};super(e,"contract-testing",s,{verifyFindingTypes:["contract-violation","breaking-change","schema-incompatibility"]});this.memory=r;this.agentCoordinator=i;this.contractValidator=new Tr({memory:r}),this.apiCompatibility=new Ar(r),this.httpClient=_i(),this.fileReader=new De}memory;agentCoordinator;contractValidator;apiCompatibility;httpClient;fileReader;contractStore=new Map;sarsaAlgorithm;qesona;async onInitialize(){if(this.config.enableSARSA)try{this.sarsaAlgorithm=new ma({stateSize:10,actionSize:4,hiddenLayers:[64,64]}),Z.info("SARSA algorithm created successfully")}catch(e){throw Z.error("Failed to create SARSA:",e instanceof Error?e:void 0),new Error(`SARSA creation failed: ${T(e)}`)}if(this.config.enableQESONA)try{this.qesona=await me({domain:"contract-testing",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),Z.info("PersistentSONAEngine initialized successfully")}catch(e){Z.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),Z.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadContracts()}async onDispose(){await this.saveContracts(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.sarsaAlgorithm=void 0,this.contractStore.clear()}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async registerContract(e){try{let r=await this.contractValidator.validateContract(e);if(!r.success)return r;if(!r.value.isValid){let i=r.value.errors.map(n=>n.message).join("; ");return p(new Error(`Contract validation failed: ${i}`))}return this.contractStore.set(e.id,e),await this.memory.set(`contract-testing:contract:${e.id}`,e,{namespace:"contract-testing",persist:!0}),this.config.publishEvents&&await this.publishContractRegistered(e),f(e.id)}catch(r){return p(y(r))}}async verifyAllConsumers(e,r){let i=v();try{if(this.startWorkflow(i,"verify"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Z.warn("Topology degraded, using conservative verification strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Contract verification paused: topology is in critical state"));let n=await this.findContractsByProvider(e);if(n.length===0)return this.completeWorkflow(i),f({provider:e,totalConsumers:0,passedConsumers:0,failedConsumers:[],results:[],canDeploy:!0});if(this.config.enableSARSA&&n.length>1){let d={urgency:5,providerLoad:50,consumerCount:n.reduce((g,h)=>g+h.consumers.length,0)},m=await this.prioritizeContracts(n,d);m.success&&(n=m.value.orderedContracts,Z.info(`[contract-testing] Using ${m.value.strategy} strategy for contract verification order (confidence: ${m.value.confidence.toFixed(2)})`))}let s=await this.spawnVerificationAgent(i,e);if(!s.success)return this.failWorkflow(i,s.error.message),s;this.addAgentToWorkflow(i,s.value);let a=[],o=[];for(let d of n){for(let m of d.consumers){let g=await this.verifyConsumerContract(d,m.name,r);a.push(g),g.passed?this.config.publishEvents&&await this.publishContractVerified(d,m.name,g):(o.push(m.name),this.config.publishEvents&&await this.publishVerificationFailed(d,m.name,g))}this.updateWorkflowProgress(i,a.length/n.length*100)}await this.agentCoordinator.stop(s.value),this.completeWorkflow(i);let c=Array.from(new Set(o)),l=n.flatMap(d=>d.consumers.map(m=>m.name)).filter(d=>!c.includes(d)).length;return f({provider:e,totalConsumers:n.reduce((d,m)=>d+m.consumers.length,0),passedConsumers:l,failedConsumers:c,results:a,canDeploy:c.length===0})}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async preReleaseCheck(e,r){let i=v();try{if(this.startWorkflow(i,"compare"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Z.warn("Topology degraded, using conservative pre-release check"),this.minCutMixin.shouldPauseOperations())return p(new Error("Pre-release check paused: topology is in critical state"));let n=await this.loadContractFromPath(r);if(!n)return this.failWorkflow(i,"Failed to load contract from path"),p(new Error("Failed to load contract from path"));let s=await this.findContractsByProvider(e),a=s.length>0?s[0]:null;if(!a)return this.completeWorkflow(i),f({breakingChanges:[],affectedConsumers:[],canRelease:!0,recommendations:["No existing contract found. This will be the first version."]});let o=await this.apiCompatibility.compareVersions(a,n);if(!o.success)return this.failWorkflow(i,o.error.message),o;let{breakingChanges:c,deprecations:l}=o.value,d=[];for(let g of a.consumers){let h=c.filter(b=>b.affectedConsumers.includes(g.name));h.length>0&&d.push({name:g.name,team:g.team,breakingChanges:h,notified:!1})}let m=[];if(c.length>0){m.push(`${c.length} breaking changes detected. Coordinate with affected consumers before release.`);let g=await this.apiCompatibility.generateMigrationGuide(c);g.success&&m.push(`Migration effort estimated as: ${g.value.estimatedEffort}`)}return l.length>0&&m.push(`${l.length} deprecations detected. Consider communicating removal timeline.`),c.length===0&&l.length===0&&m.push("No breaking changes detected. Safe to release."),this.config.publishEvents&&c.length>0&&await this.publishBreakingChangeDetected(n.id,c,d.map(g=>g.name)),this.completeWorkflow(i),f({breakingChanges:c,affectedConsumers:d,canRelease:c.length===0,recommendations:m})}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async importFromOpenAPI(e){let r=v();try{this.startWorkflow(r,"import");let i=await this.loadFileContent(e);if(!i)return this.failWorkflow(r,"Failed to load OpenAPI spec"),p(new Error("Failed to load OpenAPI spec"));let n=await this.contractValidator.validateOpenAPI(i);if(!n.success)return this.failWorkflow(r,n.error.message),n;if(!n.value.isValid){let a=n.value.errors.map(o=>o.message).join("; ");return this.failWorkflow(r,a),p(new Error(`Invalid OpenAPI spec: ${a}`))}let s=this.parseOpenAPIToContract(i);return this.contractStore.set(s.id,s),await this.memory.set(`contract-testing:contract:${s.id}`,s,{namespace:"contract-testing",persist:!0}),this.completeWorkflow(r),f(s)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async exportToOpenAPI(e){let r=v();try{this.startWorkflow(r,"export");let i=this.contractStore.get(e);if(!i)return this.failWorkflow(r,"Contract not found"),p(new Error(`Contract not found: ${e}`));let n=this.contractToOpenAPI(i);return this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async verifyConsumerContract(e,r,i){let n=[],s=[],a=i.startsWith("http://")||i.startsWith("https://");for(let o of e.endpoints){let c=`${i}${o.path}`,l=`${o.method} ${o.path}`;if(a)try{let d=await this.verifyEndpoint(c,o.method,o);d.success?d.warning&&s.push({endpoint:l,message:d.warning,severity:"low"}):n.push({endpoint:l,type:d.errorType,expected:d.expected,actual:d.actual,message:d.message})}catch(d){n.push({endpoint:l,type:"connection-error",expected:"reachable",actual:"error",message:`Failed to verify endpoint: ${T(d)}`})}else i||n.push({endpoint:l,type:"connection-error",expected:"reachable",actual:"unreachable",message:`Endpoint ${l} is not reachable (no provider URL)`})}return{contractId:e.id,provider:e.provider.name,consumer:r,passed:n.length===0,failures:n,warnings:s,timestamp:new Date}}async verifyEndpoint(e,r,i){let s={timeout:1e4,retries:1,circuitBreaker:!1},a;switch(r){case"GET":case"HEAD":a=await this.httpClient.get(e,s);break;case"POST":a=await this.httpClient.post(e,{},s);break;case"PUT":a=await this.httpClient.put(e,{},s);break;case"PATCH":a=await this.httpClient.patch(e,{},s);break;case"DELETE":a=await this.httpClient.delete(e,s);break;case"OPTIONS":a=await this.httpClient.get(e,s);break;default:a=await this.httpClient.get(e,s)}if(!a.success)return{success:!1,errorType:"connection-error",expected:"successful response",actual:`error: ${a.error.message}`,message:`Endpoint unreachable: ${a.error.message}`};let o=a.value;if(i.examples&&i.examples.length>0){let d=i.examples.map(m=>m.statusCode);if(!d.includes(o.status))return{success:!1,errorType:"status-mismatch",expected:d.join(" or "),actual:String(o.status),message:`Expected status ${d.join("/")} but got ${o.status}`}}let c,l=o.headers.get("Deprecation");return l&&(c=`Endpoint is deprecated: ${l}`),{success:!0,errorType:"",expected:"",actual:"",message:"Endpoint verified successfully",warning:c}}async findContractsByProvider(e){let r=[],i=Array.from(this.contractStore.values());for(let s of i)s.provider.name===e&&r.push(s);let n=await this.memory.search("contract-testing:contract:*",100);for(let s of n){let a=await this.memory.get(s);a&&a.provider.name===e&&(this.contractStore.has(a.id)||r.push(a))}return r}async loadContractFromPath(e){let r=await this.loadFileContent(e);if(!r)return null;try{let i=e.value.toLowerCase();if(i.endsWith(".json")){let n=E(r);return n.openapi||n.swagger?this.parseOpenAPIToContract(r):n}else if(i.endsWith(".yaml")||i.endsWith(".yml"))return Z.warn("YAML contract files not yet supported:"),null;return E(r)}catch(i){return Z.error(`Failed to parse contract from ${e.value}: ${T(i)}`),null}}async loadFileContent(e){let r=await this.fileReader.readFile(e.value);return r.success?r.value:(Z.error(`Failed to read file ${e.value}:`,r.error),null)}parseOpenAPIToContract(e){let r=E(e),i=r.info||{},n=r.paths||{},s=[],a=[];for(let[l,d]of Object.entries(n)){let m=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let g of m){let h=d[g.toLowerCase()];h&&s.push({path:l,method:g,requestSchema:this.extractRequestSchema(h),responseSchema:this.extractResponseSchema(h),headers:{},examples:[]})}}let c=(r.components||{}).schemas||{};for(let[l,d]of Object.entries(c))a.push({id:l,name:l,type:"openapi",content:JSON.stringify(d)});return{id:v(),name:i.title||"Imported Contract",version:zt.parse(i.version||"1.0.0"),type:"rest",provider:{name:i.title||"Unknown Provider",version:i.version||"1.0.0"},consumers:[],endpoints:s,schemas:a}}extractRequestSchema(e){let r=e.requestBody;if(r){let i=r.content;if(i){let n=i["application/json"];if(n?.schema){let s=n.schema.$ref;if(s)return s.split("/").pop()}}}}extractResponseSchema(e){let r=e.responses;if(r){let i=r[200]||r[201];if(i){let n=i.content;if(n){let s=n["application/json"];if(s?.schema){let a=s.schema.$ref;if(a)return a.split("/").pop()}}}}}contractToOpenAPI(e){let r={};for(let s of e.endpoints){r[s.path]||(r[s.path]={});let a={summary:`${s.method} ${s.path}`,responses:{200:{description:"Success",content:s.responseSchema?{"application/json":{schema:{$ref:`#/components/schemas/${s.responseSchema}`}}}:void 0}}};s.requestSchema&&(a.requestBody={content:{"application/json":{schema:{$ref:`#/components/schemas/${s.requestSchema}`}}}}),r[s.path][s.method.toLowerCase()]=a}let i={};for(let s of e.schemas)try{i[s.id]=E(s.content)}catch{i[s.id]={type:"object"}}let n={openapi:"3.0.3",info:{title:e.name,version:e.version.toString()},paths:r,components:{schemas:i}};return JSON.stringify(n,null,2)}async spawnVerificationAgent(e,r){let i={name:`contract-verifier-${e.slice(0,8)}`,domain:"contract-testing",type:"validator",capabilities:["contract-verification","http-testing"],config:{workflowId:e,providerName:r}};return this.agentCoordinator.spawn(i)}async publishContractRegistered(e){let r=D(pa.ContractPublished,"contract-testing",{contractId:e.id,version:e.version.toString(),provider:e.provider.name});await this.eventBus.publish(r)}async publishContractVerified(e,r,i){let n=D(pa.ContractVerified,"contract-testing",{contractId:e.id,provider:e.provider.name,consumer:r,passed:i.passed,failureCount:i.failures.length});await this.eventBus.publish(n)}async publishVerificationFailed(e,r,i){let n=D(pa.VerificationFailed,"contract-testing",{contractId:e.id,provider:e.provider.name,consumer:r,failures:i.failures.map(s=>({endpoint:s.endpoint,type:s.type,message:s.message}))});await this.eventBus.publish(n)}async publishBreakingChangeDetected(e,r,i){let n=D(pa.BreakingChangeDetected,"contract-testing",{contractId:e,changes:r,affectedConsumers:i});await this.eventBus.publish(n)}async prioritizeContracts(e,r){if(!this.sarsaAlgorithm||!this.config.enableSARSA)return f({orderedContracts:e,strategy:"default",confidence:1});if(e.length===0)return f({orderedContracts:[],strategy:"empty",confidence:1});try{let i={id:`contract-priority-${Date.now()}`,features:[r.urgency/10,r.providerLoad/100,r.consumerCount/50,e.length/100,e.filter(l=>l.version.major>=2).length/Math.max(1,e.length),e.reduce((l,d)=>l+d.endpoints.length,0)/1e3,e.reduce((l,d)=>l+d.consumers.length,0)/100,e.filter(l=>l.type==="graphql").length/Math.max(1,e.length),e.filter(l=>l.type==="rest").length/Math.max(1,e.length),e.filter(l=>l.schemas.length>5).length/Math.max(1,e.length)]},n=await this.sarsaAlgorithm.predict(i),s=[...e],a="default";switch(n.action.type){case"sequence-early":s.sort((l,d)=>{let m=l.version.major*10+l.version.minor+l.endpoints.length*.1;return d.version.major*10+d.version.minor+d.endpoints.length*.1-m}),a="high-risk-first";break;case"sequence-late":s.sort((l,d)=>{let m=l.version.major*10+l.version.minor+l.endpoints.length*.1,g=d.version.major*10+d.version.minor+d.endpoints.length*.1;return m-g}),a="low-risk-first";break;case"predict-high":s.sort((l,d)=>d.consumers.length-l.consumers.length),a="high-consumer-first";break;default:a="default";break}let o=await this.calculateOrderingReward(s,r),c=n.action;return await this.sarsaAlgorithm.train({state:i,action:c,reward:o,nextState:i,done:!0}),Z.info(`[contract-testing] SARSA prioritized ${e.length} contracts using ${a} strategy (confidence: ${n.confidence.toFixed(2)})`),f({orderedContracts:s,strategy:a,confidence:n.confidence})}catch(i){return Z.error("SARSA prioritization failed:",i instanceof Error?i:void 0),f({orderedContracts:e,strategy:"fallback",confidence:.5})}}async calculateOrderingReward(e,r){let i=.5,n=e.slice(0,Math.ceil(e.length/3)),s=n.reduce((a,o)=>a+o.consumers.length,0)/n.length;if(i+=Math.min(.3,s/50),r.urgency>7){let a=n.filter(o=>o.version.major===0).length;i+=Math.min(.2,a/n.length)}return r.providerLoad>80&&(i-=.1),Math.max(0,Math.min(1,i))}async storeContractPattern(e,r,i){if(!(!this.qesona||!this.config.enableQESONA))try{let n={id:`contract-${e.id}`,features:[e.version.major/10,e.version.minor/10,e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,e.type==="rest"?1:0,e.type==="graphql"?1:0,e.endpoints.filter(a=>a.method==="GET").length/100,e.endpoints.filter(a=>a.method==="POST").length/100,e.endpoints.filter(a=>a.responseSchema).length/100]};if(wt()&&this.qesona.isThreeLoopEnabled()){this.qesona.instantAdapt([e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,i,r?1:0,e.version.major/10]);try{if(this.qesona.recordOutcome(r?i:-i),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}let s={type:r?"validate":"reject",value:i};this.qesona.createPattern(n,s,{reward:r?i:-i,success:r,quality:i},"test-generation","contract-testing",{contractId:e.id,provider:e.provider.name,version:e.version.toString()}),Z.info(`Stored pattern for contract ${e.id} (success: ${r}, quality: ${i.toFixed(2)})`)}catch(n){Z.error("Failed to store contract pattern:",n instanceof Error?n:void 0)}}async adaptContractPatterns(e){if(!this.qesona||!this.config.enableQESONA)return{shouldValidate:!0,confidence:.5,strategy:"default"};try{let r={id:`contract-${e.id}`,features:[e.version.major/10,e.version.minor/10,e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,e.type==="rest"?1:0,e.type==="graphql"?1:0,e.endpoints.filter(n=>n.method==="GET").length/100,e.endpoints.filter(n=>n.method==="POST").length/100,e.endpoints.filter(n=>n.responseSchema).length/100]},i=await this.qesona.adaptPattern(r,"test-generation","contract-testing");if(i.success&&i.pattern){let n=i.pattern.outcome.success,s=i.pattern.action.type;return Z.info(`[contract-testing] QESONA adapted pattern for ${e.id}: shouldValidate=${n}, confidence=${i.similarity.toFixed(2)}`),{shouldValidate:n,confidence:i.similarity,strategy:s}}return{shouldValidate:!0,confidence:.5,strategy:"default"}}catch(r){return Z.error("QESONA pattern adaptation failed:",r instanceof Error?r:void 0),{shouldValidate:!0,confidence:.5,strategy:"default"}}}async handleImpactAnalysis(e){let i=e.payload.changedFiles.filter(n=>n.includes("contract")||n.includes("api")||n.includes("openapi"));i.length>0&&this.config.enableAutoVerification&&await this.memory.set(`contract-testing:pending-verification:${Date.now()}`,{changedFiles:i,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:3600})}async loadContracts(){let e=await this.memory.search("contract-testing:contract:*",100);for(let r of e){let i=await this.memory.get(r);i&&this.contractStore.set(i.id,i)}}async saveContracts(){let e=Array.from(this.contractStore.entries());for(let[r,i]of e)await this.memory.set(`contract-testing:contract:${r}`,i,{namespace:"contract-testing",persist:!0})}async verifyContractViolation(e,r){let i=V({id:v(),type:"contract-violation",confidence:r,description:`Verify contract violation: ${e.consumer} -> ${e.provider} (${e.endpoint}, ${e.type})`,payload:e,detectedBy:"contract-testing-coordinator",severity:r>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Z.info("Contract violation verified by consensus"),!0):(Z.warn(`Contract violation NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyBreakingChange(e,r){let i=V({id:v(),type:"breaking-change",confidence:r,description:`Verify breaking change: ${e.path} (${e.type}) affecting ${e.affectedConsumers.length} consumers`,payload:e,detectedBy:"contract-testing-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Z.info(`Breaking change at '${e.path}' verified by consensus`),!0):(Z.warn(`Breaking change NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifySchemaIncompatibility(e,r){let i=V({id:v(),type:"schema-incompatibility",confidence:r,description:`Verify schema incompatibility: ${e.schema}.${e.field} (expected ${e.expected}, got ${e.actual})`,payload:e,detectedBy:"contract-testing-coordinator",severity:r>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Z.info("Schema incompatibility verified by consensus"),!0):(Z.warn(`Schema incompatibility NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};A();A();H();var qy={strictMode:!1,allowAdditionalProperties:!0,maxRecursionDepth:10,inferenceMinSamples:3},ha=class{constructor(t,e={}){this.memory=t;this.config={...qy,...e}}memory;config;async validateJsonSchema(t,e){try{let r=[];this.validateValue(t,e,"",r,0);let i={isValid:r.length===0,errors:r};return f(i)}catch(r){return p(y(r))}}async validateGraphQLSchema(t){try{let e=[],r=0,i=0,n=0,s=t.split(`
2939
+ // Follow the new type specification`,s=!1;break;case"enum-change":i=`Update enum usage: ${e.description}`,n=`// Remove usage of deprecated enum value at ${e.location}`,s=!0;break;case"removed-field":i=`Remove field usage: ${e.description}`,n=`// Remove references to ${e.location}`,s=!0;break;case"response-code":i=`Update response handling: ${e.description}`,n=`// Update error handling for ${e.location}`,s=!1;break;case"removed-endpoint":i=`Migrate from removed endpoint: ${e.description}`,n=e.migrationPath?`// ${e.migrationPath}`:`// Find alternative for ${e.location}`,s=!1;break;default:i=e.description,n=void 0,s=!1}return{order:t,description:i,codeChanges:n,automated:s}}estimateEffort(t){if(t.length===0)return"trivial";let e=t.filter(i=>i.impact==="high").length,r=t.filter(i=>i.impact==="medium").length;return e>5||t.length>10?"major":e>2||r>5?"moderate":e>0||t.length>3?"minor":"trivial"}async storeComparisonResult(t,e,r){let i=`contract-testing:comparison:${t.id}:${t.version.toString()}:${e.version.toString()}`;await this.memory.set(i,{oldVersion:t.version.toString(),newVersion:e.version.toString(),isCompatible:r.isCompatible,breakingChangeCount:r.breakingChanges.length,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400*90})}};var zy={stateSize:10,actionSize:4,hiddenLayers:[128,128],minReplaySize:100},ma=class extends ae{qNetwork;replayBufferClass;sarsaConfig;actions=[];constructor(t={}){super("sarsa","value-based"),this.sarsaConfig={...zy,...t},this.initializeActions(),this.qNetwork=new q({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.replayBufferClass=new Ke(this.config.replayBufferSize,!1)}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.qNetwork.forward(e),i=this.argmax(r),n=this.actions[i];return{action:n,confidence:.7,value:r[i],reasoning:`SARSA: ${n.type}`}}async trainCore(t){for(let i of t)this.replayBufferClass.add(i);if(!this.replayBufferClass.isReady(this.sarsaConfig.minReplaySize))return this.getStats();let e=this.replayBufferClass.sample(this.config.batchSize),r=0;for(let i=0;i<e.length;i++){let n=e[i],s=e[i+1],a=this.prepareState(n.state),o=this.actionToIndex(n.action),c=this.qNetwork.forward(a),l=c[o],d=0;if(s&&!n.done){let h=this.prepareState(s.state),b=this.actionToIndex(s.action);d=this.qNetwork.forward(h)[b]}let m=n.reward+this.config.discountFactor*d,g=new Float32Array(c.length);for(let h=0;h<g.length;h++)g[h]=h===o?m:c[h];r+=Math.abs(this.qNetwork.train(a,g,new fe))}return{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/e.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural SARSA for Defect Prediction Sequencing",capabilities:["On-policy learning","Neural Q-network"],hyperparameters:{stateSize:this.sarsaConfig.stateSize,actionSize:this.sarsaConfig.actionSize,hiddenLayers:this.sarsaConfig.hiddenLayers.join(",")},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.sarsaConfig.stateSize);for(;e.length<this.sarsaConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]/=r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"predict-high",value:1},{type:"predict-low",value:0},{type:"sequence-early",value:"high-risk"},{type:"sequence-late",value:"low-risk"}],this.sarsaConfig.actionSize=this.actions.length,this.qNetwork=new q({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate})}actionToIndex(t){let e=`${t.type}:${JSON.stringify(t.value)}`;for(let r=0;r<this.actions.length;r++)if(`${this.actions[r].type}:${JSON.stringify(this.actions[r].value)}`===e)return r;return 0}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}async exportCustomData(){return{qNetwork:this.qNetwork.getParameters(),sarsaConfig:this.sarsaConfig}}async importCustomData(t){t.qNetwork&&this.qNetwork.setParameters(t.qNetwork),t.sarsaConfig&&(this.sarsaConfig={...this.sarsaConfig,...t.sarsaConfig}),this.initialized=!0}async resetAlgorithm(){this.qNetwork=new q({layerSizes:[this.sarsaConfig.stateSize,...this.sarsaConfig.hiddenLayers,this.sarsaConfig.actionSize],activations:Array(this.sarsaConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.config.learningRate}),this.replayBufferClass.clear()}};qe();H();var pa={ContractVerified:"contract-testing.ContractVerified",BreakingChangeDetected:"contract-testing.BreakingChangeDetected",ContractPublished:"contract-testing.ContractPublished",ConsumerContractCreated:"contract-testing.ConsumerContractCreated",VerificationFailed:"contract-testing.VerificationFailed"},By={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},ee=R.create("contract-testing"),ga=class extends Q{constructor(e,r,i,n={}){let s={...By,...n};super(e,"contract-testing",s,{verifyFindingTypes:["contract-violation","breaking-change","schema-incompatibility"]});this.memory=r;this.agentCoordinator=i;this.contractValidator=new Tr({memory:r}),this.apiCompatibility=new Ar(r),this.httpClient=_i(),this.fileReader=new De}memory;agentCoordinator;contractValidator;apiCompatibility;httpClient;fileReader;contractStore=new Map;sarsaAlgorithm;qesona;async onInitialize(){if(this.config.enableSARSA)try{this.sarsaAlgorithm=new ma({stateSize:10,actionSize:4,hiddenLayers:[64,64]}),ee.info("SARSA algorithm created successfully")}catch(e){throw ee.error("Failed to create SARSA:",e instanceof Error?e:void 0),new Error(`SARSA creation failed: ${T(e)}`)}if(this.config.enableQESONA)try{this.qesona=await me({domain:"contract-testing",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),ee.info("PersistentSONAEngine initialized successfully")}catch(e){ee.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),ee.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadContracts()}async onDispose(){await this.saveContracts(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.sarsaAlgorithm=void 0,this.contractStore.clear()}subscribeToEvents(){this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async registerContract(e){try{let r=await this.contractValidator.validateContract(e);if(!r.success)return r;if(!r.value.isValid){let i=r.value.errors.map(n=>n.message).join("; ");return p(new Error(`Contract validation failed: ${i}`))}return this.contractStore.set(e.id,e),await this.memory.set(`contract-testing:contract:${e.id}`,e,{namespace:"contract-testing",persist:!0}),this.config.publishEvents&&await this.publishContractRegistered(e),f(e.id)}catch(r){return p(y(r))}}async verifyAllConsumers(e,r){let i=v();try{if(this.startWorkflow(i,"verify"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ee.warn("Topology degraded, using conservative verification strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Contract verification paused: topology is in critical state"));let n=await this.findContractsByProvider(e);if(n.length===0)return this.completeWorkflow(i),f({provider:e,totalConsumers:0,passedConsumers:0,failedConsumers:[],results:[],canDeploy:!0});if(this.config.enableSARSA&&n.length>1){let d={urgency:5,providerLoad:50,consumerCount:n.reduce((g,h)=>g+h.consumers.length,0)},m=await this.prioritizeContracts(n,d);m.success&&(n=m.value.orderedContracts,ee.info(`[contract-testing] Using ${m.value.strategy} strategy for contract verification order (confidence: ${m.value.confidence.toFixed(2)})`))}let s=await this.spawnVerificationAgent(i,e);if(!s.success)return this.failWorkflow(i,s.error.message),s;this.addAgentToWorkflow(i,s.value);let a=[],o=[];for(let d of n){for(let m of d.consumers){let g=await this.verifyConsumerContract(d,m.name,r);a.push(g),g.passed?this.config.publishEvents&&await this.publishContractVerified(d,m.name,g):(o.push(m.name),this.config.publishEvents&&await this.publishVerificationFailed(d,m.name,g))}this.updateWorkflowProgress(i,a.length/n.length*100)}await this.agentCoordinator.stop(s.value),this.completeWorkflow(i);let c=Array.from(new Set(o)),l=n.flatMap(d=>d.consumers.map(m=>m.name)).filter(d=>!c.includes(d)).length;return f({provider:e,totalConsumers:n.reduce((d,m)=>d+m.consumers.length,0),passedConsumers:l,failedConsumers:c,results:a,canDeploy:c.length===0})}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async preReleaseCheck(e,r){let i=v();try{if(this.startWorkflow(i,"compare"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ee.warn("Topology degraded, using conservative pre-release check"),this.minCutMixin.shouldPauseOperations())return p(new Error("Pre-release check paused: topology is in critical state"));let n=await this.loadContractFromPath(r);if(!n)return this.failWorkflow(i,"Failed to load contract from path"),p(new Error("Failed to load contract from path"));let s=await this.findContractsByProvider(e),a=s.length>0?s[0]:null;if(!a)return this.completeWorkflow(i),f({breakingChanges:[],affectedConsumers:[],canRelease:!0,recommendations:["No existing contract found. This will be the first version."]});let o=await this.apiCompatibility.compareVersions(a,n);if(!o.success)return this.failWorkflow(i,o.error.message),o;let{breakingChanges:c,deprecations:l}=o.value,d=[];for(let g of a.consumers){let h=c.filter(b=>b.affectedConsumers.includes(g.name));h.length>0&&d.push({name:g.name,team:g.team,breakingChanges:h,notified:!1})}let m=[];if(c.length>0){m.push(`${c.length} breaking changes detected. Coordinate with affected consumers before release.`);let g=await this.apiCompatibility.generateMigrationGuide(c);g.success&&m.push(`Migration effort estimated as: ${g.value.estimatedEffort}`)}return l.length>0&&m.push(`${l.length} deprecations detected. Consider communicating removal timeline.`),c.length===0&&l.length===0&&m.push("No breaking changes detected. Safe to release."),this.config.publishEvents&&c.length>0&&await this.publishBreakingChangeDetected(n.id,c,d.map(g=>g.name)),this.completeWorkflow(i),f({breakingChanges:c,affectedConsumers:d,canRelease:c.length===0,recommendations:m})}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async importFromOpenAPI(e){let r=v();try{this.startWorkflow(r,"import");let i=await this.loadFileContent(e);if(!i)return this.failWorkflow(r,"Failed to load OpenAPI spec"),p(new Error("Failed to load OpenAPI spec"));let n=await this.contractValidator.validateOpenAPI(i);if(!n.success)return this.failWorkflow(r,n.error.message),n;if(!n.value.isValid){let a=n.value.errors.map(o=>o.message).join("; ");return this.failWorkflow(r,a),p(new Error(`Invalid OpenAPI spec: ${a}`))}let s=this.parseOpenAPIToContract(i);return this.contractStore.set(s.id,s),await this.memory.set(`contract-testing:contract:${s.id}`,s,{namespace:"contract-testing",persist:!0}),this.completeWorkflow(r),f(s)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async exportToOpenAPI(e){let r=v();try{this.startWorkflow(r,"export");let i=this.contractStore.get(e);if(!i)return this.failWorkflow(r,"Contract not found"),p(new Error(`Contract not found: ${e}`));let n=this.contractToOpenAPI(i);return this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async verifyConsumerContract(e,r,i){let n=[],s=[],a=i.startsWith("http://")||i.startsWith("https://");for(let o of e.endpoints){let c=`${i}${o.path}`,l=`${o.method} ${o.path}`;if(a)try{let d=await this.verifyEndpoint(c,o.method,o);d.success?d.warning&&s.push({endpoint:l,message:d.warning,severity:"low"}):n.push({endpoint:l,type:d.errorType,expected:d.expected,actual:d.actual,message:d.message})}catch(d){n.push({endpoint:l,type:"connection-error",expected:"reachable",actual:"error",message:`Failed to verify endpoint: ${T(d)}`})}else i||n.push({endpoint:l,type:"connection-error",expected:"reachable",actual:"unreachable",message:`Endpoint ${l} is not reachable (no provider URL)`})}return{contractId:e.id,provider:e.provider.name,consumer:r,passed:n.length===0,failures:n,warnings:s,timestamp:new Date}}async verifyEndpoint(e,r,i){let s={timeout:1e4,retries:1,circuitBreaker:!1},a;switch(r){case"GET":case"HEAD":a=await this.httpClient.get(e,s);break;case"POST":a=await this.httpClient.post(e,{},s);break;case"PUT":a=await this.httpClient.put(e,{},s);break;case"PATCH":a=await this.httpClient.patch(e,{},s);break;case"DELETE":a=await this.httpClient.delete(e,s);break;case"OPTIONS":a=await this.httpClient.get(e,s);break;default:a=await this.httpClient.get(e,s)}if(!a.success)return{success:!1,errorType:"connection-error",expected:"successful response",actual:`error: ${a.error.message}`,message:`Endpoint unreachable: ${a.error.message}`};let o=a.value;if(i.examples&&i.examples.length>0){let d=i.examples.map(m=>m.statusCode);if(!d.includes(o.status))return{success:!1,errorType:"status-mismatch",expected:d.join(" or "),actual:String(o.status),message:`Expected status ${d.join("/")} but got ${o.status}`}}let c,l=o.headers.get("Deprecation");return l&&(c=`Endpoint is deprecated: ${l}`),{success:!0,errorType:"",expected:"",actual:"",message:"Endpoint verified successfully",warning:c}}async findContractsByProvider(e){let r=[],i=Array.from(this.contractStore.values());for(let s of i)s.provider.name===e&&r.push(s);let n=await this.memory.search("contract-testing:contract:*",100);for(let s of n){let a=await this.memory.get(s);a&&a.provider.name===e&&(this.contractStore.has(a.id)||r.push(a))}return r}async loadContractFromPath(e){let r=await this.loadFileContent(e);if(!r)return null;try{let i=e.value.toLowerCase();if(i.endsWith(".json")){let n=E(r);return n.openapi||n.swagger?this.parseOpenAPIToContract(r):n}else if(i.endsWith(".yaml")||i.endsWith(".yml"))return ee.warn("YAML contract files not yet supported:"),null;return E(r)}catch(i){return ee.error(`Failed to parse contract from ${e.value}: ${T(i)}`),null}}async loadFileContent(e){let r=await this.fileReader.readFile(e.value);return r.success?r.value:(ee.error(`Failed to read file ${e.value}:`,r.error),null)}parseOpenAPIToContract(e){let r=E(e),i=r.info||{},n=r.paths||{},s=[],a=[];for(let[l,d]of Object.entries(n)){let m=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];for(let g of m){let h=d[g.toLowerCase()];h&&s.push({path:l,method:g,requestSchema:this.extractRequestSchema(h),responseSchema:this.extractResponseSchema(h),headers:{},examples:[]})}}let c=(r.components||{}).schemas||{};for(let[l,d]of Object.entries(c))a.push({id:l,name:l,type:"openapi",content:JSON.stringify(d)});return{id:v(),name:i.title||"Imported Contract",version:zt.parse(i.version||"1.0.0"),type:"rest",provider:{name:i.title||"Unknown Provider",version:i.version||"1.0.0"},consumers:[],endpoints:s,schemas:a}}extractRequestSchema(e){let r=e.requestBody;if(r){let i=r.content;if(i){let n=i["application/json"];if(n?.schema){let s=n.schema.$ref;if(s)return s.split("/").pop()}}}}extractResponseSchema(e){let r=e.responses;if(r){let i=r[200]||r[201];if(i){let n=i.content;if(n){let s=n["application/json"];if(s?.schema){let a=s.schema.$ref;if(a)return a.split("/").pop()}}}}}contractToOpenAPI(e){let r={};for(let s of e.endpoints){r[s.path]||(r[s.path]={});let a={summary:`${s.method} ${s.path}`,responses:{200:{description:"Success",content:s.responseSchema?{"application/json":{schema:{$ref:`#/components/schemas/${s.responseSchema}`}}}:void 0}}};s.requestSchema&&(a.requestBody={content:{"application/json":{schema:{$ref:`#/components/schemas/${s.requestSchema}`}}}}),r[s.path][s.method.toLowerCase()]=a}let i={};for(let s of e.schemas)try{i[s.id]=E(s.content)}catch{i[s.id]={type:"object"}}let n={openapi:"3.0.3",info:{title:e.name,version:e.version.toString()},paths:r,components:{schemas:i}};return JSON.stringify(n,null,2)}async spawnVerificationAgent(e,r){let i={name:`contract-verifier-${e.slice(0,8)}`,domain:"contract-testing",type:"validator",capabilities:["contract-verification","http-testing"],config:{workflowId:e,providerName:r}};return this.agentCoordinator.spawn(i)}async publishContractRegistered(e){let r=D(pa.ContractPublished,"contract-testing",{contractId:e.id,version:e.version.toString(),provider:e.provider.name});await this.eventBus.publish(r)}async publishContractVerified(e,r,i){let n=D(pa.ContractVerified,"contract-testing",{contractId:e.id,provider:e.provider.name,consumer:r,passed:i.passed,failureCount:i.failures.length});await this.eventBus.publish(n)}async publishVerificationFailed(e,r,i){let n=D(pa.VerificationFailed,"contract-testing",{contractId:e.id,provider:e.provider.name,consumer:r,failures:i.failures.map(s=>({endpoint:s.endpoint,type:s.type,message:s.message}))});await this.eventBus.publish(n)}async publishBreakingChangeDetected(e,r,i){let n=D(pa.BreakingChangeDetected,"contract-testing",{contractId:e,changes:r,affectedConsumers:i});await this.eventBus.publish(n)}async prioritizeContracts(e,r){if(!this.sarsaAlgorithm||!this.config.enableSARSA)return f({orderedContracts:e,strategy:"default",confidence:1});if(e.length===0)return f({orderedContracts:[],strategy:"empty",confidence:1});try{let i={id:`contract-priority-${Date.now()}`,features:[r.urgency/10,r.providerLoad/100,r.consumerCount/50,e.length/100,e.filter(l=>l.version.major>=2).length/Math.max(1,e.length),e.reduce((l,d)=>l+d.endpoints.length,0)/1e3,e.reduce((l,d)=>l+d.consumers.length,0)/100,e.filter(l=>l.type==="graphql").length/Math.max(1,e.length),e.filter(l=>l.type==="rest").length/Math.max(1,e.length),e.filter(l=>l.schemas.length>5).length/Math.max(1,e.length)]},n=await this.sarsaAlgorithm.predict(i),s=[...e],a="default";switch(n.action.type){case"sequence-early":s.sort((l,d)=>{let m=l.version.major*10+l.version.minor+l.endpoints.length*.1;return d.version.major*10+d.version.minor+d.endpoints.length*.1-m}),a="high-risk-first";break;case"sequence-late":s.sort((l,d)=>{let m=l.version.major*10+l.version.minor+l.endpoints.length*.1,g=d.version.major*10+d.version.minor+d.endpoints.length*.1;return m-g}),a="low-risk-first";break;case"predict-high":s.sort((l,d)=>d.consumers.length-l.consumers.length),a="high-consumer-first";break;default:a="default";break}let o=await this.calculateOrderingReward(s,r),c=n.action;return await this.sarsaAlgorithm.train({state:i,action:c,reward:o,nextState:i,done:!0}),ee.info(`[contract-testing] SARSA prioritized ${e.length} contracts using ${a} strategy (confidence: ${n.confidence.toFixed(2)})`),f({orderedContracts:s,strategy:a,confidence:n.confidence})}catch(i){return ee.error("SARSA prioritization failed:",i instanceof Error?i:void 0),f({orderedContracts:e,strategy:"fallback",confidence:.5})}}async calculateOrderingReward(e,r){let i=.5,n=e.slice(0,Math.ceil(e.length/3)),s=n.reduce((a,o)=>a+o.consumers.length,0)/n.length;if(i+=Math.min(.3,s/50),r.urgency>7){let a=n.filter(o=>o.version.major===0).length;i+=Math.min(.2,a/n.length)}return r.providerLoad>80&&(i-=.1),Math.max(0,Math.min(1,i))}async storeContractPattern(e,r,i){if(!(!this.qesona||!this.config.enableQESONA))try{let n={id:`contract-${e.id}`,features:[e.version.major/10,e.version.minor/10,e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,e.type==="rest"?1:0,e.type==="graphql"?1:0,e.endpoints.filter(a=>a.method==="GET").length/100,e.endpoints.filter(a=>a.method==="POST").length/100,e.endpoints.filter(a=>a.responseSchema).length/100]};if(wt()&&this.qesona.isThreeLoopEnabled()){this.qesona.instantAdapt([e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,i,r?1:0,e.version.major/10]);try{if(this.qesona.recordOutcome(r?i:-i),this.qesona.shouldConsolidate())try{this.qesona.backgroundConsolidate()}catch{}}catch{}}let s={type:r?"validate":"reject",value:i};this.qesona.createPattern(n,s,{reward:r?i:-i,success:r,quality:i},"test-generation","contract-testing",{contractId:e.id,provider:e.provider.name,version:e.version.toString()}),ee.info(`Stored pattern for contract ${e.id} (success: ${r}, quality: ${i.toFixed(2)})`)}catch(n){ee.error("Failed to store contract pattern:",n instanceof Error?n:void 0)}}async adaptContractPatterns(e){if(!this.qesona||!this.config.enableQESONA)return{shouldValidate:!0,confidence:.5,strategy:"default"};try{let r={id:`contract-${e.id}`,features:[e.version.major/10,e.version.minor/10,e.endpoints.length/100,e.consumers.length/50,e.schemas.length/50,e.type==="rest"?1:0,e.type==="graphql"?1:0,e.endpoints.filter(n=>n.method==="GET").length/100,e.endpoints.filter(n=>n.method==="POST").length/100,e.endpoints.filter(n=>n.responseSchema).length/100]},i=await this.qesona.adaptPattern(r,"test-generation","contract-testing");if(i.success&&i.pattern){let n=i.pattern.outcome.success,s=i.pattern.action.type;return ee.info(`[contract-testing] QESONA adapted pattern for ${e.id}: shouldValidate=${n}, confidence=${i.similarity.toFixed(2)}`),{shouldValidate:n,confidence:i.similarity,strategy:s}}return{shouldValidate:!0,confidence:.5,strategy:"default"}}catch(r){return ee.error("QESONA pattern adaptation failed:",r instanceof Error?r:void 0),{shouldValidate:!0,confidence:.5,strategy:"default"}}}async handleImpactAnalysis(e){let i=e.payload.changedFiles.filter(n=>n.includes("contract")||n.includes("api")||n.includes("openapi"));i.length>0&&this.config.enableAutoVerification&&await this.memory.set(`contract-testing:pending-verification:${Date.now()}`,{changedFiles:i,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:3600})}async loadContracts(){let e=await this.memory.search("contract-testing:contract:*",100);for(let r of e){let i=await this.memory.get(r);i&&this.contractStore.set(i.id,i)}}async saveContracts(){let e=Array.from(this.contractStore.entries());for(let[r,i]of e)await this.memory.set(`contract-testing:contract:${r}`,i,{namespace:"contract-testing",persist:!0})}async verifyContractViolation(e,r){let i=V({id:v(),type:"contract-violation",confidence:r,description:`Verify contract violation: ${e.consumer} -> ${e.provider} (${e.endpoint}, ${e.type})`,payload:e,detectedBy:"contract-testing-coordinator",severity:r>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ee.info("Contract violation verified by consensus"),!0):(ee.warn(`Contract violation NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyBreakingChange(e,r){let i=V({id:v(),type:"breaking-change",confidence:r,description:`Verify breaking change: ${e.path} (${e.type}) affecting ${e.affectedConsumers.length} consumers`,payload:e,detectedBy:"contract-testing-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ee.info(`Breaking change at '${e.path}' verified by consensus`),!0):(ee.warn(`Breaking change NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifySchemaIncompatibility(e,r){let i=V({id:v(),type:"schema-incompatibility",confidence:r,description:`Verify schema incompatibility: ${e.schema}.${e.field} (expected ${e.expected}, got ${e.actual})`,payload:e,detectedBy:"contract-testing-coordinator",severity:r>.85?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ee.info("Schema incompatibility verified by consensus"),!0):(ee.warn(`Schema incompatibility NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};A();A();H();var qy={strictMode:!1,allowAdditionalProperties:!0,maxRecursionDepth:10,inferenceMinSamples:3},ha=class{constructor(t,e={}){this.memory=t;this.config={...qy,...e}}memory;config;async validateJsonSchema(t,e){try{let r=[];this.validateValue(t,e,"",r,0);let i={isValid:r.length===0,errors:r};return f(i)}catch(r){return p(y(r))}}async validateGraphQLSchema(t){try{let e=[],r=0,i=0,n=0,s=t.split(`
2940
2940
  `),a=!1,o=!1,c=!1,l=0;for(let d=0;d<s.length;d++){let m=s[d].trim();if(!(m.startsWith("#")||m==="")){if(m.startsWith("type ")){let g=m.split(/\s+/)[1]?.replace(/{.*/,"").trim();g==="Query"?o=!0:g==="Mutation"?c=!0:r++,a=!0}l+=(m.match(/{/g)||[]).length,l-=(m.match(/}/g)||[]).length,o&&m.includes(":")&&!m.startsWith("type")&&i++,c&&m.includes(":")&&!m.startsWith("type")&&n++,l===0&&a&&(a=!1,o=!1,c=!1),m.includes("::")&&e.push({message:"Invalid double colon in type definition",locations:[{line:d+1,column:m.indexOf("::")+1}]})}}return l!==0&&e.push({message:"Unbalanced braces in schema",locations:[{line:s.length,column:1}]}),!t.includes("type Query")&&!t.includes("schema {")&&e.push({message:"GraphQL schema must have a Query type or schema definition",locations:[{line:1,column:1}]}),f({isValid:e.length===0,errors:e,typeCount:r,queryCount:i,mutationCount:n})}catch(e){return p(y(e))}}async compareSchemas(t,e){try{let r=[],i=[],n=[];if(t.type!==e.type)return f({isCompatible:!1,additions:[],removals:[],modifications:[{path:"type",oldType:t.type,newType:e.type,isBreaking:!0}]});switch(t.type){case"json-schema":case"openapi":this.compareJsonSchemas(t.content,e.content,r,i,n);break;case"graphql":this.compareGraphQLSchemas(t.content,e.content,r,i,n);break;case"protobuf":this.compareProtobufSchemas(t.content,e.content,r,i,n);break;case"avro":this.compareAvroSchemas(t.content,e.content,r,i,n);break}let s=n.some(a=>a.isBreaking)||i.length>0;return await this.storeComparisonResult(t,e,{isCompatible:!s,additions:r,removals:i,modifications:n}),f({isCompatible:!s,additions:r,removals:i,modifications:n})}catch(r){return p(y(r))}}async inferSchema(t){try{if(t.length===0)return p(new Error("At least one sample is required for schema inference"));t.length<this.config.inferenceMinSamples;let e=this.inferFromSamples(t),r={id:`inferred-${v().slice(0,8)}`,name:"InferredSchema",type:"json-schema",content:JSON.stringify(e,null,2)};return await this.memory.set(`contract-testing:schema:${r.id}`,r,{namespace:"contract-testing"}),f(r)}catch(e){return p(y(e))}}validateValue(t,e,r,i,n){if(n>this.config.maxRecursionDepth){i.push({path:r,keyword:"maxDepth",message:"Maximum recursion depth exceeded",params:{maxDepth:this.config.maxRecursionDepth}});return}if(t===null){if(e.nullable===!0||e.type==="null")return;this.config.strictMode&&i.push({path:r,keyword:"type",message:"Value cannot be null",params:{}});return}let s=e.type;if(e.oneOf){this.validateOneOf(t,e.oneOf,r,i,n);return}if(e.anyOf){this.validateAnyOf(t,e.anyOf,r,i,n);return}if(e.allOf){this.validateAllOf(t,e.allOf,r,i,n);return}if(s){let a=Array.isArray(s)?s:[s],o=this.getJsonType(t);if(!a.some(c=>this.typesMatch(o,c))){i.push({path:r,keyword:"type",message:`Expected type '${a.join(" | ")}' but got '${o}'`,params:{expectedType:a,actualType:o}});return}}if(typeof t=="object"&&t!==null&&!Array.isArray(t)?this.validateObject(t,e,r,i,n):Array.isArray(t)?this.validateArray(t,e,r,i,n):typeof t=="string"?this.validateString(t,e,r,i):typeof t=="number"&&this.validateNumber(t,e,r,i),e.enum){let a=e.enum;a.includes(t)||i.push({path:r,keyword:"enum",message:`Value must be one of: ${a.map(o=>JSON.stringify(o)).join(", ")}`,params:{allowedValues:a}})}"const"in e&&t!==e.const&&i.push({path:r,keyword:"const",message:`Value must be ${JSON.stringify(e.const)}`,params:{expected:e.const}})}validateObject(t,e,r,i,n){let s=e.properties||{},a=e.required||[],o=e.additionalProperties;for(let l of a)l in t||i.push({path:r?`${r}.${l}`:l,keyword:"required",message:`Required property '${l}' is missing`,params:{missingProperty:l}});for(let[l,d]of Object.entries(t)){let m=r?`${r}.${l}`:l;l in s?this.validateValue(d,s[l],m,i,n+1):this.config.strictMode&&o===!1?i.push({path:m,keyword:"additionalProperties",message:`Property '${l}' is not allowed`,params:{additionalProperty:l}}):typeof o=="object"&&this.validateValue(d,o,m,i,n+1)}let c=Object.keys(t).length;typeof e.minProperties=="number"&&c<e.minProperties&&i.push({path:r,keyword:"minProperties",message:`Object must have at least ${e.minProperties} properties`,params:{limit:e.minProperties,actual:c}}),typeof e.maxProperties=="number"&&c>e.maxProperties&&i.push({path:r,keyword:"maxProperties",message:`Object must have at most ${e.maxProperties} properties`,params:{limit:e.maxProperties,actual:c}})}validateArray(t,e,r,i,n){let s=e.items;if(s)for(let a=0;a<t.length;a++)this.validateValue(t[a],s,`${r}[${a}]`,i,n+1);if(typeof e.minItems=="number"&&t.length<e.minItems&&i.push({path:r,keyword:"minItems",message:`Array must have at least ${e.minItems} items`,params:{limit:e.minItems,actual:t.length}}),typeof e.maxItems=="number"&&t.length>e.maxItems&&i.push({path:r,keyword:"maxItems",message:`Array must have at most ${e.maxItems} items`,params:{limit:e.maxItems,actual:t.length}}),e.uniqueItems===!0){let a=new Set;for(let o=0;o<t.length;o++){let c=JSON.stringify(t[o]);a.has(c)&&i.push({path:`${r}[${o}]`,keyword:"uniqueItems",message:"Array items must be unique",params:{duplicateIndex:o}}),a.add(c)}}}validateString(t,e,r,i){if(typeof e.minLength=="number"&&t.length<e.minLength&&i.push({path:r,keyword:"minLength",message:`String must be at least ${e.minLength} characters`,params:{limit:e.minLength,actual:t.length}}),typeof e.maxLength=="number"&&t.length>e.maxLength&&i.push({path:r,keyword:"maxLength",message:`String must be at most ${e.maxLength} characters`,params:{limit:e.maxLength,actual:t.length}}),typeof e.pattern=="string"){let n=Vr(e.pattern);n&&!n.test(t)&&i.push({path:r,keyword:"pattern",message:`String must match pattern '${e.pattern}'`,params:{pattern:e.pattern}})}typeof e.format=="string"&&this.validateFormat(t,e.format,r,i)}validateNumber(t,e,r,i){if(typeof e.minimum=="number"&&(e.exclusiveMinimum===!0?t<=e.minimum&&i.push({path:r,keyword:"exclusiveMinimum",message:`Number must be greater than ${e.minimum}`,params:{limit:e.minimum,actual:t}}):t<e.minimum&&i.push({path:r,keyword:"minimum",message:`Number must be at least ${e.minimum}`,params:{limit:e.minimum,actual:t}})),typeof e.maximum=="number"&&(e.exclusiveMaximum===!0?t>=e.maximum&&i.push({path:r,keyword:"exclusiveMaximum",message:`Number must be less than ${e.maximum}`,params:{limit:e.maximum,actual:t}}):t>e.maximum&&i.push({path:r,keyword:"maximum",message:`Number must be at most ${e.maximum}`,params:{limit:e.maximum,actual:t}})),typeof e.multipleOf=="number"){let n=t%e.multipleOf;Math.abs(n)>1e-10&&i.push({path:r,keyword:"multipleOf",message:`Number must be a multiple of ${e.multipleOf}`,params:{multipleOf:e.multipleOf,actual:t}})}}validateFormat(t,e,r,i){let n=!0;switch(e){case"email":n=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t);break;case"uri":case"url":try{new URL(t)}catch{n=!1}break;case"uuid":n=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t);break;case"date":n=!isNaN(Date.parse(t))&&/^\d{4}-\d{2}-\d{2}$/.test(t);break;case"date-time":n=!isNaN(Date.parse(t));break;case"time":n=/^\d{2}:\d{2}(:\d{2})?/.test(t);break;case"ipv4":n=/^(\d{1,3}\.){3}\d{1,3}$/.test(t);break;case"ipv6":n=/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/.test(t);break;default:return}n||i.push({path:r,keyword:"format",message:`String must be a valid ${e}`,params:{format:e}})}validateOneOf(t,e,r,i,n){let s=e.reduce((a,o)=>{let c=[];return this.validateValue(t,o,r,c,n+1),a+(c.length===0?1:0)},0);s!==1&&i.push({path:r,keyword:"oneOf",message:`Value must match exactly one schema (matched ${s})`,params:{matched:s}})}validateAnyOf(t,e,r,i,n){e.some(a=>{let o=[];return this.validateValue(t,a,r,o,n+1),o.length===0})||i.push({path:r,keyword:"anyOf",message:"Value must match at least one schema",params:{}})}validateAllOf(t,e,r,i,n){for(let s of e)this.validateValue(t,s,r,i,n+1)}getJsonType(t){return t===null?"null":Array.isArray(t)?"array":typeof t=="number"?Number.isInteger(t)?"integer":"number":typeof t}typesMatch(t,e){return t===e||e==="number"&&t==="integer"}compareJsonSchemas(t,e,r,i,n){try{let s=E(t),a=E(e);this.compareSchemaObjects(s,a,"",r,i,n)}catch{n.push({path:"",oldType:"unparseable",newType:"unparseable",isBreaking:!0})}}compareSchemaObjects(t,e,r,i,n,s){let a=t.properties||{},o=e.properties||{},c=new Set(t.required||[]),l=new Set(e.required||[]);for(let m of Object.keys(a))if(!(m in o)){let g=r?`${r}.${m}`:m;n.push(g)}for(let m of Object.keys(o))if(!(m in a)){let g=r?`${r}.${m}`:m;i.push(g),l.has(m)&&s.push({path:g,oldType:"undefined",newType:"required",isBreaking:!0})}t.type!==e.type&&s.push({path:r||"root",oldType:String(t.type||"any"),newType:String(e.type||"any"),isBreaking:!0});let d=Array.from(l);for(let m of d)if(!c.has(m)&&m in a){let g=r?`${r}.${m}`:m;s.push({path:g,oldType:"optional",newType:"required",isBreaking:!0})}}compareGraphQLSchemas(t,e,r,i,n){let s=this.extractGraphQLTypes(t),a=this.extractGraphQLTypes(e);for(let o of s)a.includes(o)||i.push(`type:${o}`);for(let o of a)s.includes(o)||r.push(`type:${o}`)}extractGraphQLTypes(t){let e=[],r=/type\s+(\w+)/g,i;for(;(i=r.exec(t))!==null;)e.push(i[1]);return e}compareProtobufSchemas(t,e,r,i,n){let s=this.extractProtobufMessages(t),a=this.extractProtobufMessages(e);for(let o of s)a.includes(o)||i.push(`message:${o}`);for(let o of a)s.includes(o)||r.push(`message:${o}`)}extractProtobufMessages(t){let e=[],r=/message\s+(\w+)/g,i;for(;(i=r.exec(t))!==null;)e.push(i[1]);return e}compareAvroSchemas(t,e,r,i,n){try{let s=E(t),a=E(e);s.type!==a.type&&n.push({path:"type",oldType:String(s.type),newType:String(a.type),isBreaking:!0}),s.name!==a.name&&n.push({path:"name",oldType:String(s.name),newType:String(a.name),isBreaking:!0})}catch{n.push({path:"",oldType:"unparseable",newType:"unparseable",isBreaking:!0})}}inferFromSamples(t){if(t.length===0)return{type:"null"};let e=t.map(r=>this.inferType(r));return this.mergeTypes(e)}inferType(t){if(t===null)return{type:"null"};if(Array.isArray(t)){if(t.length===0)return{type:"array",items:{}};let e=t.map(r=>this.inferType(r));return{type:"array",items:this.mergeTypes(e)}}if(typeof t=="object"){let e={},r=[];for(let[i,n]of Object.entries(t))e[i]=this.inferType(n),n!==void 0&&r.push(i);return{type:"object",properties:e,required:r}}if(typeof t=="string"){let e=this.inferStringFormat(t);return e?{type:"string",format:e}:{type:"string"}}return typeof t=="number"?Number.isInteger(t)?{type:"integer"}:{type:"number"}:typeof t=="boolean"?{type:"boolean"}:{}}inferStringFormat(t){if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t))return"email";if(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(t))return"uuid";if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/.test(t))return"date-time";if(/^\d{4}-\d{2}-\d{2}$/.test(t))return"date";try{return new URL(t),"uri"}catch{return null}}mergeTypes(t){if(t.length===0)return{};if(t.length===1)return t[0];if(new Set(t.map(r=>r.type)).size===1){let r=t[0].type;if(r==="object"){let i=new Map,n=new Set;for(let l of t){let d=l.properties||{},m=l.required||[];for(let[g,h]of Object.entries(d))i.has(g)||i.set(g,[]),i.get(g).push(h);for(let g of m)n.add(g)}let s={},a=Array.from(i.entries());for(let[l,d]of a)s[l]=this.mergeTypes(d);let c=Array.from(n).filter(l=>t.every(d=>(d.required||[]).includes(l)));return{type:"object",properties:s,required:c}}if(r==="array"){let i=t.map(n=>n.items).filter(n=>n&&Object.keys(n).length>0);return{type:"array",items:i.length>0?this.mergeTypes(i):{}}}return t[0]}return{anyOf:t}}async storeComparisonResult(t,e,r){let i=`contract-testing:schema-comparison:${t.id}:${e.id}:${Date.now()}`;await this.memory.set(i,{oldSchemaId:t.id,newSchemaId:e.id,isCompatible:r.isCompatible,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400*30})}};var Qc=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;contractValidator=null;apiCompatibility=null;schemaValidator=null;pluginConfig;get name(){return"contract-testing"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{registerContract:this.registerContract.bind(this),verifyAllConsumers:this.verifyAllConsumers.bind(this),preReleaseCheck:this.preReleaseCheck.bind(this),importFromOpenAPI:this.importFromOpenAPI.bind(this),exportToOpenAPI:this.exportToOpenAPI.bind(this),validateContract:this.validateContract.bind(this),validateRequest:this.validateRequest.bind(this),validateResponse:this.validateResponse.bind(this),validateOpenAPI:this.validateOpenAPI.bind(this),compareVersions:this.compareVersions.bind(this),isBackwardCompatible:this.isBackwardCompatible.bind(this),checkCompatibility:this.isBackwardCompatible.bind(this),getBreakingChanges:this.getBreakingChanges.bind(this),generateMigrationGuide:this.generateMigrationGuide.bind(this),validateJsonSchema:this.validateJsonSchema.bind(this),validateGraphQLSchema:this.validateGraphQLSchema.bind(this),compareSchemas:this.compareSchemas.bind(this),inferSchema:this.inferSchema.bind(this),generateContract:this.inferSchema.bind(this),getCoordinator:()=>this.coordinator,getContractValidator:()=>this.contractValidator,getApiCompatibility:()=>this.apiCompatibility,getSchemaValidator:()=>this.schemaValidator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["validate-contract",async e=>{if(!this.contractValidator)return p(new Error("Contract validator not initialized"));let r=e.contract;return r?this.contractValidator.validateContract(r):p(new Error("Invalid validate-contract payload: missing contract"))}],["compare-versions",async e=>{if(!this.apiCompatibility)return p(new Error("API compatibility service not initialized"));let r=e.oldVersion,i=e.newVersion,n=e.oldContract,s=e.newContract;if(n&&s)return this.apiCompatibility.compareVersions(n,s);if(!r||!i)return p(new Error("Invalid compare-versions payload: missing oldVersion or newVersion"));try{let a=zt.parse(r),o=zt.parse(i),c=o.isNewerThan(a)?1:o.equals(a)?0:-1;return{success:!0,value:{oldVersion:r,newVersion:i,comparison:c}}}catch(a){return p(y(a))}}],["check-compatibility",async e=>{if(!this.apiCompatibility)return p(new Error("API compatibility service not initialized"));let r=e.provider,i=e.consumer,n=e.contract,s=e.baselineContract;return n&&s?this.apiCompatibility.isBackwardCompatible(s,n):!r||!i?p(new Error("Invalid check-compatibility payload: missing provider or consumer")):{success:!0,value:{provider:r,consumer:i,compatible:!0}}}],["generate-contract",async e=>{if(!this.schemaValidator)return p(new Error("Schema validator not initialized"));let r=e.serviceSpec,i=e.samples;return i&&i.length>0?this.schemaValidator.inferSchema(i):r?this.schemaValidator.inferSchema([r]):p(new Error("Invalid generate-contract payload: missing serviceSpec"))}]])}async onInitialize(){this.contractValidator=new Tr({memory:this.memory},this.pluginConfig.contractValidator),this.apiCompatibility=new Ar(this.memory,this.pluginConfig.apiCompatibility),this.schemaValidator=new ha(this.memory,this.pluginConfig.schemaValidator),this.coordinator=new ga(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(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"code-intelligence.ImpactAnalysisCompleted":await this.handleImpactAnalysis(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;default:break}}async registerContract(e){this.ensureInitialized();try{let r=await this.coordinator.registerContract(e);return r.success?this.trackSuccessfulOperation("register"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async verifyAllConsumers(e,r){this.ensureInitialized();try{let i=await this.coordinator.verifyAllConsumers(e,r);return i.success?this.trackSuccessfulOperation("verify"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async preReleaseCheck(e,r){this.ensureInitialized();try{return await this.coordinator.preReleaseCheck(e,r)}catch(i){return this.handleError(i)}}async importFromOpenAPI(e){this.ensureInitialized();try{return await this.coordinator.importFromOpenAPI(e)}catch(r){return this.handleError(r)}}async exportToOpenAPI(e){this.ensureInitialized();try{return await this.coordinator.exportToOpenAPI(e)}catch(r){return this.handleError(r)}}async validateContract(e){this.ensureInitialized();try{return await this.contractValidator.validateContract(e)}catch(r){return this.handleError(r)}}async validateRequest(e,r){this.ensureInitialized();try{return await this.contractValidator.validateRequest(e,r)}catch(i){return this.handleError(i)}}async validateResponse(e,r){this.ensureInitialized();try{return await this.contractValidator.validateResponse(e,r)}catch(i){return this.handleError(i)}}async validateOpenAPI(e){this.ensureInitialized();try{return await this.contractValidator.validateOpenAPI(e)}catch(r){return this.handleError(r)}}async compareVersions(e,r){this.ensureInitialized();try{return await this.apiCompatibility.compareVersions(e,r)}catch(i){return this.handleError(i)}}async isBackwardCompatible(e,r){this.ensureInitialized();try{return await this.apiCompatibility.isBackwardCompatible(e,r)}catch(i){return this.handleError(i)}}async getBreakingChanges(e,r){this.ensureInitialized();try{return await this.apiCompatibility.getBreakingChanges(e,r)}catch(i){return this.handleError(i)}}async generateMigrationGuide(e){this.ensureInitialized();try{return await this.apiCompatibility.generateMigrationGuide(e)}catch(r){return this.handleError(r)}}async validateJsonSchema(e,r){this.ensureInitialized();try{return await this.schemaValidator.validateJsonSchema(e,r)}catch(i){return this.handleError(i)}}async validateGraphQLSchema(e){this.ensureInitialized();try{return await this.schemaValidator.validateGraphQLSchema(e)}catch(r){return this.handleError(r)}}async compareSchemas(e,r){this.ensureInitialized();try{return await this.schemaValidator.compareSchemas(e,r)}catch(i){return this.handleError(i)}}async inferSchema(e){this.ensureInitialized();try{return await this.schemaValidator.inferSchema(e)}catch(r){return this.handleError(r)}}async handleImpactAnalysis(e){let r=e.payload;r.changedFiles.filter(n=>n.includes("/api/")||n.includes("/routes/")||n.includes("controller")).length>0&&await this.memory.set(`contract-testing:pending-impact:${r.analysisId}`,r,{namespace:"contract-testing",ttl:3600})}async handleQualityGate(e){let r=e.payload;r.checks.find(n=>n.name==="contract-testing")||await this.memory.set(`contract-testing:quality-gate-warning:${r.gateId}`,{warning:"Contract testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}async handlePreRelease(e){let r=e.payload,i=r.providerName||r.serviceName;if(!i){await this.memory.set(`contract-testing:pre-release-warning:${e.id}`,{warning:"Pre-release event received without provider/service name",eventId:e.id,timestamp:new Date().toISOString()},{namespace:"contract-testing",ttl:86400});return}let n=`contract-testing:pre-release:${e.id}`;if(await this.memory.set(n,{providerName:i,version:r.version,status:"pending",startedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:3600}),r.contractPath)try{let s=he.create(r.contractPath),a=await this.preReleaseCheck(i,s);if(a.success){let o=a.value;await this.memory.set(n,{providerName:i,version:r.version,status:o.canRelease?"passed":"failed",completedAt:new Date().toISOString(),breakingChanges:o.breakingChanges.length,affectedConsumers:o.affectedConsumers.length,recommendations:o.recommendations},{namespace:"contract-testing",ttl:86400}),this.eventBus.publish({id:`${e.id}-result`,type:"contract-testing.PreReleaseVerificationCompleted",source:"contract-testing",timestamp:new Date,payload:{providerName:i,version:r.version,canRelease:o.canRelease,breakingChanges:o.breakingChanges.length,affectedConsumers:o.affectedConsumers.map(c=>c.name)}})}}catch(s){await this.memory.set(n,{providerName:i,version:r.version,status:"error",error:T(s),completedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}if(r.providerUrl)try{let s=await this.verifyAllConsumers(i,r.providerUrl);if(s.success){let a=s.value;await this.memory.set(`${n}:verification`,{providerName:i,version:r.version,status:a.canDeploy?"passed":"failed",completedAt:new Date().toISOString(),totalConsumers:a.totalConsumers,passedConsumers:a.passedConsumers,failedConsumers:a.failedConsumers},{namespace:"contract-testing",ttl:86400}),this.eventBus.publish({id:`${e.id}-consumer-result`,type:"contract-testing.ConsumerVerificationCompleted",source:"contract-testing",timestamp:new Date,payload:{providerName:i,version:r.version,canDeploy:a.canDeploy,totalConsumers:a.totalConsumers,passedConsumers:a.passedConsumers,failedConsumers:a.failedConsumers}})}}catch(s){await this.memory.set(`${n}:verification`,{providerName:i,version:r.version,status:"error",error:T(s),completedAt:new Date().toISOString()},{namespace:"contract-testing",ttl:86400})}}ensureInitialized(){if(!this._initialized)throw new Error("ContractTestingPlugin is not initialized");if(!this.coordinator||!this.contractValidator||!this.apiCompatibility||!this.schemaValidator)throw new Error("ContractTestingPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function om(u,t,e,r){return new Qc(u,t,e,r)}M();A();Ki();M();A();var Gy={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},cm=R.create("visual-accessibility/visual-tester"),Kc=class{config;memory;llmRouter;vibiumClient=null;browserAvailable=null;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...Gy,...e}}setVibiumClient(t){this.vibiumClient=t,this.browserAvailable=null}getVibiumClient(){return this.vibiumClient}async isBrowserAvailable(){if(this.browserAvailable!==null)return this.browserAvailable;if(!this.vibiumClient)return this.browserAvailable=!1,!1;try{return this.browserAvailable=await this.vibiumClient.isAvailable(),this.browserAvailable}catch{return this.browserAvailable=!1,!1}}isLLMAnalysisAvailable(){return this.config.enableLLMAnalysis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}async captureScreenshot(t,e){try{let r=e?.viewport||this.config.defaultViewport,i=v(),n=new Date,s=this.hashUrl(t),a=`${r.width}x${r.height}`,o=he.create(`${this.config.baselineDirectory}/${s}_${a}_${i}.png`),c=this.estimateLoadTime(t,r),l={browser:"chromium",os:process.platform,selector:void 0,fullPage:e?.fullPage??!1,loadTime:c},d={id:i,url:t,viewport:r,timestamp:n,path:o,metadata:l};return await this.storeScreenshotMetadata(d),f(d)}catch(r){return p(y(r))}}async captureElement(t,e,r){try{let i=r?.viewport||this.config.defaultViewport,n=v(),s=new Date,a=he.create(`${this.config.baselineDirectory}/${n}.png`),o={browser:"chromium",os:process.platform,selector:e,fullPage:!1,loadTime:this.estimateLoadTime(t,i)},c={id:n,url:t,viewport:i,timestamp:s,path:a,metadata:o};return await this.storeScreenshotMetadata(c),f(c)}catch(i){return p(y(i))}}async compare(t,e){try{let r=await this.getScreenshotById(e);if(!r)return p(new Error(`Baseline not found: ${e}`));let i=this.calculateDiff(r,t);return await this.storeDiffResult(i),f(i)}catch(r){return p(y(r))}}async compareWithBrowser(t,e,r){try{let i=await this.getScreenshotById(e);if(!i)return p(new Error(`Baseline not found: ${e}`));let n=r??this.config.diffThreshold;if(this.vibiumClient&&await this.isBrowserAvailable()){let a=await this.executeBrowserComparison(i,t,n);if(a.success)return await this.storeDiffResult(a.value),a;cm.warn(`Browser comparison failed, falling back to deterministic: ${a.error.message}`)}let s=this.calculateDiff(i,t);return await this.storeDiffResult(s),f(s)}catch(i){return p(y(i))}}async executeBrowserComparison(t,e,r){if(!this.vibiumClient)return p(new Error("Vibium client not available"));try{let i=await this.vibiumClient.compareScreenshots(t.path.value,e.path.value,r/100);if(!i.success)return p(i.error);let n=i.value,s=this.convertVibiumResult(t,e,n,r);return f(s)}catch(i){return p(y(i))}}convertVibiumResult(t,e,r,i){let n=r.differencePercent,s;n===0?s="identical":n<=i?s="acceptable":n<=5?s="changed":s="failed";let a=t.viewport.width*t.viewport.height,o=Math.floor(a*n/100),c=r.diffRegions.map((d,m)=>({x:d.x,y:d.y,width:d.width,height:d.height,changeType:"modified",significance:n>2?"high":n>.5?"medium":"low"})),l=r.diffImagePath?he.create(r.diffImagePath):n>i?he.create(`${this.config.diffDirectory}/${e.id}_diff.png`):void 0;return{baselineId:t.id,comparisonId:e.id,diffPercentage:n,diffPixels:o,diffImagePath:l,regions:c,status:s}}async setBaseline(t){try{let e=this.getBaselineKey(t.url,t.viewport);return await this.memory.set(`visual-accessibility:baseline:${e}`,t,{namespace:"visual-accessibility",persist:!0}),await this.memory.set(`visual-accessibility:screenshot:${t.id}`,t,{namespace:"visual-accessibility",persist:!0}),f(e)}catch(e){return p(y(e))}}async getBaseline(t,e){let r=this.getBaselineKey(t,e);return await this.memory.get(`visual-accessibility:baseline:${r}`)??null}async analyzeDiffWithLLM(t){if(!this.isLLMAnalysisAvailable())return null;try{let e=t.regions.slice(0,5).map(i=>{let n=i.width*i.height;return`- Region at (${i.x}, ${i.y}): ${i.width}x${i.height}, ${n} pixels changed, ${i.changeType} (${i.significance} significance)`}).join(`
2941
2941
  `);return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze this visual regression diff:
2942
2942
  Screenshot: ${t.comparisonId}
@@ -3009,7 +3009,7 @@ Provide:
3009
3009
  1. Hypothesis validation likelihood
3010
3010
  2. Potential risks
3011
3011
  3. Recommended safety measures`}],maxTokens:this.config.llmMaxTokens})).content}catch{return N.warn("LLM analysis failed:"),null}}validateExperiment(t){return t.id?t.name?t.hypothesis?!t.steadyState||t.steadyState.probes.length===0?p(new Error("At least one steady state probe is required")):!t.faults||t.faults.length===0?p(new Error("At least one fault injection is required")):t.rollbackPlan?t.blastRadius.excludeProduction===!1&&!t.rollbackPlan.automatic?p(new Error("Production experiments require automatic rollback")):f(void 0):p(new Error("Rollback plan is required")):p(new Error("Experiment hypothesis is required")):p(new Error("Experiment name is required")):p(new Error("Experiment ID is required"))}validateFault(t){return t.id?t.type?t.target?t.duration<0?p(new Error("Fault duration must be non-negative")):t.probability!==void 0&&(t.probability<0||t.probability>1)?p(new Error("Fault probability must be between 0 and 1")):f(void 0):p(new Error("Fault target is required")):p(new Error("Fault type is required")):p(new Error("Fault ID is required"))}createExecution(t){return{experimentId:t.id,startTime:new Date,result:{experimentId:t.id,status:"running",startTime:new Date,hypothesisValidated:!1,steadyStateVerified:!1,faultResults:[],metrics:[],incidents:[]}}}finalizeExecution(t){t.result.endTime=new Date;let e={experimentId:t.result.experimentId,status:t.result.status,startTime:t.result.startTime,endTime:t.result.endTime,hypothesisValidated:t.result.hypothesisValidated,steadyStateVerified:t.result.steadyStateVerified,faultResults:t.result.faultResults,metrics:t.result.metrics,incidents:t.result.incidents};return this.memory.set(`chaos:results:${t.experimentId}:${Date.now()}`,e,{namespace:"chaos-resilience",persist:!0}),e}async executeProbe(t){try{switch(t.type){case"http":return await this.executeHttpProbe(t);case"tcp":return await this.executeTcpProbe(t);case"command":return await this.executeCommandProbe(t);case"metric":return await this.executeMetricProbe(t);default:return!1}}catch{return!1}}async executeHttpProbe(t){try{let e=await this.httpClient.get(t.target,{timeout:t.timeout??5e3,retries:1,circuitBreaker:!1});if(!e.success)return N.info(`HTTP probe failed: ${t.name} -> ${e.error.message}`),!1;let r=e.value;if(t.expectedStatus!==void 0){let i=r.status===t.expectedStatus;return i||N.info(`HTTP probe ${t.name}: expected status ${t.expectedStatus}, got ${r.status}`),i}return r.ok}catch(e){return N.info(`HTTP probe error: ${t.name} -> ${T(e)}`),!1}}async executeTcpProbe(t){return new Promise(e=>{try{let[r,i]=t.target.split(":"),n=parseInt(i,10);if(!r||isNaN(n)){N.info(`TCP probe invalid target: ${t.target} (expected host:port)`),e(!1);return}let s=t.timeout??5e3,a=new Tm.Socket,o=setTimeout(()=>{a.destroy(),N.info(`TCP probe timeout: ${t.name} -> ${t.target}`),e(!1)},s);a.connect(n,r,()=>{clearTimeout(o),a.destroy(),e(!0)}),a.on("error",c=>{clearTimeout(o),a.destroy(),N.info(`TCP probe error: ${t.name} -> ${c.message}`),e(!1)})}catch(r){N.info(`TCP probe exception: ${t.name} -> ${T(r)}`),e(!1)}})}static ALLOWED_PROBE_COMMANDS=["curl","wget","nc","netcat","ping","nslookup","dig","ps","pgrep","cat","head","tail","ls","stat","echo","test","[","node","npm"];async executeCommandProbe(t){return new Promise(e=>{let r=t.timeout??1e4,i=oa(t.target,u.ALLOWED_PROBE_COMMANDS);if(!i.valid){N.info(`Command probe ${t.name} blocked: ${i.error}`),N.info(`Blocked patterns: ${i.blockedPatterns?.join(", ")||"none"}`),e(!1);return}let s=(i.sanitizedCommand||t.target).trim().split(/\s+/),a=s[0],o=s.slice(1);Rm(a,o,{timeout:r},(c,l,d)=>{if(c){N.info(`Command probe failed: ${t.name} -> ${c.message}`),e(!1);return}if(t.expectedOutput!==void 0){let m=l.trim().includes(t.expectedOutput);m||N.info(`Command probe ${t.name}: output did not contain expected value`),e(m);return}e(!0)})})}async executeMetricProbe(t){try{let e=await this.httpClient.get(t.target,{timeout:t.timeout??5e3,retries:1,circuitBreaker:!1});if(!e.success)return N.info(`Metric probe failed: ${t.name} -> ${e.error.message}`),!1;let r=e.value;if(!r.ok)return N.info(`Metric probe HTTP error: ${t.name} -> ${r.status}`),!1;let i=await r.text(),n;try{let s=E(i);n=typeof s.value=="number"?s.value:parseFloat(s.value)}catch{n=parseFloat(i)}if(isNaN(n))return N.info(`Metric probe ${t.name}: could not parse metric value from response`),!1;if(t.threshold!==void 0){let{operator:s,value:a}=t.threshold;switch(s){case"lt":return n<a;case"gt":return n>a;case"lte":return n<=a;case"gte":return n>=a;case"eq":return n===a;default:return!0}}return!0}catch(e){return N.info(`Metric probe error: ${t.name} -> ${T(e)}`),!1}}async performFaultInjection(t){let r={latency:async()=>this.injectLatency(t),error:async()=>this.injectError(t),timeout:async()=>this.injectTimeout(t),"packet-loss":async()=>this.injectPacketLoss(t),"cpu-stress":async()=>this.injectCpuStress(t),"memory-stress":async()=>this.injectMemoryStress(t),"disk-stress":async()=>this.injectDiskStress(t),"network-partition":async()=>this.injectNetworkPartition(t),"dns-failure":async()=>this.injectDnsFailure(t),"process-kill":async()=>this.injectProcessKill(t)}[t.type];return r?r():p(new Error(`Unknown fault type: ${t.type}`))}async injectLatency(t){let e=t.parameters.latencyMs??100;return N.info(`Latency injection configured: ${e}ms for ${t.target.selector}`),N.info("Note: Actual latency injection requires network proxy (e.g., Toxiproxy, tc)"),f(1)}async injectError(t){let e=t.parameters.errorCode??500;return N.info(`Error injection configured: ${e} for ${t.target.selector}`),N.info("Note: Actual error injection requires service mesh (e.g., Istio, Linkerd)"),f(1)}async injectTimeout(t){return N.info(`Timeout injection configured for ${t.target.selector}`),N.info("Note: Actual timeout injection requires network proxy configuration"),f(1)}async injectPacketLoss(t){let e=t.parameters.packetLossPercent??10;return N.info(`Packet loss configured: ${e}% for ${t.target.selector}`),N.info("Note: Actual packet loss requires tc/iptables (Linux) or similar"),f(1)}async injectCpuStress(t){let e=t.parameters.cpuPercent??80,r=t.parameters.cores??1,i=t.duration;N.info(`Injecting CPU stress: ${e}% on ${r} core(s) for ${i}ms`);let n=Date.now(),s=setInterval(()=>{if(Date.now()-n>=i){clearInterval(s);return}let a=10*(e/100),o=Date.now();for(;Date.now()-o<a;)L()*L()},10);return this.stressWorkers.set(t.id,s),f(r)}async injectMemoryStress(t){let e=t.parameters.memoryBytes??104857600,r=Math.round(e/(1024*1024));N.info(`Injecting memory stress: ${r}MB allocation`);try{let n=Math.ceil(e/1048576),s=[];for(let a=0;a<n;a++){let o=Math.min(1048576,e-a*1048576),c=new Array(o).fill(L());s.push(c)}return this.stressWorkers.set(t.id,s),N.info(`Memory stress active: ${s.length} chunks allocated`),f(1)}catch(i){return p(new Error(`Failed to allocate memory: ${T(i)}`))}}async injectDiskStress(t){return N.info(`Disk stress configured for ${t.target.selector}`),N.info("Note: Actual disk stress requires file system write permissions"),f(1)}async injectNetworkPartition(t){return N.info(`Network partition configured for ${t.target.selector}`),N.info("Note: Actual network partition requires iptables/firewall rules"),f(1)}async injectDnsFailure(t){return N.info(`DNS failure configured for ${t.target.selector}`),N.info("Note: Actual DNS failure requires DNS server or /etc/hosts modification"),f(1)}async injectProcessKill(t){let e=t.target.selector;return N.info(`Process kill configured for pattern: ${e}`),N.info("Note: Actual process kill requires appropriate permissions"),this.config.enableDryRun?(N.info(`Would kill processes matching: ${e}`),f(0)):f(1)}async performFaultRemoval(t){N.info(`Removing fault: ${t.id} (${t.type})`);let e=this.stressWorkers.get(t.id);e&&(typeof e=="object"&&"unref"in e&&clearInterval(e),this.stressWorkers.delete(t.id))}async collectMetricsDuringExperiment(t,e){let r=e.hypothesis.metrics.map(s=>s.metric),i=Date.now(),n=Math.max(...e.faults.map(s=>s.duration),this.config.defaultTimeout);for(;Date.now()-i<Math.min(n,5e3);){for(let s of r){let a={timestamp:new Date,name:s,value:this.collectRealMetricValue(s),labels:{experiment:e.id}};t.result.metrics.push(a)}await this.sleep(this.config.safetyCheckInterval)}}collectRealMetricValue(t){return this.metricsCollector.getChaosMetricValue(t)}validateHypothesis(t,e){for(let r of t.metrics){let i=e.filter(s=>s.name===r.metric);if(i.length===0)return!1;let n=i.reduce((s,a)=>s+a.value,0)/i.length;if(!this.checkMetricExpectation(n,r))return!1}for(let r of t.tolerances){let i=e.filter(o=>o.name===r.metric);if(i.length===0)continue;let n=i.map(o=>o.value),s=this.calculateDeviation(n);if((r.unit==="percent"?s/n[0]*100:s)>r.maxDeviation)return!1}return!0}checkMetricExpectation(t,e){let{operator:r,value:i}=e;switch(r){case"eq":return t===i;case"lt":return t<i;case"gt":return t>i;case"lte":return t<=i;case"gte":return t>=i;case"between":let[n,s]=i;return t>=n&&t<=s;default:return!1}}calculateDeviation(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}determineExperimentStatus(t,e){return!t.result.steadyStateVerified||!e?"failed":t.result.hypothesisValidated?"completed":t.result.faultResults.filter(i=>!i.injected).length>0?"failed":"completed"}async rollbackExperiment(t){for(let e of t.rollbackPlan.steps.sort((r,i)=>r.order-i.order)){N.info(`Executing rollback step ${e.order}: ${e.action}`);try{await this.executeRollbackAction(e.action,e.target,e.timeout)}catch(r){N.error(`Rollback step ${e.order} failed: ${T(r)}`)}}for(let e of t.faults)await this.removeFault(e.id)}async executeRollbackAction(t,e,r=3e4){t.startsWith("http://")||t.startsWith("https://")?await this.executeHttpRollback(t,r):t.startsWith("cmd:")?await this.executeCommandRollback(t.slice(4),r):e&&(e.startsWith("http://")||e.startsWith("https://"))?await this.executeHttpRollback(`${e}/_chaos/${t}`,r):await this.executeBuiltInRollback(t,e,r)}async executeHttpRollback(t,e){let r=await this.httpClient.post(t,{},{timeout:e,retries:1});if(!r.success)throw new Error(`HTTP rollback failed: ${r.error.message}`)}static ALLOWED_ROLLBACK_COMMANDS=["kill","pkill","rm","rmdir","mv","cp","systemctl","service","docker","kubectl","iptables","tc","echo","true"];executeCommandRollback(t,e){return new Promise((r,i)=>{let n=oa(t,u.ALLOWED_ROLLBACK_COMMANDS);if(!n.valid){i(new Error(`Rollback command blocked: ${n.error}`));return}let a=(n.sanitizedCommand||t).trim().split(/\s+/),o=a[0],c=a.slice(1);Rm(o,c,{timeout:e},(l,d,m)=>{l?i(new Error(`Command rollback failed: ${l.message}. ${m}`)):r()})})}async executeBuiltInRollback(t,e,r){let i=t.toLowerCase();i.includes("remove")||i.includes("clear")?e&&N.info(`Clearing state for target: ${e}`):i.includes("restart")?N.info(`Restart requested for: ${e||"service"}`):i.includes("restore")?N.info(`Restore requested for: ${e||"system"}`):N.info(`Rollback action logged: ${t}`),await this.sleep(100)}sleep(t){return new Promise(e=>setTimeout(e,t))}};A();se();var Fv={defaultTimeout:3e5,maxVirtualUsers:1e3,reportingInterval:1e3,enableDetailedMetrics:!0,connectionPoolSize:100},Dr=class{constructor(t,e={}){this.memory=t;this.config={...Fv,...e},this.httpClient=new ze}memory;config;activeTests=new Map;httpClient;async createTest(t){try{let e=this.validateTest(t);return e.success?(await this.memory.set(`loadtest:tests:${t.id}`,t,{namespace:"chaos-resilience",persist:!0}),f(t.id)):p(e.error)}catch(e){return p(y(e))}}async runTest(t){try{let e=await this.memory.get(`loadtest:tests:${t}`);if(!e)return p(new Error(`Load test not found: ${t}`));if(this.activeTests.has(t))return p(new Error(`Load test ${t} is already running`));if(e.profile.virtualUsers.max>this.config.maxVirtualUsers)return p(new Error(`Virtual users (${e.profile.virtualUsers.max}) exceeds maximum (${this.config.maxVirtualUsers})`));let r=this.createExecution(e);this.activeTests.set(t,r);try{return await this.executeLoadTest(r,e),r.result.assertionResults=this.evaluateAssertions(e.assertions,r.result.summary),r.result.status=this.determineTestStatus(r.result),f(this.finalizeExecution(r))}catch(i){return r.result.status="failed",r.result.errors.push({type:"execution_error",message:T(i),count:1,firstOccurrence:new Date,lastOccurrence:new Date}),f(this.finalizeExecution(r))}finally{this.activeTests.delete(t)}}catch(e){return p(y(e))}}async stopTest(t){try{let e=this.activeTests.get(t);return e?(e.aborted=!0,e.result.status="aborted",f(this.finalizeExecution(e))):p(new Error(`No active load test found: ${t}`))}catch(e){return p(y(e))}}async getRealtimeMetrics(t){try{let e=this.activeTests.get(t);if(!e)return p(new Error(`No active load test found: ${t}`));let r=e.result.timeline[e.result.timeline.length-1];return r?f(r):p(new Error("No metrics available yet"))}catch(e){return p(y(e))}}async generateFromTraffic(t,e){try{if(t.requests.length===0)return p(new Error("Traffic sample contains no requests"));if(e<=0)return p(new Error("Multiplier must be positive"));let r=t.requests.reduce((g,h)=>g+h.frequency,0),i=t.requests.reduce((g,h)=>g+h.avgResponseTime*h.frequency,0)/r,n=t.requests.map(g=>({name:`${g.method} ${g.url}`,weight:g.frequency/r,steps:[{type:"request",target:{url:g.url,method:g.method}},{type:"think",duration:Math.max(100,i*.5)}]})),a=r/t.duration*e,o=Math.ceil(a*(i/1e3)),c={virtualUsers:{start:Math.ceil(o*.1),max:Math.min(o,this.config.maxVirtualUsers),pattern:"ramp"},duration:Math.max(6e4,t.duration*e),rampUp:3e4,rampDown:15e3},l=[{metric:"p95",operator:"lt",value:i*2},{metric:"error-rate",operator:"lt",value:5},{metric:"throughput",operator:"gte",value:a*.9}],d=e>5?"stress":"load",m={id:v(),name:`Generated from ${t.source} (${e}x)`,type:d,target:{url:t.requests[0].url,method:t.requests[0].method},profile:c,scenarios:n,assertions:l};return f(m)}catch(r){return p(y(r))}}validateTest(t){return t.id?t.name?!t.target||!t.target.url?p(new Error("Test target URL is required")):t.profile?t.profile.virtualUsers.max<=0?p(new Error("Maximum virtual users must be positive")):t.profile.duration<=0?p(new Error("Test duration must be positive")):f(void 0):p(new Error("Test profile is required")):p(new Error("Test name is required")):p(new Error("Test ID is required"))}createExecution(t){return{testId:t.id,startTime:new Date,aborted:!1,result:{testId:t.id,status:"completed",duration:0,summary:this.createEmptySummary(),timeline:[],errors:[],assertionResults:[]}}}createEmptySummary(){return{totalRequests:0,successfulRequests:0,failedRequests:0,requestsPerSecond:0,avgResponseTime:0,p50ResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,maxResponseTime:0,errorRate:0}}async executeLoadTest(t,e){let r=Date.now(),i=e.profile.duration,n=[],s=new Map,a=this.getExecutionStrategy(e.type);for(;Date.now()-r<i&&!t.aborted;){let o=Date.now()-r,c=this.calculateCurrentVirtualUsers(e.profile,o,i),l=await this.executeBatch(e,c,a);n.push(...l.responseTimes);for(let m of l.errors){let g=s.get(m);g?(g.count++,g.lastOccurrence=new Date):s.set(m,{type:"request_error",message:m,count:1,firstOccurrence:new Date,lastOccurrence:new Date})}t.result.summary.totalRequests+=l.totalRequests,t.result.summary.successfulRequests+=l.successfulRequests,t.result.summary.failedRequests+=l.failedRequests;let d={timestamp:new Date,virtualUsers:c,requestsPerSecond:l.totalRequests,avgResponseTime:l.responseTimes.length>0?l.responseTimes.reduce((m,g)=>m+g,0)/l.responseTimes.length:0,errorRate:l.totalRequests>0?l.failedRequests/l.totalRequests*100:0};t.result.timeline.push(d),await this.sleep(this.config.reportingInterval)}if(t.result.duration=Date.now()-r,t.result.errors=Array.from(s.values()),n.length>0){let o=n.sort((c,l)=>c-l);t.result.summary.avgResponseTime=o.reduce((c,l)=>c+l,0)/o.length,t.result.summary.p50ResponseTime=this.percentile(o,50),t.result.summary.p95ResponseTime=this.percentile(o,95),t.result.summary.p99ResponseTime=this.percentile(o,99),t.result.summary.maxResponseTime=o[o.length-1]}t.result.summary.requestsPerSecond=t.result.summary.totalRequests/(t.result.duration/1e3),t.result.summary.errorRate=t.result.summary.totalRequests>0?t.result.summary.failedRequests/t.result.summary.totalRequests*100:0}getExecutionStrategy(t){switch(t){case"load":return{requestMultiplier:1,errorInjectionRate:0};case"stress":return{requestMultiplier:1.5,errorInjectionRate:.01};case"spike":return{requestMultiplier:3,errorInjectionRate:.02};case"soak":return{requestMultiplier:.8,errorInjectionRate:0};case"breakpoint":return{requestMultiplier:2,errorInjectionRate:.05};default:return{requestMultiplier:1,errorInjectionRate:0}}}calculateCurrentVirtualUsers(t,e,r){let{virtualUsers:i,rampUp:n=0,rampDown:s=0}=t,{start:a,max:o,pattern:c}=i;switch(c){case"constant":return o;case"ramp":if(e<n)return Math.round(a+(o-a)*(e/n));if(e>r-s){let C=(r-e)/s;return Math.round(a+(o-a)*C)}return o;case"step":let l=5,d=r/l,m=Math.floor(e/d),g=(o-a)/l;return Math.round(a+g*m);case"spike":return e%3e4<5e3?o:a;default:return o}}async executeBatch(t,e,r){let i=Math.round(e*r.requestMultiplier),n=Math.min(i,this.config.connectionPoolSize),s=this.createBatches(i,n),a=[];for(let l of s){let d=Date.now(),m=await Promise.all(l.map(()=>this.executeRequest(t,r)));a.push(...m);let g=Date.now()-d,h=1e3/Math.max(e,1)*l.length;g<h&&await this.sleep(h-g)}let o=a.filter(l=>l.success).map(l=>l.latency),c=a.filter(l=>!l.success).map(l=>l.error||"Unknown error");return{totalRequests:a.length,successfulRequests:a.filter(l=>l.success).length,failedRequests:a.filter(l=>!l.success).length,responseTimes:o,errors:c}}async executeRequest(t,e){let r=Date.now(),i=r;if(e.errorInjectionRate>0&&L()<e.errorInjectionRate)return{status:0,latency:Date.now()-r,success:!1,error:"Simulated error injection",timestamp:i};try{let{url:n,method:s="GET",headers:a,body:o}=t.target,c={headers:a,timeout:this.config.defaultTimeout,retries:0,circuitBreaker:!1},l;switch(s.toUpperCase()){case"POST":l=await this.httpClient.post(n,o,c);break;case"PUT":l=await this.httpClient.put(n,o,c);break;case"DELETE":l=await this.httpClient.delete(n,c);break;default:l=await this.httpClient.get(n,c);break}if(l.success){let d=l.value;return{status:d.status,latency:Date.now()-r,success:d.ok,error:d.ok?void 0:`HTTP ${d.status}: ${d.statusText}`,timestamp:i}}else return{status:l.error.status??0,latency:Date.now()-r,success:!1,error:l.error.message,timestamp:i}}catch(n){return{status:0,latency:Date.now()-r,success:!1,error:T(n),timestamp:i}}}createBatches(t,e){let r=[],i=t;for(;i>0;){let n=Math.min(i,e);r.push(Array.from({length:n},(s,a)=>a)),i-=n}return r}percentile(t,e){if(t.length===0)return 0;let r=Math.ceil(e/100*t.length)-1;return t[Math.max(0,Math.min(r,t.length-1))]}evaluateAssertions(t,e){return t.map(r=>{let i=this.getMetricValue(r.metric,e),n=this.checkAssertion(r,i);return{assertion:r,passed:n,actualValue:i}})}getMetricValue(t,e){switch(t){case"response-time":return e.avgResponseTime;case"throughput":return e.requestsPerSecond;case"error-rate":return e.errorRate;case"p95":return e.p95ResponseTime;case"p99":return e.p99ResponseTime;default:return 0}}checkAssertion(t,e){switch(t.operator){case"lt":return e<t.value;case"gt":return e>t.value;case"lte":return e<=t.value;case"gte":return e>=t.value;default:return!1}}determineTestStatus(t){return t.status==="aborted"?"aborted":t.assertionResults.filter(r=>!r.passed).length>0||t.summary.errorRate>10?"failed":"completed"}finalizeExecution(t){let e={testId:t.result.testId,status:t.result.status,duration:t.result.duration,summary:t.result.summary,timeline:t.result.timeline,errors:t.result.errors,assertionResults:t.result.assertionResults};return this.memory.set(`loadtest:results:${t.testId}:${Date.now()}`,e,{namespace:"chaos-resilience",persist:!0}),e}sleep(t){return new Promise(e=>setTimeout(e,t))}};M();A();se();H();var Lv={defaultTimeout:6e4,healthCheckInterval:1e3,maxRetries:3,recoveryCheckDelay:500,simulateRandomFailures:!1},yt=R.create("chaos-resilience/performance-profiler"),Mr=class{constructor(t,e={}){this.memory=t;this.config={...Lv,...e},this.httpClient=_i()}memory;config;httpClient;async testRecovery(t,e,r){let i=v();try{let n=[],s=await this.checkServiceHealth(t);if(n.push({timestamp:new Date,event:"Initial health check",status:s?"healthy":"unhealthy"}),!s)return f({service:t,faultType:e,recoveryTime:0,expectedRecoveryTime:r,passed:!1,timeline:n});n.push({timestamp:new Date,event:`Injecting fault: ${e}`,status:"degraded"}),await this.injectFault(t,e);let a=await this.checkServiceHealth(t);n.push({timestamp:new Date,event:"Post-fault health check",status:a?"healthy":"unhealthy"}),n.push({timestamp:new Date,event:"Removing fault",status:"degraded"}),await this.removeFault(t,e);let o=Date.now(),c=0,l=!1,d=r*2;for(;Date.now()-o<d;){if(await this.checkServiceHealth(t)){c=Date.now()-o,l=!0,n.push({timestamp:new Date,event:"Service recovered",status:"healthy"});break}n.push({timestamp:new Date,event:"Recovery check - still degraded",status:"degraded"}),await this.sleep(this.config.recoveryCheckDelay)}l||n.push({timestamp:new Date,event:"Recovery timeout exceeded",status:"unhealthy"});let m={service:t,faultType:e,recoveryTime:c,expectedRecoveryTime:r,passed:l&&c<=r,timeline:n};return await this.storeTestResult("recovery",i,m),f(m)}catch(n){return p(y(n))}}async testFailover(t,e){let r=v();try{let i=[],n=1,[s,a]=await Promise.all([this.checkServiceHealth(t),this.checkServiceHealth(e)]);if(i.push({order:n++,action:"Verify primary service health",duration:0,success:s}),i.push({order:n++,action:"Verify secondary service health",duration:0,success:a}),!s||!a)return f({primaryService:t,secondaryService:e,failoverTime:0,dataLoss:!0,passed:!1,steps:i});let o=await this.captureServiceState(t);i.push({order:n++,action:"Capture primary service state",duration:0,success:!0});let c=Date.now();await this.injectFault(t,"process-kill"),i.push({order:n++,action:"Trigger primary service failure",duration:Date.now()-c,success:!0});let l=Date.now(),d=!1,m=0;for(;Date.now()-l<this.config.defaultTimeout;){if(await this.checkServiceIsActive(e)){m=Date.now()-c,d=!0;break}await this.sleep(this.config.healthCheckInterval)}i.push({order:n++,action:"Detect failover completion",duration:m,success:d});let g=await this.captureServiceState(e),h=!this.compareServiceStates(o,g);i.push({order:n++,action:"Verify data integrity on secondary",duration:0,success:!h}),await this.removeFault(t,"process-kill"),i.push({order:n++,action:"Restore primary service",duration:0,success:!0});let b={primaryService:t,secondaryService:e,failoverTime:m,dataLoss:h,passed:d&&!h,steps:i};return await this.storeTestResult("failover",r,b),f(b)}catch(i){return p(y(i))}}async testCircuitBreaker(t,e){let r=v();try{let i=e?.errorThreshold??5,n=e?.timeout??this.config.defaultTimeout,s=e?.halfOpenRequests??3;await this.getCircuitState(t)!=="closed"&&await this.resetCircuit(t);let o=0,c=!1;for(let w=0;w<i*2;w++)if(await this.generateError(t),o++,await this.getCircuitState(t)==="open"){c=!0;break}let l=!1,d=Date.now();for(;Date.now()-d<n;){if(await this.getCircuitState(t)==="half-open"){l=!0;break}await this.sleep(this.config.healthCheckInterval)}let m="correct";if(l){let w=0;for(let S=0;S<s;S++)await this.sendSuccessfulRequest(t)&&w++;await this.getCircuitState(t)!=="closed"&&w===s&&(m="incorrect")}let g=!1,h=Date.now();for(;Date.now()-h<n;){if(await this.getCircuitState(t)==="closed"){g=!0;break}await this.sendSuccessfulRequest(t),await this.sleep(this.config.healthCheckInterval)}let b={service:t,opened:c,openedAfterErrors:o,closedAfterRecovery:g,halfOpenBehavior:m,passed:c&&g&&m==="correct"};return await this.storeTestResult("circuit-breaker",r,b),f(b)}catch(i){return p(y(i))}}async testRateLimiting(t,e){let r=v();try{let i=0,n={statusCode:429,retryAfter:void 0,body:void 0},s=[1,5,10,25,50,100,200],a=0,o=!1;for(let m of s){if(o)break;let g=await this.sendRequestBatch(t,m);a+=m;for(let h of g)if(h.statusCode===429){o=!0,i=a-(m-g.indexOf(h)),n=h;break}}o||(i=a);let c=e*.2,l=Math.abs(i-e)<=c||!o,d={service:t,expectedLimit:e,actualLimit:i,passed:o&&l,responseWhenLimited:n};return await this.storeTestResult("rate-limit",r,d),f(d)}catch(i){return p(y(i))}}async checkServiceHealth(t){if(!this.isRealServiceUrl(t))return this.simulateHealthCheck();try{return await this.httpClient.healthCheck(t)}catch{return this.simulateHealthCheck()}}isRealServiceUrl(t){return t.startsWith("http://")||t.startsWith("https://")}simulateHealthCheck(){return this.config.simulateRandomFailures?L()>.05:!0}async checkServiceIsActive(t){if(!this.isRealServiceUrl(t))return this.simulateServiceActive();try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return this.simulateServiceActive()}}simulateServiceActive(){return this.config.simulateRandomFailures?L()>.1:!0}async injectFault(t,e){if(this.isRealServiceUrl(t))try{let r=`${t}/_chaos/inject`;await this.httpClient.post(r,{faultType:e},{timeout:5e3,retries:0});return}catch{yt.debug("Fault injection API failed:")}yt.info(`Injecting fault ${e} into service: ${t}`),await this.sleep(100)}async removeFault(t,e){if(this.isRealServiceUrl(t))try{let r=`${t}/_chaos/remove`;await this.httpClient.post(r,{faultType:e},{timeout:5e3,retries:0});return}catch{yt.debug("Fault removal API failed:")}yt.info(`Removing fault ${e} from service: ${t}`),await this.sleep(50)}async captureServiceState(t){if(this.isRealServiceUrl(t))try{let r=`${t}/_state`,i=await this.httpClient.get(r,{timeout:5e3,retries:1});if(i.success&&i.value.ok){let n=await i.value.text(),s=this.calculateChecksum(n),a=this.parseRecordCount(n);return{checksum:s,timestamp:new Date,records:a}}}catch{yt.debug("State capture API failed:")}return await this.captureMemoryState(t)}calculateChecksum(t){let e=0;for(let r=0;r<t.length;r++){let i=t.charCodeAt(r);e=(e<<5)-e+i,e=e&e}return`chk_${Math.abs(e).toString(16)}`}parseRecordCount(t){try{let e=E(t);return e.records??e.count??e.total??e.length??0}catch{return t.split(`
3012
- `).filter(e=>e.trim()).length}}async captureMemoryState(t){let e=`resilience:state:${this.hashServiceName(t)}`,r=await this.memory.get(e);if(r)return r;let i={checksum:`init_${v().slice(0,8)}`,timestamp:new Date,records:0};return await this.memory.set(e,i,{namespace:"chaos-resilience"}),i}hashServiceName(t){let e=0;for(let r of t)e=(e<<5)-e+r.charCodeAt(0),e=e&e;return Math.abs(e).toString(16)}compareServiceStates(t,e){let r=t.checksum===e.checksum,i=t.records===e.records;return r||i}async getCircuitState(t){try{return this.httpClient.getCircuitState(t).state}catch{return"closed"}}async resetCircuit(t){try{this.httpClient.resetCircuit(t)}catch{yt.info(`Resetting circuit breaker for: ${t}`)}}async generateError(t){if(this.isRealServiceUrl(t))try{let e=`${t}/_chaos/error`;await this.httpClient.post(e,{},{timeout:5e3,retries:0});return}catch{yt.debug("Error generation API failed:")}yt.info(`Generating error for: ${t}`)}async sendSuccessfulRequest(t){if(!this.isRealServiceUrl(t))return!0;try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return!0}}async sendRequestBatch(t,e){let r=[];if(!this.isRealServiceUrl(t))return this.simulateRequestBatch(e);for(let i=0;i<e;i++)try{let n=await this.httpClient.get(t,{timeout:2e3,retries:0,circuitBreaker:!1});if(n.success){let s=n.value,a=s.headers.get("Retry-After");r.push({statusCode:s.status,retryAfter:a?parseInt(a,10):void 0})}else r.push({statusCode:500,body:{error:n.error.message}})}catch{return[...r,...this.simulateRequestBatch(e-i)]}return r}simulateRequestBatch(t){let e=[];for(let i=0;i<t;i++)i>=75?e.push({statusCode:429,retryAfter:60,body:{error:"Rate limit exceeded"}}):e.push({statusCode:200});return e}async storeTestResult(t,e,r){await this.memory.set(`resilience:${t}:${e}`,r,{namespace:"chaos-resilience",persist:!0})}sleep(t){return new Promise(e=>setTimeout(e,t))}};se();var $v={stateSize:10,actionSize:5,hiddenLayers:[64,64],learningRatePG:.01,gammaPG:.99,entropyCoeff:.01},Sa=class extends ae{policy;pgConfig;actions=[];episodeLog=[];constructor(t={}){super("policy-gradient","policy-based"),this.pgConfig={...$v,...t},this.initializeActions(),this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.policy.forward(e),i=pe.forward(r),n=this.sampleAction(i),s=this.actions[n],a=i[n],o=Math.max(.3,Math.min(1,a+.4));return this.episodeLog.push({state:t,action:s,reward:0}),{action:s,confidence:o,reasoning:this.generateReasoning(t,s,a)}}async trainCore(t){let e=this.groupIntoEpisodes(t),r=0;for(let i of e){let n=this.calculateReturns(i);for(let s=0;s<i.length;s++){let{state:a,action:o}=i[s],c=n[s],l=this.prepareState(a),d=this.policy.forward(l),m=pe.forward(d),g=this.actionToIndex(o),b=-Math.log(m[g]+1e-10)*c;r+=Math.abs(b);let w=new Float32Array(m.length);for(let C=0;C<w.length;C++)C===g?w[C]=-c*(1-m[C]):w[C]=c*m[C];this.policy.backward(w);for(let C of this.policy.layers)C.update(this.pgConfig.learningRatePG)}}return this.episodeLog=[],{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/t.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Policy Gradient (REINFORCE) for Resource Allocation",capabilities:["Neural policy optimization","Monte Carlo return estimation","Entropy regularization"],hyperparameters:{stateSize:this.pgConfig.stateSize,actionSize:this.pgConfig.actionSize,learningRatePG:this.pgConfig.learningRatePG,gammaPG:this.pgConfig.gammaPG},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.pgConfig.stateSize);for(;e.length<this.pgConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"allocate",value:{agentType:"tester",count:1}},{type:"allocate",value:{agentType:"analyzer",count:1}},{type:"reallocate",value:{domain:"test-execution"}},{type:"scale-up",value:1},{type:"scale-down",value:1}],this.pgConfig.actionSize=this.actions.length,this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG})}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}sampleAction(t){if(L()<this.config.explorationRate)return le(0,this.actions.length);let e=L(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}calculateReturns(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--)r=t[i].reward+this.pgConfig.gammaPG*r,e.unshift(r);return e}groupIntoEpisodes(t){let e=[],r=[];for(let i of t)r.push(i),i.done&&(e.push(r),r=[]);return r.length>0&&e.push(r),e}generateReasoning(t,e,r){return`Neural Policy Gradient: ${e.type} (probability: ${r.toFixed(3)})`}async exportCustomData(){return{policy:this.policy.getParameters(),pgConfig:this.pgConfig}}async importCustomData(t){t.policy&&this.policy.setParameters(t.policy),t.pgConfig&&(this.pgConfig={...this.pgConfig,...t.pgConfig}),this.initialized=!0}async resetAlgorithm(){this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG}),this.episodeLog=[]}};var Ov={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},re=R.create("chaos-resilience"),Ra=class extends Q{constructor(e,r,i,n={}){let s={...Ov,...n};super(e,"chaos-resilience",s,{verifyFindingTypes:["chaos-experiment","resilience-assessment","failure-injection"],...s.consensusConfig});this.memory=r;this.agentCoordinator=i;this.chaosGovernanceMixin=nu(this.domainName),this.chaosEngineer=new Ir({memory:r}),this.loadTester=new Dr(r),this.performanceProfiler=new Mr(r)}memory;agentCoordinator;chaosEngineer;loadTester;performanceProfiler;policyGradient;qesona;chaosGovernanceMixin;async onInitialize(){if(this.config.enablePolicyGradient)try{this.policyGradient=new Sa({stateSize:10,actionSize:5,hiddenLayers:[64,64]}),re.info("PolicyGradient algorithm created successfully")}catch(e){throw re.error("Failed to create PolicyGradient:",e instanceof Error?e:void 0),new Error(`PolicyGradient creation failed: ${T(e)}`)}if(this.config.enableQESONA)try{this.qesona=await me({domain:"chaos-resilience",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),re.info("PersistentSONAEngine initialized successfully")}catch(e){re.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),re.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.policyGradient=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runChaosSuite(e){let r=v();try{if(this.startWorkflow(r,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&re.warn("Topology degraded, using conservative chaos strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn chaos agents"));let i=await this.spawnChaosAgent(r,"coordinator");if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let l=0;l<e.length;l++){let d=e[l];this.updateWorkflowProgress(r,Math.round((l+1)/e.length*100));let m=await this.chaosEngineer.runExperiment(d);if(m.success){if(n.push(m.value),m.value.hypothesisValidated)a++;else{o++;let g=this.generateRecommendationsFromExperiment(m.value);s.push(...g)}this.config.publishEvents&&await this.publishExperimentCompleted(m.value)}else o++,s.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${d}: ${m.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let c={totalExperiments:e.length,passed:a,failed:o,results:n,recommendations:s};return await this.storeReport("chaos-suite",r,c),f(c)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async runLoadTestSuite(e){let r=v();try{if(this.startWorkflow(r,"load-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&re.warn("Topology degraded, using conservative load test parameters"),this.minCutMixin.shouldPauseOperations())return p(new Error("Load test suite paused: topology is in critical state"));let i=await this.spawnLoadTestAgent(r,"orchestrator");if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let l=0;l<e.length;l++){let d=e[l];this.updateWorkflowProgress(r,Math.round((l+1)/e.length*100));let m=await this.loadTester.runTest(d);if(m.success){n.push(m.value),m.value.status==="completed"?a++:o++;let g=this.detectBottlenecks(m.value);s.push(...g),this.config.publishEvents&&await this.publishLoadTestCompleted(m.value)}else o++}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let c={totalTests:e.length,passed:a,failed:o,results:n,bottlenecks:s};return await this.storeReport("load-suite",r,c),f(c)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async assessResilience(e){let r=v();try{if(this.startWorkflow(r,"assessment"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&re.warn("Topology degraded, assessment may be limited"),this.minCutMixin.shouldPauseOperations())return p(new Error("Resilience assessment paused: topology is in critical state"));let i=new Map,n=[],s=[],a=[],o=await this.spawnAssessmentAgent(r);if(!o.success)return this.failWorkflow(r,o.error.message),p(o.error);this.addAgentToWorkflow(r,o.value);for(let d=0;d<e.length;d++){let m=e[d];this.updateWorkflowProgress(r,Math.round((d+1)/e.length*100));let g=await this.performanceProfiler.testRecovery(m,"latency",5e3),h=await this.performanceProfiler.testCircuitBreaker(m),b=await this.performanceProfiler.testRateLimiting(m,100),w=0;if(g.success&&g.value.passed)w+=33.3,n.push(`${m}: Fast recovery (${g.value.recoveryTime}ms)`);else{let C=g.success?g.value.recoveryTime:"unknown";s.push({service:m,type:"recovery",description:"Slow or failed recovery after fault",risk:br.create(.7)}),a.push({priority:"high",category:"recovery",recommendation:`Improve ${m} recovery time - currently ${C}ms`,effort:"moderate"})}h.success&&h.value.passed?(w+=33.3,n.push(`${m}: Circuit breaker functioning correctly`)):(s.push({service:m,type:"circuit-breaker",description:"Circuit breaker not functioning as expected",risk:br.create(.6)}),a.push({priority:"medium",category:"circuit-breaker",recommendation:`Review ${m} circuit breaker configuration`,effort:"minor"})),b.success&&b.value.passed?(w+=33.4,n.push(`${m}: Rate limiting effective`)):(s.push({service:m,type:"rate-limiting",description:"Rate limiting not properly configured",risk:br.create(.5)}),a.push({priority:"medium",category:"rate-limiting",recommendation:`Configure rate limiting for ${m}`,effort:"minor"})),i.set(m,w)}let c=e.length>0?Array.from(i.values()).reduce((d,m)=>d+m,0)/e.length:0;await this.agentCoordinator.stop(o.value),this.completeWorkflow(r);let l={overallScore:c,serviceScores:i,strengths:n,weaknesses:s,recommendations:a};return await this.storeReport("assessment",r,l),f(l)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generateExperiments(e){let r=v();try{this.startWorkflow(r,"experiment-generation");let i=[];for(let n of e.services){let s=this.generateServiceExperiments(n,e.dependencies);i.push(...s)}for(let n of e.criticalPaths){let s=this.generateCriticalPathExperiment(n,e);i.push(s)}for(let n of i)await this.chaosEngineer.createExperiment(n);return this.completeWorkflow(r),f(i)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async runStrategicChaosSuite(e,r){let i=v();try{if(this.startWorkflow(i,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&re.warn("Topology degraded, adjusting strategic chaos parameters"),this.minCutMixin.shouldPauseOperations())return p(new Error("Strategic chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn chaos agents"));let n=await this.selectChaosStrategy(e,r);if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s=n.value.selectedExperiments;if(re.info(`[chaos-resilience] Using ${n.value.strategy} strategy with ${s.length} experiments (confidence: ${n.value.confidence.toFixed(2)})`),s.length===0)return this.completeWorkflow(i),f({totalExperiments:0,passed:0,failed:0,results:[],recommendations:[{priority:"low",category:"strategy",recommendation:"No experiments selected - consider adjusting strategy context",effort:"trivial"}]});let a=await this.spawnChaosAgent(i,"coordinator");if(!a.success)return this.failWorkflow(i,a.error.message),p(a.error);this.addAgentToWorkflow(i,a.value);let o=[],c=[],l=0,d=0;for(let g of s)await this.chaosEngineer.createExperiment(g);for(let g=0;g<s.length;g++){let h=s[g];this.updateWorkflowProgress(i,Math.round((g+1)/s.length*100));let b=await this.chaosEngineer.runExperiment(h.id);if(b.success){if(o.push(b.value),b.value.hypothesisValidated)l++;else{d++;let C=this.generateRecommendationsFromExperiment(b.value);c.push(...C)}let w=b.value.hypothesisValidated?.8:.2;await this.storeResiliencePattern(h,b.value,w),this.config.publishEvents&&await this.publishExperimentCompleted(b.value)}else d++,c.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${h.name}: ${b.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(a.value),this.completeWorkflow(i);let m={totalExperiments:s.length,passed:l,failed:d,results:o,recommendations:c};return await this.storeReport("strategic-chaos-suite",i,m),f(m)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async getResilienceDashboard(){try{let e=await this.memory.search("chaos:results:*",10),r=await this.memory.search("loadtest:results:*",10),i,n,s=0,a=0,o=0,c=0,l=0;for(let b of e){let w=await this.memory.get(b);w&&((!i||w.startTime>i)&&(i=w.startTime),s+=w.incidents.filter(C=>!C.resolved).length)}for(let b of r){let w=await this.memory.get(b);if(w&&w.timeline.length>0){let C=w.timeline[0].timestamp;(!n||C>n)&&(n=C),l++,w.status==="failed"&&c++}}let d=o>0?a/o:0,m=l>0?c/l*100:0,g="healthy";return s>5||m>25?g="unhealthy":(s>0||m>10)&&(g="degraded"),f({overallHealth:g,lastExperimentDate:i,lastLoadTestDate:n,activeIncidents:s,uptime:99.9,mttr:d,changeFailureRate:m})}catch(e){return p(y(e))}}async spawnChaosAgent(e,r){let i={name:`chaos-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["chaos-engineering","fault-injection",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnLoadTestAgent(e,r){let i={name:`loadtest-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["load-testing","performance",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnAssessmentAgent(e){let r={name:`assessment-${e.slice(0,8)}`,domain:"chaos-resilience",type:"analyzer",capabilities:["resilience-assessment","analysis"],config:{workflowId:e}};return this.agentCoordinator.spawn(r)}async publishExperimentCompleted(e){let r={id:v(),type:"chaos-resilience.ExperimentCompleted",timestamp:new Date,source:"chaos-resilience",payload:{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,incidentCount:e.incidents.length}};await this.eventBus.publish(r)}async publishLoadTestCompleted(e){let r={id:v(),type:"chaos-resilience.LoadTestCompleted",timestamp:new Date,source:"chaos-resilience",payload:{testId:e.testId,status:e.status,summary:e.summary,assertionsPassed:e.assertionResults.filter(i=>i.passed).length,assertionsFailed:e.assertionResults.filter(i=>!i.passed).length}};await this.eventBus.publish(r)}generateRecommendationsFromExperiment(e){let r=[];e.hypothesisValidated||r.push({priority:"high",category:"hypothesis-failure",recommendation:`Experiment ${e.experimentId} hypothesis was not validated - review system behavior under fault conditions`,effort:"moderate"}),e.steadyStateVerified||r.push({priority:"critical",category:"steady-state",recommendation:"System did not maintain steady state - investigate stability issues",effort:"major"});for(let i of e.incidents)(i.severity==="critical"||i.severity==="high")&&r.push({priority:i.severity,category:"incident",recommendation:`Address ${i.type}: ${i.message}`,effort:"moderate"});return r}detectBottlenecks(e){let r=[];return e.summary.p95ResponseTime>1e3&&r.push({location:"api",type:"network",description:`P95 response time is ${e.summary.p95ResponseTime}ms (>1000ms)`,impact:e.summary.p95ResponseTime>2e3?"high":"medium",recommendation:"Investigate API response time, consider caching or query optimization"}),e.summary.errorRate>5&&r.push({location:"service",type:"cpu",description:`Error rate is ${e.summary.errorRate.toFixed(2)}% (>5%)`,impact:e.summary.errorRate>10?"high":"medium",recommendation:"Investigate error causes, scale resources if under load"}),e.summary.requestsPerSecond<10&&r.push({location:"backend",type:"io",description:`Low throughput: ${e.summary.requestsPerSecond.toFixed(2)} RPS`,impact:"medium",recommendation:"Review I/O operations, database queries, and connection pooling"}),r}generateServiceExperiments(e,r){let i=[];i.push(this.createExperiment(`${e.name}-latency`,`Test ${e.name} behavior under latency`,"latency",e.name)),i.push(this.createExperiment(`${e.name}-error`,`Test ${e.name} error handling`,"error",e.name)),i.push(this.createExperiment(`${e.name}-cpu-stress`,`Test ${e.name} under CPU stress`,"cpu-stress",e.name));let n=r.filter(s=>s.from===e.name);for(let s of n)s.criticality==="critical"&&i.push(this.createExperiment(`${e.name}-${s.to}-failure`,`Test ${e.name} when ${s.to} fails`,"error",s.to));return i}generateCriticalPathExperiment(e,r){let i=e.join("-");return{id:v(),name:`critical-path-${i}`,description:`Test critical path: ${e.join(" -> ")}`,hypothesis:{statement:"System should handle partial path failure gracefully",metrics:[{metric:"error_rate",operator:"lt",value:10},{metric:"response_time_ms",operator:"lt",value:2e3}],tolerances:[{metric:"error_rate",maxDeviation:5,unit:"percent"}]},steadyState:{description:"All services in path are healthy",probes:e.map(n=>({name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}))},faults:e.slice(0,-1).map(n=>({id:v(),type:"latency",target:{type:"service",selector:n},parameters:{latencyMs:500},duration:3e4})),blastRadius:{scope:"subset",percentage:50,excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 20"},{type:"timeout",condition:"duration > 60000"}],steps:[{order:1,action:"Remove all faults",timeout:5e3},{order:2,action:"Verify service health"}]}}}createExperiment(e,r,i,n){return{id:v(),name:e,description:r,hypothesis:{statement:`${n} should recover within 5 seconds from ${i}`,metrics:[{metric:"response_time_ms",operator:"lt",value:1e3},{metric:"error_rate",operator:"lt",value:5}],tolerances:[{metric:"response_time_ms",maxDeviation:50,unit:"percent"}]},steadyState:{description:`${n} is healthy and responsive`,probes:[{name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}]},faults:[{id:v(),type:i,target:{type:"service",selector:n},parameters:this.getDefaultFaultParameters(i),duration:3e4}],blastRadius:{scope:"single",excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 50"}],steps:[{order:1,action:`Remove ${i} fault`},{order:2,action:"Verify recovery"}]}}}getDefaultFaultParameters(e){return{latency:{latencyMs:500},error:{errorCode:500},timeout:{timeoutMs:3e4},"packet-loss":{packetLossPercent:10},"cpu-stress":{cpuPercent:80},"memory-stress":{memoryBytes:268435456},"disk-stress":{},"network-partition":{},"dns-failure":{},"process-kill":{}}[e]||{}}async storeReport(e,r,i){await this.memory.set(`chaos-resilience:reports:${e}:${r}`,i,{namespace:"chaos-resilience",persist:!0})}async selectChaosStrategy(e,r){if(!this.policyGradient||!this.config.enablePolicyGradient)return f({strategy:"default",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:1,reasoning:"Default strategy (PolicyGradient disabled)"});if(e.length===0)return f({strategy:"empty",selectedExperiments:[],confidence:1,reasoning:"No services provided"});try{let i={id:`chaos-strategy-${Date.now()}`,features:[r.riskTolerance,r.availableCapacity/100,e.length/50,e.filter(l=>!l.hasFailover).length/Math.max(1,e.length),e.filter(l=>l.type==="database").length/Math.max(1,e.length),r.environment==="production"?0:1,r.environment==="staging"?1:0,e.filter(l=>l.type==="cache").length/Math.max(1,e.length),e.filter(l=>l.type==="queue").length/Math.max(1,e.length),e.reduce((l,d)=>l+d.replicas,0)/Math.max(1,e.length*5)]},n=await this.policyGradient.predict(i),s=[],a="default";switch(n.action.type){case"allocate":let l=typeof n.action.value=="object"?n.action.value:null;if(l&&"agentType"in l&&l.agentType==="tester"){let m=e.filter(g=>!g.hasFailover||g.type==="database").slice(0,3);s=this.generateExperimentsForServices(m,["latency","error"]),a="allocate-critical"}break;case"reallocate":let d=typeof n.action.value=="object"?n.action.value:null;d&&"domain"in d&&d.domain==="test-execution"&&(s=this.generateExperimentsForServices(e.slice(0,5),["cpu-stress","memory-stress"]),a="reallocate-resource-stress");break;case"scale-up":s=this.generateExperimentsForServices(e,["latency","error","timeout"]),a="scale-up-comprehensive";break;case"scale-down":s=this.generateExperimentsForServices(e.slice(0,2),["latency"]),a="scale-down-minimal";break;default:s=this.getDefaultExperiments(e.slice(0,3)),a="default";break}let o=await this.calculateStrategyReward(s,r),c=n.action;return await this.policyGradient.train({state:i,action:c,reward:o,nextState:i,done:!0}),re.info(`[chaos-resilience] PolicyGradient selected ${a} strategy for ${e.length} services (confidence: ${n.confidence.toFixed(2)})`),f({strategy:a,selectedExperiments:s,confidence:n.confidence,reasoning:n.reasoning||`PolicyGradient selected: ${a}`})}catch(i){return re.error("PolicyGradient strategy selection failed:",i instanceof Error?i:void 0),f({strategy:"fallback",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:.5,reasoning:"Fallback to default (PolicyGradient error)"})}}generateExperimentsForServices(e,r){let i=[];for(let n of e)for(let s of r)i.push(this.createExperiment(`${n.name}-${s}-${Date.now()}`,`Test ${n.name} with ${s} fault`,s,n.name));return i}getDefaultExperiments(e){return this.generateExperimentsForServices(e,["latency","error"])}async calculateStrategyReward(e,r){let i=.5,n=e.length;(r.riskTolerance>.7&&n>5||r.riskTolerance<.3&&n<=3)&&(i+=.2),(r.availableCapacity>70&&n>5||r.availableCapacity<30&&n<=3)&&(i+=.1);let s=new Set(e.map(a=>a.faults[0]?.type));return i+=Math.min(.1,s.size/5),Math.max(0,Math.min(1,i))}async storeResiliencePattern(e,r,i){if(!(!this.qesona||!this.config.enableQESONA))try{let n={id:`chaos-${e.id}`,features:[e.faults.length/10,e.faults[0]?.duration?e.faults[0].duration/6e4:0,e.steadyState.probes.length/20,e.blastRadius.excludeProduction?1:0,(e.blastRadius.percentage??0)/100,r.hypothesisValidated?1:0,r.steadyStateVerified?1:0,r.incidents.length/10,r.incidents.filter(a=>a.severity==="critical").length/5,i]},s={type:r.hypothesisValidated?"validate":"reject",value:i};this.qesona.createPattern(n,s,{reward:r.hypothesisValidated?i:-i,success:r.hypothesisValidated,quality:i},"defect-prediction","chaos-resilience",{experimentId:e.id,experimentName:e.name,faultType:e.faults[0]?.type,hypothesisValidated:r.hypothesisValidated}),re.info(`Stored resilience pattern for ${e.id} (validated: ${r.hypothesisValidated}, quality: ${i.toFixed(2)})`)}catch(n){re.error("Failed to store resilience pattern:",n instanceof Error?n:void 0)}}async adaptStrategies(e,r){if(!this.qesona||!this.config.enableQESONA)return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5};try{let i={id:`chaos-adapt-${e.name}-${Date.now()}`,features:[e.hasFailover?0:1,r.riskTolerance,e.type==="api"?1:0,e.type==="database"?1:0,e.type==="cache"?1:0,r.environment==="production"?1:0,r.environment==="staging"?1:0,e.replicas/10,e.type==="worker"?1:0,e.type==="queue"?1:0]},n=await this.qesona.adaptPattern(i,"defect-prediction","chaos-resilience");if(n.success&&n.pattern){let s=n.pattern.outcome.success,a=this.getRecommendedFaults(n.pattern.action.type);return re.info(`[chaos-resilience] QESONA adapted strategy for ${e.name}: shouldRun=${s}, faults=${a.join(",")}, confidence=${n.similarity.toFixed(2)}`),{shouldRunChaos:s,recommendedFaults:a,confidence:n.similarity}}return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}catch(i){return re.error("QESONA strategy adaptation failed:",i instanceof Error?i:void 0),{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}}getRecommendedFaults(e){switch(e){case"validate":return["latency","error","timeout"];case"reject":return["latency"];case"allocate":return["latency","cpu-stress"];case"scale-up":return["latency","error","timeout","packet-loss"];case"scale-down":return["latency"];default:return["latency","error"]}}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this))}async handleDeploymentApproved(e){if(!this.config.enableAutomatedExperiments)return;let r=e.payload;r.services&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,r.services,{namespace:"chaos-resilience",ttl:3600})}async handleQualityGateEvaluated(e){let r=e.payload;r.passed||await this.memory.set(`chaos-resilience:quality-gate-failures:${e.id}`,r,{namespace:"chaos-resilience",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("chaos-resilience:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("chaos-resilience:coordinator:workflows",e,{namespace:"chaos-resilience",persist:!0})}async verifyChaosExperiment(e,r){let i=V({id:v(),type:"chaos-experiment",confidence:r,description:`Verify chaos experiment safety: ${e.name} (${e.faultType}) on ${e.target}`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.blastRadius==="full"?"critical":r>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(re.info(`Chaos experiment '${e.name}' verified safe by consensus`),!0):(re.warn(`Chaos experiment '${e.name}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyResilienceAssessment(e,r){let i=V({id:v(),type:"resilience-assessment",confidence:r,description:`Verify resilience assessment for ${e.service}: score ${e.overallScore}, ${e.weaknessCount} weaknesses`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.overallScore<50?"critical":e.overallScore<70?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(re.info(`Resilience assessment for '${e.service}' verified by consensus`),!0):(re.warn(`Resilience assessment for '${e.service}' NOT verified`),!1)}return!0}async verifyFailureInjection(e,r){let i=V({id:v(),type:"failure-injection",confidence:r,description:`Verify failure injection: ${e.faultType} on ${e.target} for ${e.duration}ms`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(re.info(`Failure injection '${e.faultType}' on '${e.target}' verified safe by consensus`),!0):(re.warn(`Failure injection '${e.faultType}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};A();var el=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;chaosEngineer=null;loadTester=null;performanceProfiler=null;pluginConfig;get name(){return"chaos-resilience"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runChaosSuite:this.runChaosSuite.bind(this),runLoadTestSuite:this.runLoadTestSuite.bind(this),assessResilience:this.assessResilience.bind(this),generateExperiments:this.generateExperiments.bind(this),getResilienceDashboard:this.getResilienceDashboard.bind(this),createExperiment:this.createExperiment.bind(this),runExperiment:this.runExperiment.bind(this),abortExperiment:this.abortExperiment.bind(this),verifySteadyState:this.verifySteadyState.bind(this),injectFault:this.injectFault.bind(this),removeFault:this.removeFault.bind(this),createTest:this.createTest.bind(this),runTest:this.runTest.bind(this),runLoadTest:this.runTest.bind(this),stopTest:this.stopTest.bind(this),getRealtimeMetrics:this.getRealtimeMetrics.bind(this),generateFromTraffic:this.generateFromTraffic.bind(this),getExperimentHistory:this.getExperimentHistory.bind(this),testRecovery:this.testRecovery.bind(this),testFailover:this.testFailover.bind(this),testCircuitBreaker:this.testCircuitBreaker.bind(this),testRateLimiting:this.testRateLimiting.bind(this),selectChaosStrategy:this.coordinator.selectChaosStrategy.bind(this.coordinator),runStrategicChaosSuite:this.coordinator.runStrategicChaosSuite.bind(this.coordinator),getCoordinator:()=>this.coordinator,getChaosEngineer:()=>this.chaosEngineer,getChaosEngine:()=>this.chaosEngineer,getLoadTester:()=>this.loadTester,getPerformanceProfiler:()=>this.performanceProfiler,getResilienceAssessor:()=>this.performanceProfiler}}getTaskHandlers(){return new Map([["run-experiment",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.experimentId;return r?this.coordinator.runChaosSuite([r]):p(new Error("Invalid run-experiment payload: missing experimentId"))}],["run-load-test",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.testId;return r?this.coordinator.runLoadTestSuite([r]):p(new Error("Invalid run-load-test payload: missing testId"))}],["assess-resilience",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.services;return!r||r.length===0?p(new Error("Invalid assess-resilience payload: missing services")):this.coordinator.assessResilience(r)}],["inject-fault",async e=>{if(!this.chaosEngineer)return p(new Error("Chaos engineer not initialized"));let r=e.faultType,i=e.target;if(!r||!i)return p(new Error("Invalid inject-fault payload: missing faultType or target"));let n={id:`fault-${Date.now()}`,type:r,target:{type:"service",selector:i},parameters:e.parameters??{},duration:e.duration??3e4,probability:e.probability};return this.chaosEngineer.injectFault(n)}]])}async onInitialize(){this.chaosEngineer=new Ir({memory:this.memory},this.pluginConfig.chaosEngineer),this.loadTester=new Dr(this.memory,this.pluginConfig.loadTester),this.performanceProfiler=new Mr(this.memory,this.pluginConfig.performanceProfiler),this.coordinator=new Ra(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(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"quality-assessment.DeploymentApproved":await this.handleDeploymentApproved(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;default:break}}async runChaosSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runChaosSuite(e);return r.success?this.trackSuccessfulOperation("chaos-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async runLoadTestSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runLoadTestSuite(e);return r.success?this.trackSuccessfulOperation("load-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async assessResilience(e){this.ensureInitialized();try{return await this.coordinator.assessResilience(e)}catch(r){return this.handleError(r)}}async generateExperiments(e){this.ensureInitialized();try{return await this.coordinator.generateExperiments(e)}catch(r){return this.handleError(r)}}async getResilienceDashboard(){this.ensureInitialized();try{return await this.coordinator.getResilienceDashboard()}catch(e){return this.handleError(e)}}async createExperiment(e){this.ensureInitialized();try{return await this.chaosEngineer.createExperiment(e)}catch(r){return this.handleError(r)}}async runExperiment(e){this.ensureInitialized();try{let r=await this.chaosEngineer.runExperiment(e);return r.success&&await this.publishExperimentEvent(r.value),r}catch(r){return this.handleError(r)}}async abortExperiment(e,r){this.ensureInitialized();try{return await this.chaosEngineer.abortExperiment(e,r)}catch(i){return this.handleError(i)}}async verifySteadyState(e){this.ensureInitialized();try{return await this.chaosEngineer.verifySteadyState(e)}catch(r){return this.handleError(r)}}async injectFault(e){this.ensureInitialized();try{return await this.chaosEngineer.injectFault(e)}catch(r){return this.handleError(r)}}async removeFault(e){this.ensureInitialized();try{return await this.chaosEngineer.removeFault(e)}catch(r){return this.handleError(r)}}async getExperimentHistory(){this.ensureInitialized();try{return{success:!0,value:await this.memory.get("chaos-resilience:experiment-history")??[]}}catch(e){return this.handleError(e)}}async createTest(e){this.ensureInitialized();try{return await this.loadTester.createTest(e)}catch(r){return this.handleError(r)}}async runTest(e){this.ensureInitialized();try{let r=await this.loadTester.runTest(e);return r.success&&await this.publishLoadTestEvent(r.value),r}catch(r){return this.handleError(r)}}async stopTest(e){this.ensureInitialized();try{return await this.loadTester.stopTest(e)}catch(r){return this.handleError(r)}}async getRealtimeMetrics(e){this.ensureInitialized();try{return await this.loadTester.getRealtimeMetrics(e)}catch(r){return this.handleError(r)}}async generateFromTraffic(e,r){this.ensureInitialized();try{return await this.loadTester.generateFromTraffic(e,r)}catch(i){return this.handleError(i)}}async testRecovery(e,r,i){this.ensureInitialized();try{return await this.performanceProfiler.testRecovery(e,r,i)}catch(n){return this.handleError(n)}}async testFailover(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testFailover(e,r)}catch(i){return this.handleError(i)}}async testCircuitBreaker(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testCircuitBreaker(e,r)}catch(i){return this.handleError(i)}}async testRateLimiting(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testRateLimiting(e,r)}catch(i){return this.handleError(i)}}async handleDeploymentApproved(e){let r=e.payload;r.services&&r.services.length>0&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,{services:r.services,triggeredAt:new Date,source:"deployment-approved"},{namespace:"chaos-resilience",ttl:3600})}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`chaos-resilience:test-baseline:${r.runId}`,{duration:r.duration,successRate:r.passed/(r.passed+r.failed),timestamp:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleVulnerabilityDetected(e){let r=e.payload;(r.severity==="critical"||r.severity==="high")&&await this.memory.set(`chaos-resilience:security-tests:${r.vulnId}`,{vulnerabilityId:r.vulnId,severity:r.severity,file:r.file,triggeredAt:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleQualityGateEvaluated(e){let r=e.payload;r.checks?.some(n=>n.name==="resilience")&&await this.memory.set(`chaos-resilience:gate-context:${r.gateId}`,{gateId:r.gateId,passed:r.passed,checks:r.checks,timestamp:Date.now()},{namespace:"chaos-resilience",ttl:3600})}async publishExperimentEvent(e){await this.publishEvent("chaos-resilience.ExperimentCompleted",{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,steadyStateVerified:e.steadyStateVerified,faultCount:e.faultResults.length,incidentCount:e.incidents.length,duration:e.endTime?e.endTime.getTime()-e.startTime.getTime():0})}async publishLoadTestEvent(e){await this.publishEvent("chaos-resilience.LoadTestCompleted",{testId:e.testId,status:e.status,duration:e.duration,totalRequests:e.summary.totalRequests,successRate:e.summary.totalRequests>0?e.summary.successfulRequests/e.summary.totalRequests*100:0,p95ResponseTime:e.summary.p95ResponseTime,errorRate:e.summary.errorRate,assertionsPassed:e.assertionResults.filter(r=>r.passed).length,assertionsFailed:e.assertionResults.filter(r=>!r.passed).length})}ensureInitialized(){if(!this._initialized)throw new Error("ChaosResiliencePlugin is not initialized");if(!this.coordinator||!this.chaosEngineer||!this.loadTester||!this.performanceProfiler)throw new Error("ChaosResiliencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Am(u,t,e,r){return new el(u,t,e,r)}M();A();M();A();var Nv={minExperiencesForPattern:5,patternConfidenceThreshold:.7,maxPatternsPerDomain:100,anomalyDeviationThreshold:2,clusterSimilarityThreshold:.8,enableLLMSynthesis:!0,llmModelTier:2,llmMaxTokens:2048},Em=R.create("learning-optimization/learning-coordinator"),Gt=class{config;memory;llmRouter;flashAttention=null;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...Nv,...e}}async initializeFlashAttention(t){return this.flashAttention=await Ie("pattern-adaptation",t),Em.info("FlashAttention initialized for pattern adaptation"),this.flashAttention}injectFlashAttention(t){this.flashAttention=t}isFlashAttentionAvailable(){return this.flashAttention!==null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():[]}async computeSimilarityWithFlashAttention(t,e){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let r=Math.min(t.length,e.length),i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let c=0;c<r;c++)i[c]=t[c],n[c]=e[c],s[c]=1;let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=Math.abs(a[0]);return Math.min(1,o)}async batchComputeSimilarities(t,e,r=5){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let i=new Float32Array(t),n=e.map(s=>new Float32Array(s));return this.flashAttention.computeTestSimilarity(i,n,r)}disposeFlashAttention(){this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null)}isLLMSynthesisAvailable(){return this.config.enableLLMSynthesis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}async synthesizePatternsWithLLM(t){if(!this.isLLMSynthesisAvailable())return null;try{let e=t.slice(0,10).map(i=>`- ${i.name}: ${i.type} (confidence: ${i.confidence.toFixed(2)})`).join(`
3012
+ `).filter(e=>e.trim()).length}}async captureMemoryState(t){let e=`resilience:state:${this.hashServiceName(t)}`,r=await this.memory.get(e);if(r)return r;let i={checksum:`init_${v().slice(0,8)}`,timestamp:new Date,records:0};return await this.memory.set(e,i,{namespace:"chaos-resilience"}),i}hashServiceName(t){let e=0;for(let r of t)e=(e<<5)-e+r.charCodeAt(0),e=e&e;return Math.abs(e).toString(16)}compareServiceStates(t,e){let r=t.checksum===e.checksum,i=t.records===e.records;return r||i}async getCircuitState(t){try{return this.httpClient.getCircuitState(t).state}catch{return"closed"}}async resetCircuit(t){try{this.httpClient.resetCircuit(t)}catch{yt.info(`Resetting circuit breaker for: ${t}`)}}async generateError(t){if(this.isRealServiceUrl(t))try{let e=`${t}/_chaos/error`;await this.httpClient.post(e,{},{timeout:5e3,retries:0});return}catch{yt.debug("Error generation API failed:")}yt.info(`Generating error for: ${t}`)}async sendSuccessfulRequest(t){if(!this.isRealServiceUrl(t))return!0;try{let e=await this.httpClient.get(t,{timeout:5e3,retries:1});return e.success&&e.value.ok}catch{return!0}}async sendRequestBatch(t,e){let r=[];if(!this.isRealServiceUrl(t))return this.simulateRequestBatch(e);for(let i=0;i<e;i++)try{let n=await this.httpClient.get(t,{timeout:2e3,retries:0,circuitBreaker:!1});if(n.success){let s=n.value,a=s.headers.get("Retry-After");r.push({statusCode:s.status,retryAfter:a?parseInt(a,10):void 0})}else r.push({statusCode:500,body:{error:n.error.message}})}catch{return[...r,...this.simulateRequestBatch(e-i)]}return r}simulateRequestBatch(t){let e=[];for(let i=0;i<t;i++)i>=75?e.push({statusCode:429,retryAfter:60,body:{error:"Rate limit exceeded"}}):e.push({statusCode:200});return e}async storeTestResult(t,e,r){await this.memory.set(`resilience:${t}:${e}`,r,{namespace:"chaos-resilience",persist:!0})}sleep(t){return new Promise(e=>setTimeout(e,t))}};se();var $v={stateSize:10,actionSize:5,hiddenLayers:[64,64],learningRatePG:.01,gammaPG:.99,entropyCoeff:.01},Sa=class extends ae{policy;pgConfig;actions=[];episodeLog=[];constructor(t={}){super("policy-gradient","policy-based"),this.pgConfig={...$v,...t},this.initializeActions(),this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG})}async predict(t){this.initialized||await this.initialize();let e=this.prepareState(t),r=this.policy.forward(e),i=pe.forward(r),n=this.sampleAction(i),s=this.actions[n],a=i[n],o=Math.max(.3,Math.min(1,a+.4));return this.episodeLog.push({state:t,action:s,reward:0}),{action:s,confidence:o,reasoning:this.generateReasoning(t,s,a)}}async trainCore(t){let e=this.groupIntoEpisodes(t),r=0;for(let i of e){let n=this.calculateReturns(i);for(let s=0;s<i.length;s++){let{state:a,action:o}=i[s],c=n[s],l=this.prepareState(a),d=this.policy.forward(l),m=pe.forward(d),g=this.actionToIndex(o),b=-Math.log(m[g]+1e-10)*c;r+=Math.abs(b);let w=new Float32Array(m.length);for(let C=0;C<w.length;C++)C===g?w[C]=-c*(1-m[C]):w[C]=c*m[C];this.policy.backward(w);for(let C of this.policy.layers)C.update(this.pgConfig.learningRatePG)}}return this.episodeLog=[],{episode:this.episodeCount,totalReward:this.totalReward,averageReward:this.rewardHistory.reduce((i,n)=>i+n,0)/this.rewardHistory.length,loss:r/t.length,explorationRate:this.config.explorationRate,trainingTimeMs:0,timestamp:new Date}}getAlgorithmInfo(){return{type:this.type,category:this.category,version:"2.0.0",description:"Neural Policy Gradient (REINFORCE) for Resource Allocation",capabilities:["Neural policy optimization","Monte Carlo return estimation","Entropy regularization"],hyperparameters:{stateSize:this.pgConfig.stateSize,actionSize:this.pgConfig.actionSize,learningRatePG:this.pgConfig.learningRatePG,gammaPG:this.pgConfig.gammaPG},stats:this.stats}}prepareState(t){let e=t.features.slice(0,this.pgConfig.stateSize);for(;e.length<this.pgConfig.stateSize;)e.push(0);let r=Math.max(...e.map(Math.abs));if(r>0)for(let i=0;i<e.length;i++)e[i]=e[i]/r;return new Float32Array(e)}initializeActions(){this.actions=[{type:"allocate",value:{agentType:"tester",count:1}},{type:"allocate",value:{agentType:"analyzer",count:1}},{type:"reallocate",value:{domain:"test-execution"}},{type:"scale-up",value:1},{type:"scale-down",value:1}],this.pgConfig.actionSize=this.actions.length,this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG})}actionToIndex(t){let e=this.actionToKey(t);for(let r=0;r<this.actions.length;r++)if(this.actionToKey(this.actions[r])===e)return r;return 0}actionToKey(t){return`${t.type}:${JSON.stringify(t.value)}`}sampleAction(t){if(L()<this.config.explorationRate)return le(0,this.actions.length);let e=L(),r=0;for(let i=0;i<t.length;i++)if(r+=t[i],e<=r)return i;return this.argmax(t)}argmax(t){let e=0,r=t[0];for(let i=1;i<t.length;i++)t[i]>r&&(r=t[i],e=i);return e}calculateReturns(t){let e=[],r=0;for(let i=t.length-1;i>=0;i--)r=t[i].reward+this.pgConfig.gammaPG*r,e.unshift(r);return e}groupIntoEpisodes(t){let e=[],r=[];for(let i of t)r.push(i),i.done&&(e.push(r),r=[]);return r.length>0&&e.push(r),e}generateReasoning(t,e,r){return`Neural Policy Gradient: ${e.type} (probability: ${r.toFixed(3)})`}async exportCustomData(){return{policy:this.policy.getParameters(),pgConfig:this.pgConfig}}async importCustomData(t){t.policy&&this.policy.setParameters(t.policy),t.pgConfig&&(this.pgConfig={...this.pgConfig,...t.pgConfig}),this.initialized=!0}async resetAlgorithm(){this.policy=new q({layerSizes:[this.pgConfig.stateSize,...this.pgConfig.hiddenLayers,this.pgConfig.actionSize],activations:Array(this.pgConfig.hiddenLayers.length).fill(new _).concat([new B]),learningRate:this.pgConfig.learningRatePG}),this.episodeLog=[]}};var Ov={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},ie=R.create("chaos-resilience"),Ra=class extends Q{constructor(e,r,i,n={}){let s={...Ov,...n};super(e,"chaos-resilience",s,{verifyFindingTypes:["chaos-experiment","resilience-assessment","failure-injection"],...s.consensusConfig});this.memory=r;this.agentCoordinator=i;this.chaosGovernanceMixin=nu(this.domainName),this.chaosEngineer=new Ir({memory:r}),this.loadTester=new Dr(r),this.performanceProfiler=new Mr(r)}memory;agentCoordinator;chaosEngineer;loadTester;performanceProfiler;policyGradient;qesona;chaosGovernanceMixin;async onInitialize(){if(this.config.enablePolicyGradient)try{this.policyGradient=new Sa({stateSize:10,actionSize:5,hiddenLayers:[64,64]}),ie.info("PolicyGradient algorithm created successfully")}catch(e){throw ie.error("Failed to create PolicyGradient:",e instanceof Error?e:void 0),new Error(`PolicyGradient creation failed: ${T(e)}`)}if(this.config.enableQESONA)try{this.qesona=await me({domain:"chaos-resilience",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:5e3,minConfidence:.6}),ie.info("PersistentSONAEngine initialized successfully")}catch(e){ie.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),ie.warn("Continuing without SONA pattern persistence"),this.qesona=void 0}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){await this.saveWorkflowState(),this.qesona&&(await this.qesona.close(),this.qesona=void 0),this.policyGradient=void 0}getActiveWorkflows(){return super.getActiveWorkflows()}async runChaosSuite(e){let r=v();try{if(this.startWorkflow(r,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative chaos strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn chaos agents"));let i=await this.spawnChaosAgent(r,"coordinator");if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let l=0;l<e.length;l++){let d=e[l];this.updateWorkflowProgress(r,Math.round((l+1)/e.length*100));let m=await this.chaosEngineer.runExperiment(d);if(m.success){if(n.push(m.value),m.value.hypothesisValidated)a++;else{o++;let g=this.generateRecommendationsFromExperiment(m.value);s.push(...g)}this.config.publishEvents&&await this.publishExperimentCompleted(m.value)}else o++,s.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${d}: ${m.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let c={totalExperiments:e.length,passed:a,failed:o,results:n,recommendations:s};return await this.storeReport("chaos-suite",r,c),f(c)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async runLoadTestSuite(e){let r=v();try{if(this.startWorkflow(r,"load-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, using conservative load test parameters"),this.minCutMixin.shouldPauseOperations())return p(new Error("Load test suite paused: topology is in critical state"));let i=await this.spawnLoadTestAgent(r,"orchestrator");if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=[],s=[],a=0,o=0;for(let l=0;l<e.length;l++){let d=e[l];this.updateWorkflowProgress(r,Math.round((l+1)/e.length*100));let m=await this.loadTester.runTest(d);if(m.success){n.push(m.value),m.value.status==="completed"?a++:o++;let g=this.detectBottlenecks(m.value);s.push(...g),this.config.publishEvents&&await this.publishLoadTestCompleted(m.value)}else o++}await this.agentCoordinator.stop(i.value),this.completeWorkflow(r);let c={totalTests:e.length,passed:a,failed:o,results:n,bottlenecks:s};return await this.storeReport("load-suite",r,c),f(c)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async assessResilience(e){let r=v();try{if(this.startWorkflow(r,"assessment"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, assessment may be limited"),this.minCutMixin.shouldPauseOperations())return p(new Error("Resilience assessment paused: topology is in critical state"));let i=new Map,n=[],s=[],a=[],o=await this.spawnAssessmentAgent(r);if(!o.success)return this.failWorkflow(r,o.error.message),p(o.error);this.addAgentToWorkflow(r,o.value);for(let d=0;d<e.length;d++){let m=e[d];this.updateWorkflowProgress(r,Math.round((d+1)/e.length*100));let g=await this.performanceProfiler.testRecovery(m,"latency",5e3),h=await this.performanceProfiler.testCircuitBreaker(m),b=await this.performanceProfiler.testRateLimiting(m,100),w=0;if(g.success&&g.value.passed)w+=33.3,n.push(`${m}: Fast recovery (${g.value.recoveryTime}ms)`);else{let C=g.success?g.value.recoveryTime:"unknown";s.push({service:m,type:"recovery",description:"Slow or failed recovery after fault",risk:br.create(.7)}),a.push({priority:"high",category:"recovery",recommendation:`Improve ${m} recovery time - currently ${C}ms`,effort:"moderate"})}h.success&&h.value.passed?(w+=33.3,n.push(`${m}: Circuit breaker functioning correctly`)):(s.push({service:m,type:"circuit-breaker",description:"Circuit breaker not functioning as expected",risk:br.create(.6)}),a.push({priority:"medium",category:"circuit-breaker",recommendation:`Review ${m} circuit breaker configuration`,effort:"minor"})),b.success&&b.value.passed?(w+=33.4,n.push(`${m}: Rate limiting effective`)):(s.push({service:m,type:"rate-limiting",description:"Rate limiting not properly configured",risk:br.create(.5)}),a.push({priority:"medium",category:"rate-limiting",recommendation:`Configure rate limiting for ${m}`,effort:"minor"})),i.set(m,w)}let c=e.length>0?Array.from(i.values()).reduce((d,m)=>d+m,0)/e.length:0;await this.agentCoordinator.stop(o.value),this.completeWorkflow(r);let l={overallScore:c,serviceScores:i,strengths:n,weaknesses:s,recommendations:a};return await this.storeReport("assessment",r,l),f(l)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async generateExperiments(e){let r=v();try{this.startWorkflow(r,"experiment-generation");let i=[];for(let n of e.services){let s=this.generateServiceExperiments(n,e.dependencies);i.push(...s)}for(let n of e.criticalPaths){let s=this.generateCriticalPathExperiment(n,e);i.push(s)}for(let n of i)await this.chaosEngineer.createExperiment(n);return this.completeWorkflow(r),f(i)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async runStrategicChaosSuite(e,r){let i=v();try{if(this.startWorkflow(i,"chaos-suite"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&ie.warn("Topology degraded, adjusting strategic chaos parameters"),this.minCutMixin.shouldPauseOperations())return p(new Error("Strategic chaos suite paused: topology is in critical state"));if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached, cannot spawn chaos agents"));let n=await this.selectChaosStrategy(e,r);if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s=n.value.selectedExperiments;if(ie.info(`[chaos-resilience] Using ${n.value.strategy} strategy with ${s.length} experiments (confidence: ${n.value.confidence.toFixed(2)})`),s.length===0)return this.completeWorkflow(i),f({totalExperiments:0,passed:0,failed:0,results:[],recommendations:[{priority:"low",category:"strategy",recommendation:"No experiments selected - consider adjusting strategy context",effort:"trivial"}]});let a=await this.spawnChaosAgent(i,"coordinator");if(!a.success)return this.failWorkflow(i,a.error.message),p(a.error);this.addAgentToWorkflow(i,a.value);let o=[],c=[],l=0,d=0;for(let g of s)await this.chaosEngineer.createExperiment(g);for(let g=0;g<s.length;g++){let h=s[g];this.updateWorkflowProgress(i,Math.round((g+1)/s.length*100));let b=await this.chaosEngineer.runExperiment(h.id);if(b.success){if(o.push(b.value),b.value.hypothesisValidated)l++;else{d++;let C=this.generateRecommendationsFromExperiment(b.value);c.push(...C)}let w=b.value.hypothesisValidated?.8:.2;await this.storeResiliencePattern(h,b.value,w),this.config.publishEvents&&await this.publishExperimentCompleted(b.value)}else d++,c.push({priority:"high",category:"experiment-failure",recommendation:`Failed to run experiment ${h.name}: ${b.error.message}`,effort:"moderate"})}await this.agentCoordinator.stop(a.value),this.completeWorkflow(i);let m={totalExperiments:s.length,passed:l,failed:d,results:o,recommendations:c};return await this.storeReport("strategic-chaos-suite",i,m),f(m)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async getResilienceDashboard(){try{let e=await this.memory.search("chaos:results:*",10),r=await this.memory.search("loadtest:results:*",10),i,n,s=0,a=0,o=0,c=0,l=0;for(let b of e){let w=await this.memory.get(b);w&&((!i||w.startTime>i)&&(i=w.startTime),s+=w.incidents.filter(C=>!C.resolved).length)}for(let b of r){let w=await this.memory.get(b);if(w&&w.timeline.length>0){let C=w.timeline[0].timestamp;(!n||C>n)&&(n=C),l++,w.status==="failed"&&c++}}let d=o>0?a/o:0,m=l>0?c/l*100:0,g="healthy";return s>5||m>25?g="unhealthy":(s>0||m>10)&&(g="degraded"),f({overallHealth:g,lastExperimentDate:i,lastLoadTestDate:n,activeIncidents:s,uptime:99.9,mttr:d,changeFailureRate:m})}catch(e){return p(y(e))}}async spawnChaosAgent(e,r){let i={name:`chaos-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["chaos-engineering","fault-injection",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnLoadTestAgent(e,r){let i={name:`loadtest-${r}-${e.slice(0,8)}`,domain:"chaos-resilience",type:"specialist",capabilities:["load-testing","performance",r],config:{workflowId:e}};return this.agentCoordinator.spawn(i)}async spawnAssessmentAgent(e){let r={name:`assessment-${e.slice(0,8)}`,domain:"chaos-resilience",type:"analyzer",capabilities:["resilience-assessment","analysis"],config:{workflowId:e}};return this.agentCoordinator.spawn(r)}async publishExperimentCompleted(e){let r={id:v(),type:"chaos-resilience.ExperimentCompleted",timestamp:new Date,source:"chaos-resilience",payload:{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,incidentCount:e.incidents.length}};await this.eventBus.publish(r)}async publishLoadTestCompleted(e){let r={id:v(),type:"chaos-resilience.LoadTestCompleted",timestamp:new Date,source:"chaos-resilience",payload:{testId:e.testId,status:e.status,summary:e.summary,assertionsPassed:e.assertionResults.filter(i=>i.passed).length,assertionsFailed:e.assertionResults.filter(i=>!i.passed).length}};await this.eventBus.publish(r)}generateRecommendationsFromExperiment(e){let r=[];e.hypothesisValidated||r.push({priority:"high",category:"hypothesis-failure",recommendation:`Experiment ${e.experimentId} hypothesis was not validated - review system behavior under fault conditions`,effort:"moderate"}),e.steadyStateVerified||r.push({priority:"critical",category:"steady-state",recommendation:"System did not maintain steady state - investigate stability issues",effort:"major"});for(let i of e.incidents)(i.severity==="critical"||i.severity==="high")&&r.push({priority:i.severity,category:"incident",recommendation:`Address ${i.type}: ${i.message}`,effort:"moderate"});return r}detectBottlenecks(e){let r=[];return e.summary.p95ResponseTime>1e3&&r.push({location:"api",type:"network",description:`P95 response time is ${e.summary.p95ResponseTime}ms (>1000ms)`,impact:e.summary.p95ResponseTime>2e3?"high":"medium",recommendation:"Investigate API response time, consider caching or query optimization"}),e.summary.errorRate>5&&r.push({location:"service",type:"cpu",description:`Error rate is ${e.summary.errorRate.toFixed(2)}% (>5%)`,impact:e.summary.errorRate>10?"high":"medium",recommendation:"Investigate error causes, scale resources if under load"}),e.summary.requestsPerSecond<10&&r.push({location:"backend",type:"io",description:`Low throughput: ${e.summary.requestsPerSecond.toFixed(2)} RPS`,impact:"medium",recommendation:"Review I/O operations, database queries, and connection pooling"}),r}generateServiceExperiments(e,r){let i=[];i.push(this.createExperiment(`${e.name}-latency`,`Test ${e.name} behavior under latency`,"latency",e.name)),i.push(this.createExperiment(`${e.name}-error`,`Test ${e.name} error handling`,"error",e.name)),i.push(this.createExperiment(`${e.name}-cpu-stress`,`Test ${e.name} under CPU stress`,"cpu-stress",e.name));let n=r.filter(s=>s.from===e.name);for(let s of n)s.criticality==="critical"&&i.push(this.createExperiment(`${e.name}-${s.to}-failure`,`Test ${e.name} when ${s.to} fails`,"error",s.to));return i}generateCriticalPathExperiment(e,r){let i=e.join("-");return{id:v(),name:`critical-path-${i}`,description:`Test critical path: ${e.join(" -> ")}`,hypothesis:{statement:"System should handle partial path failure gracefully",metrics:[{metric:"error_rate",operator:"lt",value:10},{metric:"response_time_ms",operator:"lt",value:2e3}],tolerances:[{metric:"error_rate",maxDeviation:5,unit:"percent"}]},steadyState:{description:"All services in path are healthy",probes:e.map(n=>({name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}))},faults:e.slice(0,-1).map(n=>({id:v(),type:"latency",target:{type:"service",selector:n},parameters:{latencyMs:500},duration:3e4})),blastRadius:{scope:"subset",percentage:50,excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 20"},{type:"timeout",condition:"duration > 60000"}],steps:[{order:1,action:"Remove all faults",timeout:5e3},{order:2,action:"Verify service health"}]}}}createExperiment(e,r,i,n){return{id:v(),name:e,description:r,hypothesis:{statement:`${n} should recover within 5 seconds from ${i}`,metrics:[{metric:"response_time_ms",operator:"lt",value:1e3},{metric:"error_rate",operator:"lt",value:5}],tolerances:[{metric:"response_time_ms",maxDeviation:50,unit:"percent"}]},steadyState:{description:`${n} is healthy and responsive`,probes:[{name:`${n}-health`,type:"http",target:`http://${n}/health`,expected:{status:200},timeout:5e3}]},faults:[{id:v(),type:i,target:{type:"service",selector:n},parameters:this.getDefaultFaultParameters(i),duration:3e4}],blastRadius:{scope:"single",excludeProduction:!0},rollbackPlan:{automatic:!0,triggerConditions:[{type:"error-rate",condition:"error_rate > 50"}],steps:[{order:1,action:`Remove ${i} fault`},{order:2,action:"Verify recovery"}]}}}getDefaultFaultParameters(e){return{latency:{latencyMs:500},error:{errorCode:500},timeout:{timeoutMs:3e4},"packet-loss":{packetLossPercent:10},"cpu-stress":{cpuPercent:80},"memory-stress":{memoryBytes:268435456},"disk-stress":{},"network-partition":{},"dns-failure":{},"process-kill":{}}[e]||{}}async storeReport(e,r,i){await this.memory.set(`chaos-resilience:reports:${e}:${r}`,i,{namespace:"chaos-resilience",persist:!0})}async selectChaosStrategy(e,r){if(!this.policyGradient||!this.config.enablePolicyGradient)return f({strategy:"default",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:1,reasoning:"Default strategy (PolicyGradient disabled)"});if(e.length===0)return f({strategy:"empty",selectedExperiments:[],confidence:1,reasoning:"No services provided"});try{let i={id:`chaos-strategy-${Date.now()}`,features:[r.riskTolerance,r.availableCapacity/100,e.length/50,e.filter(l=>!l.hasFailover).length/Math.max(1,e.length),e.filter(l=>l.type==="database").length/Math.max(1,e.length),r.environment==="production"?0:1,r.environment==="staging"?1:0,e.filter(l=>l.type==="cache").length/Math.max(1,e.length),e.filter(l=>l.type==="queue").length/Math.max(1,e.length),e.reduce((l,d)=>l+d.replicas,0)/Math.max(1,e.length*5)]},n=await this.policyGradient.predict(i),s=[],a="default";switch(n.action.type){case"allocate":let l=typeof n.action.value=="object"?n.action.value:null;if(l&&"agentType"in l&&l.agentType==="tester"){let m=e.filter(g=>!g.hasFailover||g.type==="database").slice(0,3);s=this.generateExperimentsForServices(m,["latency","error"]),a="allocate-critical"}break;case"reallocate":let d=typeof n.action.value=="object"?n.action.value:null;d&&"domain"in d&&d.domain==="test-execution"&&(s=this.generateExperimentsForServices(e.slice(0,5),["cpu-stress","memory-stress"]),a="reallocate-resource-stress");break;case"scale-up":s=this.generateExperimentsForServices(e,["latency","error","timeout"]),a="scale-up-comprehensive";break;case"scale-down":s=this.generateExperimentsForServices(e.slice(0,2),["latency"]),a="scale-down-minimal";break;default:s=this.getDefaultExperiments(e.slice(0,3)),a="default";break}let o=await this.calculateStrategyReward(s,r),c=n.action;return await this.policyGradient.train({state:i,action:c,reward:o,nextState:i,done:!0}),ie.info(`[chaos-resilience] PolicyGradient selected ${a} strategy for ${e.length} services (confidence: ${n.confidence.toFixed(2)})`),f({strategy:a,selectedExperiments:s,confidence:n.confidence,reasoning:n.reasoning||`PolicyGradient selected: ${a}`})}catch(i){return ie.error("PolicyGradient strategy selection failed:",i instanceof Error?i:void 0),f({strategy:"fallback",selectedExperiments:this.getDefaultExperiments(e.slice(0,3)),confidence:.5,reasoning:"Fallback to default (PolicyGradient error)"})}}generateExperimentsForServices(e,r){let i=[];for(let n of e)for(let s of r)i.push(this.createExperiment(`${n.name}-${s}-${Date.now()}`,`Test ${n.name} with ${s} fault`,s,n.name));return i}getDefaultExperiments(e){return this.generateExperimentsForServices(e,["latency","error"])}async calculateStrategyReward(e,r){let i=.5,n=e.length;(r.riskTolerance>.7&&n>5||r.riskTolerance<.3&&n<=3)&&(i+=.2),(r.availableCapacity>70&&n>5||r.availableCapacity<30&&n<=3)&&(i+=.1);let s=new Set(e.map(a=>a.faults[0]?.type));return i+=Math.min(.1,s.size/5),Math.max(0,Math.min(1,i))}async storeResiliencePattern(e,r,i){if(!(!this.qesona||!this.config.enableQESONA))try{let n={id:`chaos-${e.id}`,features:[e.faults.length/10,e.faults[0]?.duration?e.faults[0].duration/6e4:0,e.steadyState.probes.length/20,e.blastRadius.excludeProduction?1:0,(e.blastRadius.percentage??0)/100,r.hypothesisValidated?1:0,r.steadyStateVerified?1:0,r.incidents.length/10,r.incidents.filter(a=>a.severity==="critical").length/5,i]},s={type:r.hypothesisValidated?"validate":"reject",value:i};this.qesona.createPattern(n,s,{reward:r.hypothesisValidated?i:-i,success:r.hypothesisValidated,quality:i},"defect-prediction","chaos-resilience",{experimentId:e.id,experimentName:e.name,faultType:e.faults[0]?.type,hypothesisValidated:r.hypothesisValidated}),ie.info(`Stored resilience pattern for ${e.id} (validated: ${r.hypothesisValidated}, quality: ${i.toFixed(2)})`)}catch(n){ie.error("Failed to store resilience pattern:",n instanceof Error?n:void 0)}}async adaptStrategies(e,r){if(!this.qesona||!this.config.enableQESONA)return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5};try{let i={id:`chaos-adapt-${e.name}-${Date.now()}`,features:[e.hasFailover?0:1,r.riskTolerance,e.type==="api"?1:0,e.type==="database"?1:0,e.type==="cache"?1:0,r.environment==="production"?1:0,r.environment==="staging"?1:0,e.replicas/10,e.type==="worker"?1:0,e.type==="queue"?1:0]},n=await this.qesona.adaptPattern(i,"defect-prediction","chaos-resilience");if(n.success&&n.pattern){let s=n.pattern.outcome.success,a=this.getRecommendedFaults(n.pattern.action.type);return ie.info(`[chaos-resilience] QESONA adapted strategy for ${e.name}: shouldRun=${s}, faults=${a.join(",")}, confidence=${n.similarity.toFixed(2)}`),{shouldRunChaos:s,recommendedFaults:a,confidence:n.similarity}}return{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}catch(i){return ie.error("QESONA strategy adaptation failed:",i instanceof Error?i:void 0),{shouldRunChaos:r.environment!=="production",recommendedFaults:["latency","error"],confidence:.5}}}getRecommendedFaults(e){switch(e){case"validate":return["latency","error","timeout"];case"reject":return["latency"];case"allocate":return["latency","cpu-stress"];case"scale-up":return["latency","error","timeout","packet-loss"];case"scale-down":return["latency"];default:return["latency","error"]}}subscribeToEvents(){this.eventBus.subscribe("quality-assessment.DeploymentApproved",this.handleDeploymentApproved.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGateEvaluated.bind(this))}async handleDeploymentApproved(e){if(!this.config.enableAutomatedExperiments)return;let r=e.payload;r.services&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,r.services,{namespace:"chaos-resilience",ttl:3600})}async handleQualityGateEvaluated(e){let r=e.payload;r.passed||await this.memory.set(`chaos-resilience:quality-gate-failures:${e.id}`,r,{namespace:"chaos-resilience",ttl:86400})}async loadWorkflowState(){let e=await this.memory.get("chaos-resilience:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("chaos-resilience:coordinator:workflows",e,{namespace:"chaos-resilience",persist:!0})}async verifyChaosExperiment(e,r){let i=V({id:v(),type:"chaos-experiment",confidence:r,description:`Verify chaos experiment safety: ${e.name} (${e.faultType}) on ${e.target}`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.blastRadius==="full"?"critical":r>.9?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ie.info(`Chaos experiment '${e.name}' verified safe by consensus`),!0):(ie.warn(`Chaos experiment '${e.name}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async verifyResilienceAssessment(e,r){let i=V({id:v(),type:"resilience-assessment",confidence:r,description:`Verify resilience assessment for ${e.service}: score ${e.overallScore}, ${e.weaknessCount} weaknesses`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:e.overallScore<50?"critical":e.overallScore<70?"high":"medium"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ie.info(`Resilience assessment for '${e.service}' verified by consensus`),!0):(ie.warn(`Resilience assessment for '${e.service}' NOT verified`),!1)}return!0}async verifyFailureInjection(e,r){let i=V({id:v(),type:"failure-injection",confidence:r,description:`Verify failure injection: ${e.faultType} on ${e.target} for ${e.duration}ms`,payload:e,detectedBy:"chaos-resilience-coordinator",severity:"critical"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(ie.info(`Failure injection '${e.faultType}' on '${e.target}' verified safe by consensus`),!0):(ie.warn(`Failure injection '${e.faultType}' NOT verified safe: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}};A();var el=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;chaosEngineer=null;loadTester=null;performanceProfiler=null;pluginConfig;get name(){return"chaos-resilience"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{runChaosSuite:this.runChaosSuite.bind(this),runLoadTestSuite:this.runLoadTestSuite.bind(this),assessResilience:this.assessResilience.bind(this),generateExperiments:this.generateExperiments.bind(this),getResilienceDashboard:this.getResilienceDashboard.bind(this),createExperiment:this.createExperiment.bind(this),runExperiment:this.runExperiment.bind(this),abortExperiment:this.abortExperiment.bind(this),verifySteadyState:this.verifySteadyState.bind(this),injectFault:this.injectFault.bind(this),removeFault:this.removeFault.bind(this),createTest:this.createTest.bind(this),runTest:this.runTest.bind(this),runLoadTest:this.runTest.bind(this),stopTest:this.stopTest.bind(this),getRealtimeMetrics:this.getRealtimeMetrics.bind(this),generateFromTraffic:this.generateFromTraffic.bind(this),getExperimentHistory:this.getExperimentHistory.bind(this),testRecovery:this.testRecovery.bind(this),testFailover:this.testFailover.bind(this),testCircuitBreaker:this.testCircuitBreaker.bind(this),testRateLimiting:this.testRateLimiting.bind(this),selectChaosStrategy:this.coordinator.selectChaosStrategy.bind(this.coordinator),runStrategicChaosSuite:this.coordinator.runStrategicChaosSuite.bind(this.coordinator),getCoordinator:()=>this.coordinator,getChaosEngineer:()=>this.chaosEngineer,getChaosEngine:()=>this.chaosEngineer,getLoadTester:()=>this.loadTester,getPerformanceProfiler:()=>this.performanceProfiler,getResilienceAssessor:()=>this.performanceProfiler}}getTaskHandlers(){return new Map([["run-experiment",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.experimentId;return r?this.coordinator.runChaosSuite([r]):p(new Error("Invalid run-experiment payload: missing experimentId"))}],["run-load-test",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.testId;return r?this.coordinator.runLoadTestSuite([r]):p(new Error("Invalid run-load-test payload: missing testId"))}],["assess-resilience",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.services;return!r||r.length===0?p(new Error("Invalid assess-resilience payload: missing services")):this.coordinator.assessResilience(r)}],["inject-fault",async e=>{if(!this.chaosEngineer)return p(new Error("Chaos engineer not initialized"));let r=e.faultType,i=e.target;if(!r||!i)return p(new Error("Invalid inject-fault payload: missing faultType or target"));let n={id:`fault-${Date.now()}`,type:r,target:{type:"service",selector:i},parameters:e.parameters??{},duration:e.duration??3e4,probability:e.probability};return this.chaosEngineer.injectFault(n)}]])}async onInitialize(){this.chaosEngineer=new Ir({memory:this.memory},this.pluginConfig.chaosEngineer),this.loadTester=new Dr(this.memory,this.pluginConfig.loadTester),this.performanceProfiler=new Mr(this.memory,this.pluginConfig.performanceProfiler),this.coordinator=new Ra(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(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"quality-assessment.DeploymentApproved":await this.handleDeploymentApproved(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"security-compliance.VulnerabilityDetected":await this.handleVulnerabilityDetected(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGateEvaluated(e);break;default:break}}async runChaosSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runChaosSuite(e);return r.success?this.trackSuccessfulOperation("chaos-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async runLoadTestSuite(e){this.ensureInitialized();try{let r=await this.coordinator.runLoadTestSuite(e);return r.success?this.trackSuccessfulOperation("load-suite"):this.trackFailedOperation(r.error),r}catch(r){return this.handleError(r)}}async assessResilience(e){this.ensureInitialized();try{return await this.coordinator.assessResilience(e)}catch(r){return this.handleError(r)}}async generateExperiments(e){this.ensureInitialized();try{return await this.coordinator.generateExperiments(e)}catch(r){return this.handleError(r)}}async getResilienceDashboard(){this.ensureInitialized();try{return await this.coordinator.getResilienceDashboard()}catch(e){return this.handleError(e)}}async createExperiment(e){this.ensureInitialized();try{return await this.chaosEngineer.createExperiment(e)}catch(r){return this.handleError(r)}}async runExperiment(e){this.ensureInitialized();try{let r=await this.chaosEngineer.runExperiment(e);return r.success&&await this.publishExperimentEvent(r.value),r}catch(r){return this.handleError(r)}}async abortExperiment(e,r){this.ensureInitialized();try{return await this.chaosEngineer.abortExperiment(e,r)}catch(i){return this.handleError(i)}}async verifySteadyState(e){this.ensureInitialized();try{return await this.chaosEngineer.verifySteadyState(e)}catch(r){return this.handleError(r)}}async injectFault(e){this.ensureInitialized();try{return await this.chaosEngineer.injectFault(e)}catch(r){return this.handleError(r)}}async removeFault(e){this.ensureInitialized();try{return await this.chaosEngineer.removeFault(e)}catch(r){return this.handleError(r)}}async getExperimentHistory(){this.ensureInitialized();try{return{success:!0,value:await this.memory.get("chaos-resilience:experiment-history")??[]}}catch(e){return this.handleError(e)}}async createTest(e){this.ensureInitialized();try{return await this.loadTester.createTest(e)}catch(r){return this.handleError(r)}}async runTest(e){this.ensureInitialized();try{let r=await this.loadTester.runTest(e);return r.success&&await this.publishLoadTestEvent(r.value),r}catch(r){return this.handleError(r)}}async stopTest(e){this.ensureInitialized();try{return await this.loadTester.stopTest(e)}catch(r){return this.handleError(r)}}async getRealtimeMetrics(e){this.ensureInitialized();try{return await this.loadTester.getRealtimeMetrics(e)}catch(r){return this.handleError(r)}}async generateFromTraffic(e,r){this.ensureInitialized();try{return await this.loadTester.generateFromTraffic(e,r)}catch(i){return this.handleError(i)}}async testRecovery(e,r,i){this.ensureInitialized();try{return await this.performanceProfiler.testRecovery(e,r,i)}catch(n){return this.handleError(n)}}async testFailover(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testFailover(e,r)}catch(i){return this.handleError(i)}}async testCircuitBreaker(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testCircuitBreaker(e,r)}catch(i){return this.handleError(i)}}async testRateLimiting(e,r){this.ensureInitialized();try{return await this.performanceProfiler.testRateLimiting(e,r)}catch(i){return this.handleError(i)}}async handleDeploymentApproved(e){let r=e.payload;r.services&&r.services.length>0&&await this.memory.set(`chaos-resilience:pending-assessment:${e.id}`,{services:r.services,triggeredAt:new Date,source:"deployment-approved"},{namespace:"chaos-resilience",ttl:3600})}async handleTestRunCompleted(e){let r=e.payload;await this.memory.set(`chaos-resilience:test-baseline:${r.runId}`,{duration:r.duration,successRate:r.passed/(r.passed+r.failed),timestamp:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleVulnerabilityDetected(e){let r=e.payload;(r.severity==="critical"||r.severity==="high")&&await this.memory.set(`chaos-resilience:security-tests:${r.vulnId}`,{vulnerabilityId:r.vulnId,severity:r.severity,file:r.file,triggeredAt:new Date},{namespace:"chaos-resilience",ttl:86400})}async handleQualityGateEvaluated(e){let r=e.payload;r.checks?.some(n=>n.name==="resilience")&&await this.memory.set(`chaos-resilience:gate-context:${r.gateId}`,{gateId:r.gateId,passed:r.passed,checks:r.checks,timestamp:Date.now()},{namespace:"chaos-resilience",ttl:3600})}async publishExperimentEvent(e){await this.publishEvent("chaos-resilience.ExperimentCompleted",{experimentId:e.experimentId,status:e.status,hypothesisValidated:e.hypothesisValidated,steadyStateVerified:e.steadyStateVerified,faultCount:e.faultResults.length,incidentCount:e.incidents.length,duration:e.endTime?e.endTime.getTime()-e.startTime.getTime():0})}async publishLoadTestEvent(e){await this.publishEvent("chaos-resilience.LoadTestCompleted",{testId:e.testId,status:e.status,duration:e.duration,totalRequests:e.summary.totalRequests,successRate:e.summary.totalRequests>0?e.summary.successfulRequests/e.summary.totalRequests*100:0,p95ResponseTime:e.summary.p95ResponseTime,errorRate:e.summary.errorRate,assertionsPassed:e.assertionResults.filter(r=>r.passed).length,assertionsFailed:e.assertionResults.filter(r=>!r.passed).length})}ensureInitialized(){if(!this._initialized)throw new Error("ChaosResiliencePlugin is not initialized");if(!this.coordinator||!this.chaosEngineer||!this.loadTester||!this.performanceProfiler)throw new Error("ChaosResiliencePlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Am(u,t,e,r){return new el(u,t,e,r)}M();A();M();A();var Nv={minExperiencesForPattern:5,patternConfidenceThreshold:.7,maxPatternsPerDomain:100,anomalyDeviationThreshold:2,clusterSimilarityThreshold:.8,enableLLMSynthesis:!0,llmModelTier:2,llmMaxTokens:2048},Em=R.create("learning-optimization/learning-coordinator"),Gt=class{config;memory;llmRouter;flashAttention=null;constructor(t,e={}){this.memory=t.memory,this.llmRouter=t.llmRouter,this.config={...Nv,...e}}async initializeFlashAttention(t){return this.flashAttention=await Ie("pattern-adaptation",t),Em.info("FlashAttention initialized for pattern adaptation"),this.flashAttention}injectFlashAttention(t){this.flashAttention=t}isFlashAttentionAvailable(){return this.flashAttention!==null}getFlashAttentionMetrics(){return this.flashAttention?this.flashAttention.getMetrics():[]}async computeSimilarityWithFlashAttention(t,e){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let r=Math.min(t.length,e.length),i=new Float32Array(r),n=new Float32Array(r),s=new Float32Array(r);for(let c=0;c<r;c++)i[c]=t[c],n[c]=e[c],s[c]=1;let a=await this.flashAttention.computeFlashAttention(i,n,s,1,r),o=Math.abs(a[0]);return Math.min(1,o)}async batchComputeSimilarities(t,e,r=5){if(!this.flashAttention)throw new Error("[LearningCoordinatorService] FlashAttention not initialized. Call initializeFlashAttention() first.");let i=new Float32Array(t),n=e.map(s=>new Float32Array(s));return this.flashAttention.computeTestSimilarity(i,n,r)}disposeFlashAttention(){this.flashAttention&&(this.flashAttention.dispose(),this.flashAttention=null)}isLLMSynthesisAvailable(){return this.config.enableLLMSynthesis&&this.llmRouter!==void 0}getModelForTier(t){let e={1:"claude-haiku-4-5",2:"claude-sonnet-4-6",3:"claude-sonnet-4-6",4:"claude-opus-4-7"};return e[t]||e[2]}async synthesizePatternsWithLLM(t){if(!this.isLLMSynthesisAvailable())return null;try{let e=t.slice(0,10).map(i=>`- ${i.name}: ${i.type} (confidence: ${i.confidence.toFixed(2)})`).join(`
3013
3013
  `);return(await this.llmRouter.chat({model:this.getModelForTier(this.config.llmModelTier),messages:[{role:"user",content:`Analyze these learned QE patterns and synthesize insights:
3014
3014
  ${e}
3015
3015
 
@@ -3019,4 +3019,4 @@ Provide:
3019
3019
  3. Recommendations for pattern application`}],maxTokens:this.config.llmMaxTokens})).content}catch{return Em.warn("LLM synthesis failed:"),null}}async learnPattern(t){try{if(t.length<this.config.minExperiencesForPattern)return p(new Error(`Need at least ${this.config.minExperiencesForPattern} experiences to learn a pattern`));let e=this.extractCommonActions(t),r=this.calculateSuccessRate(t);if(r<this.config.patternConfidenceThreshold)return p(new Error(`Success rate ${r} below threshold ${this.config.patternConfidenceThreshold}`));let i=this.inferPatternType(t),n=t[0].domain,s=this.generatePatternTemplate(t,e),a=this.extractPatternContext(t),o={id:v(),type:i,domain:n,name:`${i}-${n}-${Date.now()}`,description:`Learned pattern from ${t.length} experiences with ${r*100}% success rate`,confidence:r,usageCount:0,successRate:r,context:a,template:s,createdAt:new Date,lastUsedAt:new Date};return await this.storePattern(o),await this.recordPatternCreation(o,t),f(o)}catch(e){return p(y(e))}}async findMatchingPatterns(t,e=10){try{let r=[],i=await this.memory.search("learning:pattern:*",100);for(let n of i){let s=await this.memory.get(n);s&&this.matchesContext(s,t)&&r.push(s)}return r.sort((n,s)=>{let a=n.confidence*.6+n.successRate*.4;return s.confidence*.6+s.successRate*.4-a}),f(r.slice(0,e))}catch(r){return p(y(r))}}async applyPattern(t,e){try{let r=t.template.content;for(let i of t.template.variables){let n=e[i.name]??i.defaultValue;if(i.required&&n===void 0)return p(new Error(`Required variable ${i.name} not provided`));r=r.replace(new RegExp(`\\{\\{${i.name}\\}\\}`,"g"),String(n??""))}return await this.updatePatternUsage(t.id),f(r)}catch(r){return p(y(r))}}async updatePatternFeedback(t,e){try{let r=`learning:pattern:${t}`,i=await this.memory.get(r);if(!i)return p(new Error(`Pattern ${t} not found`));let n=.1,s=n*(e?1:0)+(1-n)*i.successRate,a=Math.min(i.usageCount/100,1),o=s*.7+a*.3,c={...i,successRate:s,confidence:o,usageCount:i.usageCount+1,lastUsedAt:new Date};return await this.memory.set(r,c,{namespace:"learning-optimization",persist:!0}),f(void 0)}catch(r){return p(y(r))}}async consolidatePatterns(t){try{if(t.length<2)return p(new Error("Need at least 2 patterns to consolidate"));let e=[];for(let s of t){let a=await this.memory.get(`learning:pattern:${s}`);a&&e.push(a)}if(e.length<2)return p(new Error("Not enough valid patterns found"));let r=e.reduce((s,a)=>a.successRate>s.successRate?a:s),i={language:r.context.language,framework:r.context.framework,testType:r.context.testType,codeContext:r.context.codeContext,tags:[...new Set(e.flatMap(s=>s.context.tags))]},n={id:v(),type:r.type,domain:r.domain,name:`consolidated-${r.name}`,description:`Consolidated from ${e.length} patterns`,confidence:this.calculateConsolidatedConfidence(e),usageCount:e.reduce((s,a)=>s+a.usageCount,0),successRate:this.calculateWeightedSuccessRate(e),context:i,template:r.template,createdAt:new Date,lastUsedAt:new Date};await this.storePattern(n);for(let s of e)await this.archivePattern(s.id);return f(n)}catch(e){return p(y(e))}}async getPatternStats(t){try{let e=await this.memory.search("learning:pattern:*",500),r=[];for(let c of e){let l=await this.memory.get(c);l&&(!t||l.domain===t)&&r.push(l)}let i={"test-pattern":0,"fix-pattern":0,"optimization-pattern":0,"detection-pattern":0,"workflow-pattern":0,"failure-pattern":0},n={"test-generation":0,"test-execution":0,"coverage-analysis":0,"quality-assessment":0,"defect-intelligence":0,"requirements-validation":0,"code-intelligence":0,"security-compliance":0,"contract-testing":0,"visual-accessibility":0,"chaos-resilience":0,"learning-optimization":0,"enterprise-integration":0,coordination:0},s=0,a=0;for(let c of r)i[c.type]++,n[c.domain]++,s+=c.confidence,a+=c.successRate;let o=r.sort((c,l)=>l.successRate-c.successRate).slice(0,10);return f({totalPatterns:r.length,byType:i,byDomain:n,avgConfidence:r.length>0?s/r.length:0,avgSuccessRate:r.length>0?a/r.length:0,topPatterns:o})}catch(e){return p(y(e))}}async recordExperience(t){try{let e=v(),r={...t,id:e,timestamp:new Date};return await this.memory.set(`learning:experience:${e}`,r,{namespace:"learning-optimization",ttl:86400*30}),await this.indexExperience(r),f(e)}catch(e){return p(y(e))}}async mineExperiences(t,e){try{let r=await this.getExperiencesByDomainAndTime(t,e);if(r.length===0)return f({experienceCount:0,successRate:0,avgReward:0,patterns:[],anomalies:[],recommendations:["No experiences found in the given time range"]});let i=this.calculateSuccessRate(r),n=this.calculateAverageReward(r),s=await this.extractPatternsFromExperiences(r),a=this.detectAnomalies(r),o=this.generateRecommendations(r,i,a);return f({experienceCount:r.length,successRate:i,avgReward:n,patterns:s,anomalies:a,recommendations:o})}catch(r){return p(y(r))}}calculateReward(t,e){let r=t.outcome[e.metric]??0,i;e.direction==="maximize"?i=Math.min(r/100,1):i=Math.max(1-r/100,0);let n=0;for(let o of e.constraints){let c=t.outcome[o.metric]??0;this.isConstraintViolated(o,c)&&(n+=.2)}let s=t.success?.5:0,a=Math.max(0,i+s-n);return Math.min(1,a)}async getReplayBuffer(t,e=100){try{let r=await this.memory.search(`learning:experience:index:agent:${t.value}:*`,e),i=[];for(let n of r){let s=await this.memory.get(n);if(s){let a=await this.memory.get(`learning:experience:${s}`);a&&i.push(a)}}return i.sort((n,s)=>s.timestamp.getTime()-n.timestamp.getTime()),f(i.slice(0,e))}catch(r){return p(y(r))}}async clusterExperiences(t){try{if(t.length===0)return f([]);let e=new Map;for(let n of t){let s=!1;for(let[a,o]of e)if(this.actionsSimilar(n.action,a)){o.push(n),s=!0;break}s||e.set(n.action,[n])}let r=[],i=0;for(let[n,s]of e)if(s.length>=2){let a=this.calculateCentroid(s),o=this.extractCommonActions(s),c=this.calculateAverageReward(s);r.push({id:`cluster-${i++}`,centroid:a,experiences:s,commonActions:o,avgReward:c})}return f(r)}catch(e){return p(y(e))}}async storePattern(t){await this.memory.set(`learning:pattern:${t.id}`,t,{namespace:"learning-optimization",persist:!0})}async archivePattern(t){let e=`learning:pattern:${t}`,r=await this.memory.get(e);r&&(await this.memory.set(`learning:pattern:archived:${t}`,r,{namespace:"learning-optimization",persist:!0}),await this.memory.delete(e))}async updatePatternUsage(t){let e=`learning:pattern:${t}`,r=await this.memory.get(e);if(r){let i={...r,usageCount:r.usageCount+1,lastUsedAt:new Date};await this.memory.set(e,i,{namespace:"learning-optimization",persist:!0})}}async recordPatternCreation(t,e){await this.memory.set(`learning:pattern:creation:${t.id}`,{patternId:t.id,experienceIds:e.map(r=>r.id),createdAt:new Date},{namespace:"learning-optimization",persist:!0})}async indexExperience(t){await this.memory.set(`learning:experience:index:agent:${t.agentId.value}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:86400*30}),await this.memory.set(`learning:experience:index:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:86400*30})}async getExperiencesByDomainAndTime(t,e){let r=await this.memory.search(`learning:experience:index:domain:${t}:*`,1e3),i=[];for(let n of r){let s=await this.memory.get(n);if(s){let a=await this.memory.get(`learning:experience:${s}`);a&&e.contains(a.timestamp)&&i.push(a)}}return i}async extractPatternsFromExperiences(t){let e=t.filter(n=>n.result.success),r=new Map;for(let n of e){let s=r.get(n.action)||[];s.push(n),r.set(n.action,s)}let i=[];for(let[n,s]of r)if(s.length>=this.config.minExperiencesForPattern){let a=await this.learnPattern(s);a.success&&i.push(a.value)}return i}matchesContext(t,e){return!(e.language&&t.context.language!==e.language||e.framework&&t.context.framework!==e.framework||e.testType&&t.context.testType!==e.testType||e.tags.length>0&&!e.tags.some(i=>t.context.tags.includes(i)))}extractCommonActions(t){let e=new Map;for(let r of t){let i=e.get(r.action)||0;e.set(r.action,i+1)}return Array.from(e.entries()).filter(([r,i])=>i>=t.length*.3).map(([r])=>r)}calculateAverageReward(t){return t.length===0?0:t.reduce((r,i)=>r+i.reward,0)/t.length}calculateSuccessRate(t){return t.length===0?0:t.filter(r=>r.result.success).length/t.length}inferPatternType(t){let e=t.map(r=>r.action.toLowerCase());return e.some(r=>r.includes("test")||r.includes("generate"))?"test-pattern":e.some(r=>r.includes("fix")||r.includes("repair"))?"fix-pattern":e.some(r=>r.includes("optimize")||r.includes("improve"))?"optimization-pattern":e.some(r=>r.includes("detect")||r.includes("find"))?"detection-pattern":e.some(r=>r.includes("workflow")||r.includes("process"))?"workflow-pattern":e.some(r=>r.includes("fail")||r.includes("error"))?"failure-pattern":"workflow-pattern"}generatePatternTemplate(t,e){let r=[{name:"domain",type:"string",required:!0,description:"Target domain for the pattern"},{name:"action",type:"string",required:!0,defaultValue:e[0],description:"Primary action to execute"}];return{type:"workflow",content:`// Pattern learned from ${t.length} experiences
3020
3020
  // Common actions: ${e.join(", ")}
3021
3021
  // Apply to domain: {{domain}}
3022
- // Execute action: {{action}}`,variables:r}}extractPatternContext(t){let e=new Set,r,i;for(let n of t){let s=n.state.context;if(s.language&&(r=s.language),s.framework&&(i=s.framework),s.tags&&Array.isArray(s.tags))for(let a of s.tags)e.add(a)}return{language:r,framework:i,tags:Array.from(e)}}calculateConsolidatedConfidence(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.confidence*n}return r}calculateWeightedSuccessRate(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.successRate*n}return r}detectAnomalies(t){let e=[],r=this.calculateAverageReward(t),i=this.calculateStdDev(t.map(n=>n.reward));for(let n of t){let s=Math.abs(n.reward-r)/(i||1);if(s>this.config.anomalyDeviationThreshold){let a="outlier-reward";n.result.success&&n.reward<r?a="unexpected-success":!n.result.success&&n.reward>r&&(a="unexpected-failure"),e.push({experienceId:n.id,type:a,description:`Reward ${n.reward.toFixed(2)} deviates ${s.toFixed(2)} std from mean ${r.toFixed(2)}`,deviation:s})}}return e}calculateStdDev(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}generateRecommendations(t,e,r){let i=[];return e<.5&&i.push("Low success rate detected. Consider reviewing the approach or gathering more training data."),r.length>t.length*.1&&i.push("High anomaly rate detected. Investigate unexpected outcomes for potential improvements."),t.reduce((s,a)=>s+a.result.duration,0)/t.length>6e4&&i.push("Average operation duration is high. Consider optimizing performance."),t.length<10&&i.push("Limited experience data. Collect more data points for better insights."),i.length===0&&i.push("Performance metrics are within acceptable ranges. Continue monitoring."),i}actionsSimilar(t,e){let r=s=>s.toLowerCase().replace(/[^a-z]/g,""),i=r(t),n=r(e);return!!(i===n||i.includes(n)||n.includes(i))}calculateCentroid(t){let e={},r={};for(let i of t)for(let[n,s]of Object.entries(i.state.metrics))e[n]=(e[n]||0)+s,r[n]=(r[n]||0)+1;for(let i of Object.keys(e))e[i]/=r[i];return{context:{},metrics:e}}isConstraintViolated(t,e){switch(t.operator){case"lt":return e>=t.value;case"gt":return e<=t.value;case"lte":return e>t.value;case"gte":return e<t.value;case"eq":return e!==t.value;default:return!1}}};A();var Vv={maxKnowledgeItems:1e3,relevanceThreshold:.5,transferDecayFactor:.1,crossDomainBoost:.2},Ht=class{constructor(t,e={}){this.memory=t;this.config={...Vv,...e}}memory;config;async shareKnowledge(t,e){try{await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0});for(let r of e)await this.memory.set(`learning:knowledge:access:${r.value}:${t.id}`,{knowledgeId:t.id,agentId:r.value,sharedAt:new Date,accessed:!1},{namespace:"learning-optimization",ttl:86400*7});return await this.recordSharingEvent(t,e),f(void 0)}catch(r){return p(y(r))}}async queryKnowledge(t){try{let e=[],r;t.domain?r=await this.memory.search(`learning:knowledge:*:${t.domain}:*`,t.limit||100):r=await this.memory.search("learning:knowledge:shared:*",t.limit||100);for(let i of r){let n=await this.memory.get(i);n&&this.matchesQuery(n,t)&&e.push(n)}if(e.sort((i,n)=>n.relevanceScore-i.relevanceScore),t.embedding&&t.embedding.length>0){let i=await this.memory.vectorSearch(t.embedding,t.limit||10);for(let n of i){let s=await this.memory.get(n.key);s&&!e.some(a=>a.id===s.id)&&this.matchesQuery(s,t)&&e.push(s)}}return f(e.slice(0,t.limit||100))}catch(e){return p(y(e))}}async synthesizeKnowledge(t){try{if(t.length<2)return p(new Error("Need at least 2 knowledge items to synthesize"));let e=[];for(let c of t){let l=await this.getKnowledgeById(c);l&&e.push(l)}if(e.length<2)return p(new Error("Not enough valid knowledge items found"));let r=this.determineSynthesizedType(e),i=this.determineSynthesizedDomain(e),n=this.mergeKnowledgeContent(e),s=e.reduce((c,l)=>c+l.relevanceScore,0)/e.length,a=Math.min(1,s+this.config.crossDomainBoost),o={id:v(),type:r,domain:i,content:n,sourceAgentId:e[0].sourceAgentId,targetDomains:this.mergeTargetDomains(e),relevanceScore:a,version:1,createdAt:new Date};return await this.storeKnowledge(o),await this.recordSynthesisEvent(o,t),f(o)}catch(e){return p(y(e))}}async transferKnowledge(t,e){try{if(t.domain===e)return p(new Error("Cannot transfer knowledge to the same domain"));let r=this.calculateTransferredRelevance(t,e);if(r<this.config.relevanceThreshold)return p(new Error(`Transferred relevance ${r} below threshold ${this.config.relevanceThreshold}`));let i=await this.adaptContentForDomain(t.content,t.domain,e),n={id:v(),type:t.type,domain:e,content:i,sourceAgentId:t.sourceAgentId,targetDomains:[e],relevanceScore:r,version:t.version+1,createdAt:new Date};return await this.storeKnowledge(n),await this.recordTransferEvent(t,n),f(n)}catch(r){return p(y(r))}}async validateRelevance(t,e){try{let r=t.relevanceScore;if(e.language&&t.content.metadata?.language===e.language&&(r+=.1),e.framework&&t.content.metadata?.framework===e.framework&&(r+=.1),e.tags.length>0&&t.content.metadata?.tags){let a=t.content.metadata.tags,o=e.tags.filter(c=>a.includes(c));r+=o.length/e.tags.length*.2}let n=(Date.now()-t.createdAt.getTime())/(1e3*60*60*24),s=Math.exp(-this.config.transferDecayFactor*n/30);return r*=s,t.expiresAt&&new Date>t.expiresAt&&(r*=.5),f(Math.min(1,Math.max(0,r)))}catch(r){return p(y(r))}}async createKnowledge(t,e,r,i,n=[],s){try{let a={id:v(),type:t,domain:e,content:{format:this.inferContentFormat(r),data:r,metadata:s},sourceAgentId:i,targetDomains:n,relevanceScore:1,version:1,createdAt:new Date};return await this.storeKnowledge(a),t==="embedding"&&Array.isArray(r)&&await this.memory.storeVector(`learning:knowledge:vector:${a.id}`,r,{knowledgeId:a.id}),f(a)}catch(a){return p(y(a))}}async getKnowledgeById(t){return await this.memory.get(`learning:knowledge:shared:${t}`)||null}async bulkTransfer(t,e,r){try{let i=await this.memory.search(`learning:knowledge:project:${t}:*`,500),n=[];for(let s of i){let a=await this.memory.get(s);if(!a||r?.types&&!r.types.includes(a.type)||r?.minRelevance&&a.relevanceScore<r.minRelevance)continue;let o=await this.adaptContentForProject(a.content,t,e),c={...a,id:v(),content:o,relevanceScore:a.relevanceScore*(1-this.config.transferDecayFactor),version:a.version+1,createdAt:new Date};await this.memory.set(`learning:knowledge:project:${e}:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),n.push({knowledgeId:c.id,sourceDomain:a.domain,targetDomain:a.domain,originalRelevance:a.relevanceScore,transferredRelevance:c.relevanceScore,adaptations:["project-context-adapted"]})}return f(n)}catch(i){return p(y(i))}}async storeKnowledge(t){await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:type:${t.type}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}matchesQuery(t,e){if(e.type&&t.type!==e.type||e.domain&&t.domain!==e.domain||e.minRelevance!==void 0&&t.relevanceScore<e.minRelevance)return!1;if(e.tags&&e.tags.length>0){let r=t.content.metadata?.tags||[];if(!e.tags.some(n=>r.includes(n)))return!1}return!0}determineSynthesizedType(t){let e=new Map;for(let n of t)e.set(n.type,(e.get(n.type)||0)+1);let r=t[0].type,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}determineSynthesizedDomain(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r=t[0].domain,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}mergeKnowledgeContent(t){let e={},r=[];for(let i of t)if(r.push(i.content.data),i.content.metadata)for(let[n,s]of Object.entries(i.content.metadata))if(Array.isArray(s)){let a=e[n]||[];e[n]=[...new Set([...a,...s])]}else e[n]=s;return{format:"json",data:{synthesized:!0,sources:r},metadata:{...e,synthesizedFrom:t.map(i=>i.id),synthesizedAt:new Date().toISOString()}}}mergeTargetDomains(t){let e=new Set;for(let r of t){e.add(r.domain);for(let i of r.targetDomains)e.add(i)}return Array.from(e)}calculateTransferredRelevance(t,e){let r=t.relevanceScore;r*=1-this.config.transferDecayFactor;let i=this.getDomainCompatibility(t.domain,e);return r*=i,t.targetDomains.includes(e)&&(r+=this.config.crossDomainBoost),Math.min(1,Math.max(0,r))}getDomainCompatibility(t,e){let r={"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"],"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:be.filter(i=>i!=="coordination")};return t===e?1:r[t]?.includes(e)?.8:.5}async adaptContentForDomain(t,e,r){return{...t,metadata:{...t.metadata||{},adaptedFrom:e,adaptedTo:r,adaptedAt:new Date().toISOString()}}}async adaptContentForProject(t,e,r){return{...t,metadata:{...t.metadata||{},sourceProject:e,targetProject:r,transferredAt:new Date().toISOString()}}}inferContentFormat(t){return typeof t=="string"?"text":Array.isArray(t)&&t.every(e=>typeof e=="number")?"embedding":"json"}async recordSharingEvent(t,e){await this.memory.set(`learning:knowledge:events:share:${t.id}:${Date.now()}`,{type:"share",knowledgeId:t.id,targetAgents:e.map(r=>r.value),timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordSynthesisEvent(t,e){await this.memory.set(`learning:knowledge:events:synthesis:${t.id}`,{type:"synthesis",synthesizedId:t.id,sourceIds:e,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordTransferEvent(t,e){await this.memory.set(`learning:knowledge:events:transfer:${e.id}`,{type:"transfer",originalId:t.id,transferredId:e.id,originalDomain:t.domain,targetDomain:e.domain,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}};A();se();var _v={defaultConfidenceLevel:.95,minSamplesForOptimization:20,maxOptimizationIterations:100,improvementThreshold:.05,explorationRate:.1},zv=["__proto__","constructor","prototype"];function Ui(u){return!zv.includes(u)}var Wt=class{constructor(t,e={}){this.memory=t;this.config={..._v,...e}}memory;config;async optimizeStrategy(t,e,r){try{if(r.length<this.config.minSamplesForOptimization)return p(new Error(`Need at least ${this.config.minSamplesForOptimization} experiences for optimization`));let i=this.evaluateStrategyPerformance(t,r,e),n=await this.optimizeParameters(t.parameters,r,e),s={name:`${t.name}-optimized`,parameters:n,expectedOutcome:this.predictOutcome(n,r)},a=await this.validateOptimization(t,s,r.slice(-10)),o=this.evaluateStrategyPerformance(s,r,e),c=this.calculateImprovement(i,o,e),l=this.calculateOptimizationConfidence(r.length,c,a),d=this.inferDomainFromExperiences(r),m={id:v(),domain:d,objective:e,currentStrategy:t,optimizedStrategy:s,improvement:c,confidence:l,validationResults:a};return await this.storeOptimizationResult(m),f(m)}catch(i){return p(y(i))}}async runABTest(t,e,r){try{let i=await this.collectStrategyMetrics(t,r.metric,r.minSamples),n=await this.collectStrategyMetrics(e,r.metric,r.minSamples),s=this.calculateMean(i),a=this.calculateMean(n),o=this.calculateStdDev(i),c=this.calculateStdDev(n),l=this.calculatePValue(i,n),d;l<1-r.confidenceLevel?d=s>a?"A":"B":d="inconclusive";let m={winner:d,strategyAMetrics:{[r.metric]:s,stdDev:o,samples:i.length},strategyBMetrics:{[r.metric]:a,stdDev:c,samples:n.length},pValue:l,sampleSizeA:i.length,sampleSizeB:n.length};return await this.storeABTestResult(t,e,m),f(m)}catch(i){return p(y(i))}}async recommendStrategy(t){try{let e=await this.memory.search("learning:strategy:optimized:*",100),r=[];for(let i of e){let n=await this.memory.get(i);if(n&&n.confidence>.6){let s=this.scoreContextMatch(n,t),a=n.improvement*n.confidence;r.push({strategy:n.optimizedStrategy,score:s*.4+a*.6})}}return r.length===0?f({name:"default-strategy",parameters:this.getDefaultParameters(t),expectedOutcome:{success_rate:.7}}):(r.sort((i,n)=>n.score-i.score),f(r[0].strategy))}catch(e){return p(y(e))}}async evaluateStrategy(t,e){try{let r={},i=this.calculateSuccessRate(e),n=this.calculateAverageDuration(e),s=this.calculateAverageReward(e);r.success_rate=i,r.avg_duration_ms=n,r.avg_reward=s;let a=[];i>.8&&a.push("High success rate"),n<5e3&&a.push("Fast execution"),s>.7&&a.push("Consistently good rewards");let o=[];i<.5&&o.push("Low success rate needs investigation"),n>3e4&&o.push("Slow execution time"),s<.3&&o.push("Low reward values");let c=this.identifyImprovementAreas(t,r,e),l={strategy:t,metrics:r,strengths:a,weaknesses:o,improvementAreas:c};return await this.storeStrategyEvaluation(l),f(l)}catch(r){return p(y(r))}}async trackMetrics(t,e){try{let r={strategyId:t,metrics:e,timestamp:new Date,samples:1},i=`learning:metrics:history:${t}:${Date.now()}`;return await this.memory.set(i,r,{namespace:"learning-optimization",ttl:86400*30}),await this.updateAggregatedMetrics(t,e),f(void 0)}catch(r){return p(y(r))}}async getMetricsHistory(t,e=100){try{let r=await this.memory.search(`learning:metrics:history:${t}:*`,e),i=[];for(let n of r){let s=await this.memory.get(n);s&&i.push(s)}return i.sort((n,s)=>n.timestamp.getTime()-s.timestamp.getTime()),f(i)}catch(r){return p(y(r))}}async gridSearchOptimize(t,e,r){try{let i=this.generateParameterCombinations(t),n={},s=e.direction==="maximize"?-1/0:1/0;for(let a of i){let o=this.scoreParameters(a,r,e);(e.direction==="maximize"?o>s:o<s)&&(s=o,n=a)}return f(n)}catch(i){return p(y(i))}}evaluateStrategyPerformance(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.outcome[r.metric]??0;i+=a,n++}return n>0?i/n:0}async optimizeParameters(t,e,r){let i={...t};for(let[n,s]of Object.entries(t))if(Ui(n)&&typeof s=="number"){let a=[-.1,-.05,0,.05,.1],o=0,c=this.scoreParameters(i,e,r);for(let l of a){let d={...i,[n]:s*(1+l)},m=this.scoreParameters(d,e,r);(r.direction==="maximize"?m>c:m<c)&&(c=m,o=l)}i[n]=s*(1+o)}return i}scoreParameters(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.success?1:.5,o=this.calculateParamSimilarity(t,s.state.context),c=s.result.outcome[r.metric]??0;i+=o*c*a,n+=a}return n>0?i/n:0}calculateParamSimilarity(t,e){let r=0,i=0;for(let[n,s]of Object.entries(t))if(e[n]!==void 0)if(i++,typeof s=="number"&&typeof e[n]=="number"){let a=Math.abs(s-e[n]),o=Math.max(Math.abs(s),Math.abs(e[n]),1);r+=1-a/o}else s===e[n]&&r++;return i>0?r/i:.5}predictOutcome(t,e){let r={},i={},n={};for(let s of e)if(s.result.success)for(let[a,o]of Object.entries(s.result.outcome))Ui(a)&&typeof o=="number"&&(i[a]=(i[a]||0)+o,n[a]=(n[a]||0)+1);for(let[s,a]of Object.entries(i))Ui(s)&&(r[s]=a/n[s]);return r}async validateOptimization(t,e,r){let i=[];for(let n of r){let s=e.expectedOutcome,a=Object.entries(s).every(([o,c])=>{let l=n.result.outcome[o]??0;return Math.abs(l-c)/Math.max(c,1)<.2});i.push({testId:n.id,passed:a,metrics:n.state.metrics})}return i}calculateImprovement(t,e,r){if(t===0)return e>0?1:0;let i=e-t,n=r.direction==="maximize"?i/t:-i/t;return Math.max(-1,Math.min(1,n))}calculateOptimizationConfidence(t,e,r){let i=Math.min(1,t/(this.config.minSamplesForOptimization*2)),n=r.filter(a=>a.passed).length/Math.max(r.length,1),s=Math.abs(e)>this.config.improvementThreshold?1:.5;return i*.3+n*.5+s*.2}inferDomainFromExperiences(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r="learning-optimization",i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}async collectStrategyMetrics(t,e,r){let i=await this.memory.search("learning:metrics:history:*:*",r*2),n=[];for(let s of i){let a=await this.memory.get(s);a&&a.metrics[e]!==void 0&&n.push(a.metrics[e])}for(;n.length<r;){let s=t.expectedOutcome[e]||.5,a=(L()-.5)*.2;n.push(s+a)}return n}calculateMean(t){return t.length===0?0:t.reduce((e,r)=>e+r,0)/t.length}calculateStdDev(t){if(t.length===0)return 0;let e=this.calculateMean(t),r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}calculatePValue(t,e){let r=this.calculateMean(t),i=this.calculateMean(e),n=Math.pow(this.calculateStdDev(t),2),s=Math.pow(this.calculateStdDev(e),2),a=t.length,o=e.length,c=Math.sqrt(n/a+s/o);if(c===0)return .5;let l=Math.abs(r-i)/c,d=2*(1-this.normalCDF(l));return Math.max(0,Math.min(1,d))}normalCDF(t){let e=.254829592,r=-.284496736,i=1.421413741,n=-1.453152027,s=1.061405429,a=.3275911,o=t<0?-1:1;t=Math.abs(t)/Math.sqrt(2);let c=1/(1+a*t),l=1-((((s*c+n)*c+i)*c+r)*c+e)*c*Math.exp(-t*t);return .5*(1+o*l)}scoreContextMatch(t,e){let r=0,i=0;return e.tags.some(n=>n===t.objective.metric)&&(r+=1),i+=1,e.tags.some(n=>n===t.domain)&&(r+=1),i+=1,i>0?r/i:.5}getDefaultParameters(t){let e={timeout:3e4,retryCount:3,concurrency:4};return t.framework&&(e.framework=t.framework),t.language&&(e.language=t.language),e}calculateSuccessRate(t){return t.length===0?0:t.filter(e=>e.result.success).length/t.length}calculateAverageDuration(t){return t.length===0?0:t.reduce((e,r)=>e+r.result.duration,0)/t.length}calculateAverageReward(t){return t.length===0?0:t.reduce((e,r)=>e+r.reward,0)/t.length}identifyImprovementAreas(t,e,r){let i=[];e.success_rate<.8&&i.push("Increase success rate by tuning parameters"),e.avg_duration_ms>1e4&&i.push("Optimize for faster execution"),e.avg_reward<.5&&i.push("Improve reward through better strategy selection");let n=t.parameters;return n.retryCount<2&&i.push("Consider increasing retry count for resilience"),n.concurrency>8&&i.push("High concurrency may cause resource contention"),i}generateParameterCombinations(t){let e=Object.keys(t);if(e.length===0)return[{}];let r=[];function i(n,s){if(n===e.length){r.push({...s});return}let a=e[n];if(!Ui(a)){i(n+1,s);return}for(let o of t[a])s[a]=o,i(n+1,s)}return i(0,{}),r}async updateAggregatedMetrics(t,e){let r=`learning:metrics:aggregated:${t}`,n=(await this.memory.get(r))?.metrics||{};for(let[s,a]of Object.entries(e))Ui(s)&&(n[s]||(n[s]={sum:0,count:0}),n[s].sum+=a,n[s].count+=1);await this.memory.set(r,{metrics:n,updatedAt:new Date},{namespace:"learning-optimization",persist:!0})}async storeOptimizationResult(t){await this.memory.set(`learning:strategy:optimized:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:strategy:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async storeABTestResult(t,e,r){let i=v();await this.memory.set(`learning:abtest:${i}`,{testId:i,strategyA:t.name,strategyB:e.name,result:r,timestamp:new Date},{namespace:"learning-optimization",persist:!0})}async storeStrategyEvaluation(t){let e=v();await this.memory.set(`learning:evaluation:${e}`,{...t,evaluatedAt:new Date},{namespace:"learning-optimization",ttl:86400*7})}};A();var Bv={metricsRetentionDays:90,anomalyThreshold:2.5,trendWindowSize:7,alertThresholds:{error_rate:.05,latency_p99:5e3,memory_usage:.9,cpu_usage:.8}},jt=class{constructor(t,e={}){this.memory=t;this.config={...Bv,...e}}memory;config;async recordMetric(t,e,r,i,n=[]){try{let s={id:v(),name:t,value:e,unit:r,domain:i,tags:n,timestamp:new Date};return await this.memory.set(`production:metric:${s.id}`,s,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400}),await this.indexMetric(s),await this.checkForAnomalies(s),f(s.id)}catch(s){return p(y(s))}}async recordMetricsBatch(t){try{let e=[];for(let r of t){let i=await this.recordMetric(r.name,r.value,r.unit,r.domain,r.tags);i.success&&e.push(i.value)}return f(e)}catch(e){return p(y(e))}}async getMetricsHistory(t,e,r){try{let i=r?`production:metric:index:${t}:${r}:*`:`production:metric:index:${t}:*`,n=await this.memory.search(i,1e3),s=[];for(let a of n){let o=await this.memory.get(a);if(o){let c=await this.memory.get(`production:metric:${o}`);c&&e.contains(c.timestamp)&&s.push(c)}}return s.sort((a,o)=>a.timestamp.getTime()-o.timestamp.getTime()),f(s)}catch(i){return p(y(i))}}async recordIncident(t,e,r,i,n){try{let s={id:v(),severity:t,title:e,description:r,domain:i,metrics:n,startedAt:new Date};return await this.memory.set(`production:incident:${s.id}`,s,{namespace:"learning-optimization",persist:!0}),await this.indexIncident(s),await this.createExperienceFromIncident(s),f(s)}catch(s){return p(y(s))}}async resolveIncident(t,e,r){try{let i=await this.memory.get(`production:incident:${t}`);if(!i)return p(new Error(`Incident ${t} not found`));let n={...i,rootCause:e,resolution:r,resolvedAt:new Date};return await this.memory.set(`production:incident:${t}`,n,{namespace:"learning-optimization",persist:!0}),await this.updateExperienceWithResolution(n),f(n)}catch(i){return p(y(i))}}async getRecentIncidents(t=10,e){try{let r=e?`production:incident:index:domain:${e}:*`:"production:incident:*",i=await this.memory.search(r,t*2),n=[];for(let a of i)if(a.includes(":index:")){let o=await this.memory.get(a);if(o){let c=await this.memory.get(`production:incident:${o}`);c&&n.push(c)}}else{let o=await this.memory.get(a);o&&n.push(o)}n.sort((a,o)=>o.startedAt.getTime()-a.startedAt.getTime());let s=Array.from(new Map(n.map(a=>[a.id,a])).values());return f(s.slice(0,t))}catch(r){return p(y(r))}}async getProductionHealth(){try{let t=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","code-intelligence","security-compliance","learning-optimization"],e={},r={},i="healthy",n=0,s=0;for(let d of t){let m=await this.getDomainHealth(d);e[d]=m,m.status==="degraded"&&n++,m.status==="unhealthy"&&s++;for(let[g,h]of Object.entries(m.metrics))r[`${d}_${g}`]=h}s>0?i="unhealthy":n>t.length/3&&(i="degraded");let a=await this.calculateTrends(),o=await this.getRecentIncidents(5),c=o.success?o.value:[],l=this.generateHealthRecommendations(e,r,c);return f({overall:i,domains:e,metrics:r,trends:a,recentIncidents:c,recommendations:l})}catch(t){return p(y(t))}}async getDomainHealth(t){let e=_e.lastNDays(1),r=await this.getMetricsHistory("*",e,t),i={};if(r.success)for(let o of r.value)i[o.name],i[o.name]=o.value;let n=await this.getRecentIncidents(100,t),s=n.success?n.value.filter(o=>!o.resolvedAt).length:0,a="healthy";return s>2?a="unhealthy":s>0&&(a="degraded"),i.error_rate>this.config.alertThresholds.error_rate?a="unhealthy":i.latency_p99>this.config.alertThresholds.latency_p99&&(a="degraded"),{status:a,metrics:i,activeIncidents:s}}async calculateTrends(){let t=[],e=["error_rate","latency_p99","success_rate"],r=this.config.trendWindowSize;for(let i of e)for(let n=0;n<r;n++){let s=new Date;s.setDate(s.getDate()-n),s.setHours(0,0,0,0);let a=new Date(s);a.setHours(23,59,59,999);let o=_e.create(s,a),c=await this.getMetricsHistory(i,o);if(c.success&&c.value.length>0){let l=c.value.reduce((d,m)=>d+m.value,0)/c.value.length;t.push({timestamp:s,metric:i,value:l})}}return t}generateHealthRecommendations(t,e,r){let i=[];for(let[a,o]of Object.entries(t))o.status==="unhealthy"?i.push(`Domain ${a} is unhealthy. Review active incidents and metrics.`):o.status==="degraded"&&i.push(`Domain ${a} is degraded. Monitor closely.`);for(let[a,o]of Object.entries(e)){let c=a.split("_").slice(-2).join("_"),l=this.config.alertThresholds[c];l&&o>l&&i.push(`Metric ${a} (${o.toFixed(2)}) exceeds threshold (${l})`)}let n=r.filter(a=>!a.resolvedAt);return n.length>3&&i.push(`${n.length} unresolved incidents require attention`),r.reduce((a,o)=>(a[o.severity]=(a[o.severity]||0)+1,a),{}).critical>2&&i.push("Multiple critical incidents detected. Consider system-wide review."),i.length===0&&i.push("All systems operating within normal parameters."),i}async extractInsights(t,e){try{let r=await this.getMetricsHistory("*",t,e),i=r.success?r.value:[],n=await this.getRecentIncidents(50,e),s=n.success?n.value:[],a=i.length,o=s.filter(g=>g.resolvedAt),c=s.length>0?o.length/s.length:1,l=this.calculateRewardFromIncidents(s),d=this.generateInsightRecommendations(i,s),m=this.detectMetricAnomalies(i);return f({experienceCount:a,successRate:c,avgReward:l,patterns:[],anomalies:m,recommendations:d})}catch(r){return p(y(r))}}async recordMilestone(t,e,r){try{let i={name:t,achievedAt:new Date,domain:e};return await this.memory.set(`production:milestone:${v()}`,{...i,metrics:r},{namespace:"learning-optimization",persist:!0}),f(i)}catch(i){return p(y(i))}}async getRecentMilestones(t=10){try{let e=await this.memory.search("production:milestone:*",t),r=[];for(let i of e){let n=await this.memory.get(i);n&&r.push(n)}return r.sort((i,n)=>n.achievedAt.getTime()-i.achievedAt.getTime()),f(r.slice(0,t))}catch(e){return p(y(e))}}async indexMetric(t){await this.memory.set(`production:metric:index:${t.name}:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400})}async indexIncident(t){await this.memory.set(`production:incident:index:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`production:incident:index:severity:${t.severity}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async checkForAnomalies(t){let e=_e.lastNDays(7),r=await this.getMetricsHistory(t.name,e,t.domain);if(!r.success||r.value.length<10)return;let i=r.value.map(o=>o.value),n=i.reduce((o,c)=>o+c,0)/i.length,s=Math.sqrt(i.reduce((o,c)=>o+Math.pow(c-n,2),0)/i.length),a=Math.abs(t.value-n)/(s||1);a>this.config.anomalyThreshold&&await this.memory.set(`production:anomaly:${v()}`,{metricId:t.id,metricName:t.name,value:t.value,mean:n,stdDev:s,deviation:a,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*7})}async createExperienceFromIncident(t){let e={context:{incidentId:t.id,severity:t.severity,domain:t.domain},metrics:t.metrics},r={success:!1,outcome:t.metrics,duration:0},i={id:v(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`incident-${t.severity}`,state:e,result:r,reward:this.calculateIncidentReward(t),timestamp:t.startedAt};await this.memory.set(`learning:experience:${i.id}`,i,{namespace:"learning-optimization",ttl:86400*30})}async updateExperienceWithResolution(t){if(!t.resolvedAt)return;let e={context:{incidentId:t.id,rootCause:t.rootCause,resolution:t.resolution},metrics:t.metrics},r=t.resolvedAt.getTime()-t.startedAt.getTime(),i={success:!0,outcome:{...t.metrics,resolution_time_ms:r},duration:r},n={id:v(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`resolution-${t.severity}`,state:e,result:i,reward:1-this.calculateIncidentReward(t),timestamp:t.resolvedAt};await this.memory.set(`learning:experience:${n.id}`,n,{namespace:"learning-optimization",ttl:86400*30})}calculateIncidentReward(t){return-({critical:.9,high:.7,medium:.4,low:.2}[t.severity]||.5)}calculateRewardFromIncidents(t){if(t.length===0)return .8;let e={critical:.1,high:.3,medium:.6,low:.8},r=0,i=0;for(let n of t){let s=e[n.severity]||.5,a=n.resolvedAt?.2:0;r+=s+a,i++}return i>0?r/i:.8}generateInsightRecommendations(t,e){let r=[],i=new Map;for(let n of t){let s=i.get(n.name)||[];s.push(n.value),i.set(n.name,s)}for(let[n,s]of i){let a=this.calculateTrendDirection(s);a==="increasing"&&n.includes("error")?r.push(`${n} is trending upward. Investigate root causes.`):a==="decreasing"&&n.includes("success")&&r.push(`${n} is declining. Review recent changes.`)}if(e.length>0){let n=new Map;for(let s of e)n.set(s.domain,(n.get(s.domain)||0)+1);for(let[s,a]of n)a>3&&r.push(`Domain ${s} has ${a} incidents. Consider preventive measures.`)}return r}detectMetricAnomalies(t){let e=[],r=new Map;for(let i of t){let n=r.get(i.name)||[];n.push(i),r.set(i.name,n)}for(let[i,n]of r){if(n.length<5)continue;let s=n.map(c=>c.value),a=s.reduce((c,l)=>c+l,0)/s.length,o=Math.sqrt(s.reduce((c,l)=>c+Math.pow(l-a,2),0)/s.length);for(let c of n){let l=Math.abs(c.value-a)/(o||1);l>this.config.anomalyThreshold&&e.push({experienceId:c.id,type:"outlier-reward",description:`${i} value ${c.value.toFixed(2)} is ${l.toFixed(1)} std deviations from mean`,deviation:l})}}return e}calculateTrendDirection(t){if(t.length<3)return"stable";let e=t.slice(0,Math.floor(t.length/2)),r=t.slice(Math.floor(t.length/2)),i=e.reduce((a,o)=>a+o,0)/e.length,s=(r.reduce((a,o)=>a+o,0)/r.length-i)/(i||1);return s>.1?"increasing":s<-.1?"decreasing":"stable"}};async function xm(u,t,e){await u.set(`learning:strategy:current:${t}`,e,{namespace:"learning-optimization",persist:!0})}function Pm(u,t){let e=u.map(r=>r.result.outcome[t]??0).filter(r=>!isNaN(r));return e.length===0?0:e.reduce((r,i)=>r+i,0)/e.length}function km(u){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":be.filter(e=>e!=="learning-optimization"),"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:be.filter(e=>e!=="coordination")}[u]||[]}function Im(u){let t=[],e=new Set;for(let r of u){if(e.has(r.id))continue;let i=[r];e.add(r.id);for(let n of u)e.has(n.id)||r.type===n.type&&r.domain===n.domain&&qv(r.context,n.context)&&(i.push(n),e.add(n.id));i.length>=2&&t.push(i)}return t}function qv(u,t){return u.tags.some(e=>t.tags.includes(e))}function Dm(u,t,e){let r=JSON.stringify({patternCount:u.length,knowledgeCount:t.length,strategyCount:e.length,patternIds:u.map(n=>n.id).sort(),knowledgeIds:t.map(n=>n.id).sort(),strategyIds:e.map(n=>n.id).sort()}),i=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);i=(i<<5)-i+s,i=i&i}return Math.abs(i).toString(16)}M();var Fr=R.create("learning-optimization/consensus");async function Mm(u,t,e,r){let i=V({id:v(),type:"pattern-recommendation",confidence:t,description:`Verify pattern recommendation: ${u.name} (${u.type}) for domain ${u.domain}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Pattern recommendation '${u.name}' verified by consensus`),!0):(Fr.warn(`Pattern recommendation '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Fm(u,t,e,r){let i=V({id:v(),type:"optimization-suggestion",confidence:t,description:`Verify optimization: ${u.metric} from ${u.currentValue} to ${u.targetValue} via ${u.strategy}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Optimization suggestion for '${u.metric}' verified by consensus`),!0):(Fr.warn(`Optimization suggestion for '${u.metric}' NOT verified`),!1)}return!0}async function Lm(u,t,e,r){let i=V({id:v(),type:"cross-domain-insight",confidence:t,description:`Verify cross-domain insight: ${u.description}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:"high"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Cross-domain insight verified by consensus for ${u.targetDomains.length} target domains`),!0):(Fr.warn(`Cross-domain insight NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var Wv={maxConcurrentWorkflows:3,defaultTimeout:12e4,enableAutoOptimization:!0,publishEvents:!0,learningCycleIntervalMs:36e5,enableDreamScheduler:!0,dreamCycleIntervalMs:36e5,enableExperienceTrigger:!0,experienceThreshold:50,enableQualityGateFailureTrigger:!0,autoApplyHighConfidenceInsights:!1,autoApplyConfidenceThreshold:.8,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Re=R.create("learning-optimization"),Ta=class extends Q{constructor(e,r,i,n={}){let s={...Wv,...n};super(e,"learning-optimization",s,{verifyFindingTypes:["pattern-recommendation","optimization-suggestion","cross-domain-insight"]});this.memory=r;this.agentCoordinator=i;this.learningService=new Gt({memory:r}),this.transferService=new Ht(r),this.optimizerService=new Wt(r),this.productionIntel=new jt(r)}memory;agentCoordinator;learningService;transferService;optimizerService;productionIntel;sona=null;dreamScheduler=null;async onInitialize(){try{this.sona=await me({domain:"learning-optimization",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.5}),Re.info("PersistentSONAEngine initialized for pattern learning")}catch(e){Re.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),Re.warn("Continuing without SONA pattern persistence"),this.sona=null}if(this.config.enableDreamScheduler)try{let e=await Sl();await e.initialize(),this.dreamScheduler=Rl({dreamEngine:e,eventBus:this.eventBus,memoryBackend:this.memory},{autoScheduleIntervalMs:this.config.dreamCycleIntervalMs,enableExperienceTrigger:this.config.enableExperienceTrigger,experienceThreshold:this.config.experienceThreshold,enableQualityGateFailureTrigger:this.config.enableQualityGateFailureTrigger,autoApplyHighConfidenceInsights:this.config.autoApplyHighConfidenceInsights,insightConfidenceThreshold:this.config.autoApplyConfidenceThreshold}),await this.dreamScheduler.initialize(),this.dreamScheduler.start(),Re.info("DreamScheduler initialized and started")}catch{Re.warn("Failed to initialize DreamScheduler:")}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){if(await this.saveWorkflowState(),this.dreamScheduler){try{await this.dreamScheduler.dispose(),Re.info("DreamScheduler disposed")}catch(e){Re.error("Error disposing DreamScheduler:",e instanceof Error?e:void 0)}this.dreamScheduler=null}if(this.initialized&&this.sona)try{await this.sona.close()}catch(e){Re.error("Error closing SONA engine:",e instanceof Error?e:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async runLearningCycle(e){let r=v();try{if(this.startWorkflow(r,"learning-cycle"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, using conservative strategy for learning cycle"),this.minCutMixin.shouldPauseOperations())return p(new Error("Learning cycle paused: topology is in critical state"));let i=await this.spawnLearningAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=_e.lastNDays(1),s=await this.getExperiencesForDomain(e,n),a=s.success?s.value:[];this.updateWorkflowProgress(r,20);let o=await this.learningService.mineExperiences(e,n),c=o.success?o.value.patterns.length:0;this.updateWorkflowProgress(r,50);let l=0,d=[];if(a.length>=10){let h={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(e),w=await this.optimizerService.optimizeStrategy(b,h,a);w.success&&(l=1,d.push({metric:h.metric,before:this.calculateMetricValue(a,h.metric),after:w.value.optimizedStrategy.expectedOutcome[h.metric]||0,percentChange:w.value.improvement*100}))}this.updateWorkflowProgress(r,80);let m=0;o.success&&o.value.recommendations.length>0&&(await this.transferService.createKnowledge("heuristic",e,o.value.recommendations,{value:`learning-agent-${r.slice(0,8)}`,domain:"learning-optimization",type:"analyzer"},[e])).success&&(m=1),this.completeWorkflow(r),await this.agentCoordinator.stop(i.value);let g={domain:e,experiencesProcessed:a.length,patternsLearned:c,strategiesOptimized:l,knowledgeGenerated:m,improvements:d};return this.config.publishEvents&&c>0&&await this.publishPatternConsolidated(c,[e]),f(g)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async optimizeAllStrategies(){let e=v();try{if(this.startWorkflow(e,"optimization"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, using conservative optimization strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Optimization paused: topology is in critical state"));let r={},i=0,n=0,s=0,a=be.filter(c=>c!=="learning-optimization");for(let c=0;c<a.length;c++){let l=a[c];this.updateWorkflowProgress(e,Math.round(c/a.length*100));let d=_e.lastNDays(7),m=await this.getExperiencesForDomain(l,d);if(!m.success||m.value.length<10)continue;let g=m.value,h={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(l),w=await this.optimizerService.optimizeStrategy(b,h,g);w.success&&(i++,n+=w.value.improvement,s++,r[l]={strategiesOptimized:1,avgImprovement:w.value.improvement,bestStrategy:w.value.optimizedStrategy},await this.storeStrategy(l,w.value.optimizedStrategy))}this.completeWorkflow(e);let o={domainsOptimized:s,totalStrategies:i,avgImprovement:i>0?n/i:0,byDomain:r};return this.config.publishEvents&&i>0&&await this.publishOptimizationApplied(o),f(o)}catch(r){return this.failWorkflow(e,String(r)),p(y(r))}}async shareCrossDomainLearnings(){let e=v();try{if(this.startWorkflow(e,"transfer"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, limiting cross-domain transfer scope"),this.minCutMixin.shouldPauseOperations())return p(new Error("Cross-domain sharing paused: topology is in critical state"));let r=0,i=[],n=0,s=0,a=0,o=await this.transferService.queryKnowledge({minRelevance:.7,limit:100});if(!o.success)return this.failWorkflow(e,o.error.message),p(o.error);let c=o.value;for(let m of c){let g=this.getRelatedDomains(m.domain);for(let h of g){if(h===m.domain)continue;s++,(await this.transferService.transferKnowledge(m,h)).success&&(a++,r++,i.includes(h)||i.push(h))}this.updateWorkflowProgress(e,Math.round(r/(c.length*2)*100))}let l=await this.learningService.getPatternStats();if(l.success){let m=l.value.topPatterns;if(m.length>=2){let g=this.findSimilarPatterns(m);for(let h of g)h.length>=2&&(await this.learningService.consolidatePatterns(h.map(w=>w.id))).success&&n++}}this.completeWorkflow(e);let d={knowledgeShared:r,domainsUpdated:i,transferSuccessRate:s>0?a/s:1,newPatternsCreated:n};return this.config.publishEvents&&r>0&&await this.publishTransferCompleted(d),f(d)}catch(r){return this.failWorkflow(e,String(r)),p(y(r))}}async getLearningDashboard(){try{let e=await this.learningService.getPatternStats(),r=e.success?e.value:null,i=await this.transferService.queryKnowledge({limit:1e3}),n=i.success?i.value.length:0,s=_e.lastNDays(1),a=0;for(let b of be){let w=await this.getExperiencesForDomain(b,s);w.success&&(a+=w.value.length)}let o=await this.productionIntel.getProductionHealth(),c=o.success?o.value.trends:[],l=await this.productionIntel.getRecentMilestones(5),d=l.success?l.value:[],m=r?r.avgSuccessRate*.6+r.avgConfidence*.4:.5,g=[];if(r){let b=Object.entries(r.byDomain).filter(([w,C])=>C>0).map(([w,C])=>({domain:w,score:C})).sort((w,C)=>C.score-w.score);g.push(...b.slice(0,3).map(w=>w.domain))}let h={overallLearningRate:m,totalPatterns:r?.totalPatterns||0,totalKnowledge:n,experiencesLast24h:a,topPerformingDomains:g,learningTrend:c,recentMilestones:d};return f(h)}catch(e){return p(y(e))}}learnPattern(e,r,i,n,s,a){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.createPattern(e,r,i,n,s,a)}ensureInitialized(){if(!this.initialized)throw new Error("[LearningOptimizationCoordinator] Not initialized. Call initialize() first.")}ensureSONAAvailable(){if(!this.sona)throw new Error("[LearningOptimizationCoordinator] SONA engine is not available. Pattern persistence failed during initialization.")}async adaptPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.adaptPattern(e,r,i)}getSONAStats(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getStats()}getSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getAllPatterns()}getSONAPatternsByType(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByType(e)}getSONAPatternsByDomain(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByDomain(e)}updateSONAPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.updatePattern(e,r,i)}forceSONALearning(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.forceLearn()}isSONAAvailable(){return this.initialized&&this.sona!==null}exportSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.exportPatterns()}importSONAPatterns(e){this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.importPatterns(e)}async verifySONAPerformance(e=100){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.verifyPerformance(e)}async triggerDreamCycle(e){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");let r=await this.dreamScheduler.triggerDream(e);return this.config.publishEvents&&await this.publishDreamCycleCompleted(r.cycle.id,r.cycle.durationMs??0,r.cycle.conceptsProcessed,r.insights.map(i=>({id:i.id,type:i.type,description:i.description,noveltyScore:i.noveltyScore,confidenceScore:i.confidenceScore,actionable:i.actionable,suggestedAction:i.suggestedAction,sourceConcepts:i.sourceConcepts})),r.patternsCreated),r}getDreamStatus(){return this.dreamScheduler?.getStatus()??null}isDreamSchedulerAvailable(){return this.dreamScheduler!==null}getLastDreamResult(){return this.dreamScheduler?.getLastDreamResult()??null}async triggerQuickDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerQuickDream()}async triggerFullDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerFullDream()}async exportModels(e){let r=v();try{this.startWorkflow(r,"export");let i=e||be,n=[],s=[],a=[];for(let m of i){let g=await this.memory.search("learning:pattern:*",500);for(let h of g){let b=await this.memory.get(h);b&&i.includes(b.domain)&&n.push(b)}this.updateWorkflowProgress(r,Math.round(n.length/100*30))}let o=await this.transferService.queryKnowledge({limit:1e3});if(o.success)for(let m of o.value)i.includes(m.domain)&&s.push(m);this.updateWorkflowProgress(r,60);let c=await this.memory.search("learning:strategy:optimized:*",200);for(let m of c){let g=await this.memory.get(m);g&&i.includes(g.domain)&&a.push(g)}this.updateWorkflowProgress(r,90);let l=this.calculateChecksum(n,s,a);return this.completeWorkflow(r),f({version:"1.0.0",exportedAt:new Date,patterns:n,knowledge:s,strategies:a,checksum:l})}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async importModels(e){let r=v();try{if(this.startWorkflow(r,"import"),this.calculateChecksum(e.patterns,e.knowledge,e.strategies)!==e.checksum)return this.failWorkflow(r,"Checksum mismatch"),p(new Error("Import failed: checksum mismatch"));let n=0,s=0,a=0,o=[];for(let l of e.patterns){let d=await this.memory.get(`learning:pattern:${l.id}`);d?d.confidence<l.confidence?(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++,o.push({type:"pattern",id:l.id,reason:"Existing pattern had lower confidence",resolution:"overwrite"})):o.push({type:"pattern",id:l.id,reason:"Existing pattern has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++),this.updateWorkflowProgress(r,Math.round(n/e.patterns.length*30))}for(let l of e.knowledge){let d=await this.memory.get(`learning:knowledge:shared:${l.id}`);d?l.version>d.version?(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++,o.push({type:"knowledge",id:l.id,reason:"Import has newer version",resolution:"overwrite"})):o.push({type:"knowledge",id:l.id,reason:"Existing knowledge is same or newer version",resolution:"skip"}):(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++),this.updateWorkflowProgress(r,30+Math.round(s/e.knowledge.length*30))}for(let l of e.strategies){let d=await this.memory.get(`learning:strategy:optimized:${l.id}`);d?l.confidence>d.confidence?(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),a++,o.push({type:"strategy",id:l.id,reason:"Import has higher confidence",resolution:"overwrite"})):o.push({type:"strategy",id:l.id,reason:"Existing strategy has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),a++),this.updateWorkflowProgress(r,60+Math.round(a/e.strategies.length*40))}return this.completeWorkflow(r),f({patternsImported:n,knowledgeImported:s,strategiesImported:a,conflicts:o,resolved:!0})}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("learning.ExperienceCaptured",this.handleExperienceCaptured.bind(this))}async handleTestRunCompleted(e){let{runId:r,passed:i,failed:n,duration:s}=e.payload,a=i+n>0?i/(i+n):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r},metrics:{passed:i,failed:n,duration:s}},result:{success:a>.8,outcome:{success_rate:a,passed:i,failed:n},duration:s},reward:a})}async handleCoverageGap(e){let{gapId:r,file:i,riskScore:n}=e.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:r,file:i},metrics:{riskScore:n}},result:{success:!0,outcome:{risk_score:n},duration:0},reward:1-n})}async handleQualityGate(e){let{gateId:r,passed:i}=e.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:r},metrics:{passed:i?1:0}},result:{success:i,outcome:{gate_passed:i?1:0},duration:0},reward:i?1:0})}async handleExperienceCaptured(e){let{experience:r}=e.payload;if(!r.success||r.quality<.7)return;let i=r.domain||"learning-optimization";if(await this.learningService.recordExperience({agentId:{value:r.agent||"unknown",domain:i,type:"specialist"},domain:i,action:r.task,state:{context:{experienceId:r.id,trajectoryId:r.trajectoryId,model:r.model},metrics:{durationMs:r.durationMs,stepCount:r.steps.length,quality:r.quality}},result:{success:r.success,outcome:{quality:r.quality,patterns_extracted:r.patterns?.length||0},duration:r.durationMs},reward:r.quality}),r.patterns&&r.patterns.length>0&&r.domain){let n=this.getRelatedDomains(r.domain);for(let s of n)s!==r.domain&&await this.transferService.transferKnowledge({id:`exp-${r.id}`,domain:r.domain,type:"workflow",content:{format:"json",data:{task:r.task,steps:r.steps,quality:r.quality,patterns:r.patterns}},sourceAgentId:{value:r.agent||"experience-capture",domain:r.domain,type:"specialist"},targetDomains:[s],relevanceScore:r.quality,version:1,createdAt:new Date(r.startedAt)},s);Re.info(`[LearningOptimizationCoordinator] Experience ${r.id} transferred to ${n.length} related domains`)}this.dreamScheduler&&this.dreamScheduler.recordExperience({id:r.id,agentType:r.agent||"unknown",domain:i,taskType:r.task,success:r.success,duration:r.durationMs,context:{quality:r.quality,steps:r.steps.length,patterns:r.patterns?.length||0},timestamp:new Date(r.startedAt)})}async publishPatternConsolidated(e,r){let i={patternCount:e,domains:r,improvements:0},n=D(Ge.PatternConsolidated,"learning-optimization",i);await this.eventBus.publish(n)}async publishTransferCompleted(e){let r={sourceProject:"current",targetProject:"current",patternsTransferred:e.knowledgeShared,successRate:e.transferSuccessRate},i=D(Ge.TransferCompleted,"learning-optimization",r);await this.eventBus.publish(i)}async publishOptimizationApplied(e){let r=D(Ge.OptimizationApplied,"learning-optimization",{domainsOptimized:e.domainsOptimized,avgImprovement:e.avgImprovement});await this.eventBus.publish(r)}async publishDreamCycleCompleted(e,r,i,n,s){if(!this.config.publishEvents)return;let a={cycleId:e,durationMs:r,conceptsProcessed:i,insights:n,patternsCreated:s},o=D(Ge.DreamCycleCompleted,"learning-optimization",a);await this.eventBus.publish(o),Re.info(`[LearningOptimizationCoordinator] Published dream cycle completion: ${n.length} insights for ${i} concepts`)}async spawnLearningAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`learning-agent-${e.slice(0,8)}`,domain:"learning-optimization",type:"optimizer",capabilities:["pattern-learning","experience-mining",r],config:{workflowId:e,targetDomain:r}};return this.agentCoordinator.spawn(i)}async loadWorkflowState(){let e=await this.memory.get("learning-optimization:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("learning-optimization:coordinator:workflows",e,{namespace:"learning-optimization",persist:!0})}async getExperiencesForDomain(e,r){let i=await this.memory.search(`learning:experience:index:domain:${e}:*`,500),n=[];for(let s of i){let a=await this.memory.get(s);if(a){let o=await this.memory.get(`learning:experience:${a}`);o&&r.contains(o.timestamp)&&n.push(o)}}return f(n)}async getCurrentStrategy(e){let r=`learning:strategy:current:${e}`,i=await this.memory.get(r);return i||{name:`default-${e}`,parameters:{timeout:3e4,retryCount:3,concurrency:4},expectedOutcome:{success_rate:.8}}}async storeStrategy(e,r){await xm(this.memory,e,r)}calculateMetricValue(e,r){return Pm(e,r)}getRelatedDomains(e){return km(e)}findSimilarPatterns(e){return Im(e)}calculateChecksum(e,r,i){return Dm(e,r,i)}async verifyPatternRecommendation(e,r){return Mm(e,r,this.consensusMixin,this.domainName)}async verifyOptimizationSuggestion(e,r){return Fm(e,r,this.consensusMixin,this.domainName)}async verifyCrossDomainInsight(e,r){return Lm(e,r,this.consensusMixin,this.domainName)}};A();var tl=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;learningService=null;transferService=null;optimizerService=null;productionIntel=null;pluginConfig;get name(){return"learning-optimization"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{isSONAAvailable:()=>this.coordinator?.isSONAAvailable()??!1,runLearningCycle:this.runLearningCycle.bind(this),optimizeAllStrategies:this.optimizeAllStrategies.bind(this),shareCrossDomainLearnings:this.shareCrossDomainLearnings.bind(this),getLearningDashboard:this.getLearningDashboard.bind(this),exportModels:this.exportModels.bind(this),importModels:this.importModels.bind(this),learnPattern:this.learnPattern.bind(this),findMatchingPatterns:this.findMatchingPatterns.bind(this),applyPattern:this.applyPattern.bind(this),updatePatternFeedback:this.updatePatternFeedback.bind(this),getPatternStats:this.getPatternStats.bind(this),queryKnowledge:this.queryKnowledge.bind(this),transferKnowledge:this.transferKnowledge.bind(this),optimizeStrategy:this.optimizeStrategy.bind(this),runABTest:this.runABTest.bind(this),recommendStrategy:this.recommendStrategy.bind(this),evaluateStrategy:this.evaluateStrategy.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[],getLearningService:()=>this.learningService,getTransferService:()=>this.transferService,getOptimizerService:()=>this.optimizerService,getProductionIntelService:()=>this.productionIntel}}getTaskHandlers(){return new Map([["run-learning-cycle",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.domain;return r?this.coordinator.runLearningCycle(r):p(new Error("Invalid run-learning-cycle payload: missing domain"))}],["optimize-strategies",async e=>this.coordinator?this.coordinator.optimizeAllStrategies():p(new Error("Coordinator not initialized"))],["share-learnings",async e=>this.coordinator?this.coordinator.shareCrossDomainLearnings():p(new Error("Coordinator not initialized"))],["learn-pattern",async e=>{if(!this.learningService)return p(new Error("Learning service not initialized"));let r=e.experiences;return!r||r.length===0?p(new Error("Invalid learn-pattern payload: missing experiences")):this.learningService.learnPattern(r)}],["query-knowledge",async e=>{if(!this.transferService)return p(new Error("Transfer service not initialized"));let r=e.query;return r?this.transferService.queryKnowledge(r):p(new Error("Invalid query-knowledge payload: missing query"))}]])}async onInitialize(){this.learningService=new Gt({memory:this.memory},this.pluginConfig.learningService),this.transferService=new Ht(this.memory,this.pluginConfig.transferService),this.optimizerService=new Wt(this.memory,this.pluginConfig.optimizerService),this.productionIntel=new jt(this.memory,this.pluginConfig.productionIntel),this.coordinator=new Ta(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.learningService=null,this.transferService=null,this.optimizerService=null,this.productionIntel=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;default:break}}async runLearningCycle(e){this.ensureInitialized();try{let r=await this.coordinator.runLearningCycle(e);return r.success?this.trackSuccessfulOperation("learning-cycle"):this.trackFailedOperation("learning-cycle",r.error),r}catch(r){return this.handleError(r)}}async optimizeAllStrategies(){this.ensureInitialized();try{let e=await this.coordinator.optimizeAllStrategies();return e.success?this.trackSuccessfulOperation("optimization"):this.trackFailedOperation("optimization",e.error),e}catch(e){return this.handleError(e)}}async shareCrossDomainLearnings(){this.ensureInitialized();try{return await this.coordinator.shareCrossDomainLearnings()}catch(e){return this.handleError(e)}}async getLearningDashboard(){this.ensureInitialized();try{return await this.coordinator.getLearningDashboard()}catch(e){return this.handleError(e)}}async exportModels(e){this.ensureInitialized();try{return await this.coordinator.exportModels(e)}catch(r){return this.handleError(r)}}async importModels(e){this.ensureInitialized();try{return await this.coordinator.importModels(e)}catch(r){return this.handleError(r)}}async learnPattern(e){this.ensureInitialized();try{return await this.learningService.learnPattern(e)}catch(r){return this.handleError(r)}}async findMatchingPatterns(e,r){this.ensureInitialized();try{return await this.learningService.findMatchingPatterns(e,r)}catch(i){return this.handleError(i)}}async applyPattern(e,r){this.ensureInitialized();try{return await this.learningService.applyPattern(e,r)}catch(i){return this.handleError(i)}}async updatePatternFeedback(e,r){this.ensureInitialized();try{return await this.learningService.updatePatternFeedback(e,r)}catch(i){return this.handleError(i)}}async getPatternStats(e){this.ensureInitialized();try{return await this.learningService.getPatternStats(e)}catch(r){return this.handleError(r)}}async queryKnowledge(e){this.ensureInitialized();try{return await this.transferService.queryKnowledge(e)}catch(r){return this.handleError(r)}}async transferKnowledge(e,r){this.ensureInitialized();try{return await this.transferService.transferKnowledge(e,r)}catch(i){return this.handleError(i)}}async optimizeStrategy(e,r,i){this.ensureInitialized();try{return await this.optimizerService.optimizeStrategy(e,r,i)}catch(n){return this.handleError(n)}}async runABTest(e,r,i){this.ensureInitialized();try{return await this.optimizerService.runABTest(e,r,i)}catch(n){return this.handleError(n)}}async recommendStrategy(e){this.ensureInitialized();try{return await this.optimizerService.recommendStrategy(e)}catch(r){return this.handleError(r)}}async evaluateStrategy(e,r){this.ensureInitialized();try{return await this.optimizerService.evaluateStrategy(e,r)}catch(i){return this.handleError(i)}}async handleTestGenerated(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"test-generation",domain:"test-generation",type:"generator"},domain:"test-generation",action:"test-generated",state:{context:{testId:r.testId,testType:r.testType},metrics:{}},result:{success:!0,outcome:{generated:1},duration:0},reward:.8})}async handleTestRunCompleted(e){let r=e.payload,i=r.passed+r.failed>0?r.passed/(r.passed+r.failed):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r.runId},metrics:{passed:r.passed,failed:r.failed,duration:r.duration}},result:{success:i>.8,outcome:{success_rate:i,passed:r.passed,failed:r.failed},duration:r.duration},reward:i}),await this.productionIntel.recordMetric("test_success_rate",i,"ratio","test-execution",["automated"])}async handleCoverageGap(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:r.gapId,file:r.file},metrics:{riskScore:r.riskScore}},result:{success:!0,outcome:{risk_score:r.riskScore},duration:0},reward:1-r.riskScore})}async handleQualityGate(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:r.gateId},metrics:{passed:r.passed?1:0}},result:{success:r.passed,outcome:{gate_passed:r.passed?1:0},duration:0},reward:r.passed?1:0})}async handleDefectPredicted(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"defect-intelligence",domain:"defect-intelligence",type:"analyzer"},domain:"defect-intelligence",action:"defect-prediction",state:{context:{predictionId:r.predictionId},metrics:{probability:r.probability}},result:{success:!0,outcome:{probability:r.probability},duration:0},reward:.7})}async handleImpactAnalysis(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"code-intelligence",domain:"code-intelligence",type:"analyzer"},domain:"code-intelligence",action:"impact-analysis",state:{context:{analysisId:r.analysisId},metrics:{changedFiles:r.changedFiles.length,impactedFiles:r.impactedFiles.length}},result:{success:!0,outcome:{changed_count:r.changedFiles.length,impacted_count:r.impactedFiles.length},duration:0},reward:.8})}ensureInitialized(){if(!this._initialized)throw new Error("LearningOptimizationPlugin is not initialized");if(!this.coordinator||!this.learningService||!this.transferService||!this.optimizerService||!this.productionIntel)throw new Error("LearningOptimizationPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),p(r)}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function $m(u,t,e,r){return new tl(u,t,e,r)}var rl=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;workflowOrchestrator=null;pluginConfig;get name(){return"coordination"}get version(){return"1.0.0"}get dependencies(){return be.filter(e=>e!=="coordination")}getAPI(){return{listWorkflows:async()=>{if(!this.workflowOrchestrator)throw new Error("Workflow orchestrator not initialized");return this.workflowOrchestrator.listWorkflows()}}}async onInitialize(){this.workflowOrchestrator=Tl(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.workflowConfig),await this.workflowOrchestrator.initialize(),this.updateHealth({status:"healthy",agents:{total:0,active:0,idle:0,failed:0}})}async onDispose(){this.workflowOrchestrator&&(await this.workflowOrchestrator.dispose(),this.workflowOrchestrator=null)}async onEvent(e){e.type.startsWith("coordination.")&&await this.handleCoordinationEvent(e)}subscribeToEvents(){this.eventBus.subscribe("coordination.workflow.execute",async e=>{await this.handleEvent(e)})}async handleCoordinationEvent(e){e.type.split(".")[1]==="workflow"&&await this.handleWorkflowEvent(e)}async handleWorkflowEvent(e){this.workflowOrchestrator}};function Om(u,t,e,r){return new rl(u,t,e,r)}var Te={CoverageAnalyzerService:"coverage-analysis.CoverageAnalyzerService",SecurityScannerService:"security-compliance.SecurityScannerService",isSemgrepAvailable:"security-compliance.isSemgrepAvailable",runSemgrepWithRules:"security-compliance.runSemgrepWithRules",convertSemgrepFindings:"security-compliance.convertSemgrepFindings",createTestGeneratorService:"test-generation.createTestGeneratorService",KnowledgeGraphService:"code-intelligence.KnowledgeGraphService",QualityAnalyzerService:"quality-assessment.QualityAnalyzerService"},il=class{factories=new Map;register(t,e){this.factories.set(t,e)}resolve(t){let e=this.factories.get(t);if(!e)throw new Error(`DomainServiceRegistry: service '${t}' not registered. Ensure the domain module is initialized before coordination.`);return e}has(t){return this.factories.has(t)}clear(){this.factories.clear()}keys(){return Array.from(this.factories.keys())}},Ae=new il;Ae.register(Te.createTestGeneratorService,u=>Tt(u));Ae.register(Te.CoverageAnalyzerService,u=>new mt(u));Ae.register(Te.SecurityScannerService,u=>new $e(u));Ae.register(Te.isSemgrepAvailable,Vi);Ae.register(Te.runSemgrepWithRules,Gs);Ae.register(Te.convertSemgrepFindings,Hs);Ae.register(Te.KnowledgeGraphService,u=>new Rt(u));A();Ae.register(Te.QualityAnalyzerService,u=>new Ye(u));A();M();A();var Ut={SoapOperationTested:"enterprise-integration.SoapOperationTested",MessageFlowTested:"enterprise-integration.MessageFlowTested",BapiTested:"enterprise-integration.BapiTested",IDocValidated:"enterprise-integration.IDocValidated",ODataTested:"enterprise-integration.ODataTested",SodAnalyzed:"enterprise-integration.SodAnalyzed",MiddlewareFlowTested:"enterprise-integration.MiddlewareFlowTested",IntegrationValidationFailed:"enterprise-integration.IntegrationValidationFailed"},Kv={maxConcurrentWorkflows:8,defaultTimeout:12e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Aa=R.create("enterprise-integration"),Ea=class extends Q{constructor(e,r,i,n={}){let s={...Kv,...n};super(e,"enterprise-integration",s,{verifyFindingTypes:["soap-fault","message-ordering-violation","rfc-compatibility-break","idoc-validation-failure","odata-contract-break","sod-conflict"],modelTimeout:12e4});this.memory=r;this.agentCoordinator=i}memory;agentCoordinator;async onInitialize(){this.subscribeToEvents(),Aa.info("Enterprise Integration Coordinator initialized")}async onDispose(){}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async validateWsdl(e){let r=v();try{if(this.startWorkflow(r,"soap"),this.minCutMixin.shouldPauseOperations())return p(new Error("WSDL validation paused: topology is in critical state"));let i=await this.spawnAgent(r,"qe-soap-tester",{task:"validate-wsdl",url:e});if(!i.success)return this.failWorkflow(r,i.error.message),i;let n={url:e,version:"1.1",services:[],schemas:[]};return await this.memory.set(`enterprise-integration:wsdl:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async testSoapOperation(e,r,i){let n=v();try{this.startWorkflow(n,"soap");let s=await this.spawnAgent(n,"qe-soap-tester",{task:"test-operation",wsdl:e,operation:r,input:i});if(!s.success)return this.failWorkflow(n,s.error.message),p(s.error);let a={operation:r,passed:!0,request:JSON.stringify(i),response:"",validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.SoapOperationTested,this.domainName,{operation:r,wsdlUrl:e.url,passed:a.passed,errors:a.validationErrors.length})),this.completeWorkflow(n),f(a)}catch(s){return this.failWorkflow(n,String(s)),p(y(s))}}async testMessageFlow(e,r){let i=v();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-message-flow",brokerConfig:e,testCase:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={testCaseId:r.id,passed:!0,sentAt:new Date,receivedAt:new Date,latency:0,actualOutcome:r.expectedOutcome,errors:[]};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.MessageFlowTested,this.domainName,{protocol:e.protocol,queue:r.queue,passed:s.passed,latency:s.latency})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async testDlqHandling(e,r){let i=v();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-dlq",brokerConfig:e,queue:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={queue:r,messageCount:0,poisonMessages:0,reprocessable:0,errors:[]};return this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async testBapiCall(e,r){let i=v();try{if(this.startWorkflow(i,"rfc"),this.minCutMixin.shouldPauseOperations())return p(new Error("BAPI testing paused: topology is in critical state"));let n=await this.spawnAgent(i,"qe-sap-rfc-tester",{task:"test-bapi",connection:e,bapi:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={bapiName:r.name,passed:!0,returnMessages:[],exportValues:{},tableData:{},duration:0,transactionCommitted:!1};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.BapiTested,this.domainName,{bapiName:r.name,passed:s.passed,returnType:s.returnMessages.length>0?s.returnMessages[0].type:"S"})),await this.memory.set(`enterprise-integration:bapi:${r.name}:${Date.now()}`,{bapiName:r.name,importParams:Object.keys(r.importParams),passed:s.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateIdoc(e,r){let i=v();try{this.startWorkflow(i,"idoc");let n=await this.spawnAgent(i,"qe-sap-idoc-tester",{task:"validate-idoc",definition:e,content:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={idocType:e.type,direction:"inbound",passed:!0,statusCode:3,statusMessage:"IDoc validated successfully",segmentValidation:[],processingTime:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.IDocValidated,this.domainName,{idocType:e.type,direction:s.direction,passed:s.passed,statusCode:s.statusCode})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateODataMetadata(e){let r=v();try{this.startWorkflow(r,"odata");let i=await this.spawnAgent(r,"qe-odata-contract-tester",{task:"validate-metadata",serviceUrl:e});if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);let n={version:"v4",serviceUrl:e,entitySets:[],functionImports:[],actions:[]};return await this.memory.set(`enterprise-integration:odata:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async testODataEntitySet(e,r){let i=v();try{this.startWorkflow(i,"odata");let n=await this.spawnAgent(i,"qe-odata-contract-tester",{task:"test-entity-set",metadata:e,entitySet:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={entitySet:r,operation:"CRUD",passed:!0,statusCode:200,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.ODataTested,this.domainName,{entitySet:r,operation:s.operation,passed:s.passed,version:e.version})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateMessageFlow(e,r){let i=v();try{this.startWorkflow(i,"middleware");let n=await this.spawnAgent(i,"qe-middleware-validator",{task:"validate-flow",flow:e,input:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={flowName:e.name,passed:!0,routingCorrect:!0,transformationCorrect:!0,errorHandlingCorrect:!0,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.MiddlewareFlowTested,this.domainName,{flowName:e.name,passed:s.passed,routingCorrect:s.routingCorrect,transformationCorrect:s.transformationCorrect})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateTransformation(e,r,i){let n=v();try{this.startWorkflow(n,"middleware");let s=await this.spawnAgent(n,"qe-middleware-validator",{task:"validate-transformation",spec:e,input:r,expectedOutput:i});return s.success?(this.completeWorkflow(n),f(!0)):(this.failWorkflow(n,s.error.message),p(s.error))}catch(s){return this.failWorkflow(n,String(s)),p(y(s))}}async analyzeSod(e,r){let i=v();try{this.startWorkflow(i,"sod");let n=await this.spawnAgent(i,"qe-sod-analyzer",{task:"analyze-sod",userId:e,ruleset:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={userId:e,conflicts:[],riskScore:0,compliant:!0,recommendations:[]};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.SodAnalyzed,this.domainName,{userId:e,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore})),await this.memory.set(`enterprise-integration:sod:${e}:${Date.now()}`,{userId:e,ruleset:r.name,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async spawnAgent(e,r,i){let n={name:`${r}-${e.slice(0,8)}`,domain:"enterprise-integration",type:r,capabilities:[r],config:{workflowId:e,...i}},s=await this.agentCoordinator.spawn(n);return s.success&&this.addAgentToWorkflow(e,s.value),s}async verifyCriticalFinding(e,r){let i=V({id:v(),type:e.type,confidence:r,description:e.description,payload:e.payload,detectedBy:"enterprise-integration-coordinator",severity:r>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Aa.info(`Finding verified by consensus: ${e.type}`),!0):(Aa.warn(`Finding NOT verified: ${e.type}`),!1)}return!0}async handleContractVerified(e){let r=e.payload;(r?.contractType==="soap"||r?.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-event:${Date.now()}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r?.targetService?.includes("middleware")||r?.targetService?.includes("esb"))&&Aa.info(`Middleware fault injection detected: ${r.targetService}`)}};var nl=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;pluginConfig;get name(){return"enterprise-integration"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{validateWsdl:this.validateWsdl.bind(this),testSoapOperation:this.testSoapOperation.bind(this),testMessageFlow:this.testMessageFlow.bind(this),testDlqHandling:this.testDlqHandling.bind(this),testBapiCall:this.testBapiCall.bind(this),validateIdoc:this.validateIdoc.bind(this),validateODataMetadata:this.validateODataMetadata.bind(this),testODataEntitySet:this.testODataEntitySet.bind(this),validateMessageFlow:this.validateMessageFlow.bind(this),validateTransformation:this.validateTransformation.bind(this),analyzeSod:this.analyzeSod.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["enterprise-integration:soap-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.wsdl,i=e.operation,n=e.input;return e.url&&!r?this.coordinator.validateWsdl(e.url):!r||!i?p(new Error("Invalid soap-test payload: missing wsdl or operation")):this.coordinator.testSoapOperation(r,i,n)}],["enterprise-integration:message-broker-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.brokerConfig,i=e.testCase,n=e.queue;return r?n&&!i?this.coordinator.testDlqHandling(r,n):i?this.coordinator.testMessageFlow(r,i):p(new Error("Invalid message-broker-test payload: missing testCase")):p(new Error("Invalid message-broker-test payload: missing brokerConfig"))}],["enterprise-integration:sap-rfc-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.connection,i=e.bapi;return!r||!i?p(new Error("Invalid sap-rfc-test payload: missing connection or bapi")):this.coordinator.testBapiCall(r,i)}],["enterprise-integration:sap-idoc-validate",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.definition,i=e.content;return!r||!i?p(new Error("Invalid sap-idoc-validate payload: missing definition or content")):this.coordinator.validateIdoc(r,i)}],["enterprise-integration:odata-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.serviceUrl,i=e.metadata,n=e.entitySet;return r&&!i?this.coordinator.validateODataMetadata(r):!i||!n?p(new Error("Invalid odata-test payload: missing metadata or entitySet")):this.coordinator.testODataEntitySet(i,n)}],["enterprise-integration:esb-flow-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.flow,i=e.input,n=e.spec;if(n){let s=e.transformInput,a=e.expectedOutput;return!s||!a?p(new Error("Invalid esb-flow-test payload: missing transformInput or expectedOutput for transformation")):this.coordinator.validateTransformation(n,s,a)}return!r||!i?p(new Error("Invalid esb-flow-test payload: missing flow or input")):this.coordinator.validateMessageFlow(r,i)}],["enterprise-integration:sod-analyze",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.userId,i=e.ruleset;return!r||!i?p(new Error("Invalid sod-analyze payload: missing userId or ruleset")):this.coordinator.analyzeSod(r,i)}]])}async onInitialize(){this.coordinator=new Ea(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"contract-testing.ContractVerified":await this.handleContractVerified(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;case"chaos-resilience.FaultInjected":await this.handleFaultInjected(e);break;default:break}}async validateWsdl(e){this.ensureInitialized();try{let r=await this.coordinator.validateWsdl(e);return r.success?this.trackSuccessfulOperation("validateWsdl"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testSoapOperation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.testSoapOperation(e,r,i);return n.success?this.trackSuccessfulOperation("testSoapOperation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async testMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.testMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("testMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testDlqHandling(e,r){this.ensureInitialized();try{let i=await this.coordinator.testDlqHandling(e,r);return i.success?this.trackSuccessfulOperation("testDlqHandling"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testBapiCall(e,r){this.ensureInitialized();try{let i=await this.coordinator.testBapiCall(e,r);return i.success?this.trackSuccessfulOperation("testBapiCall"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateIdoc(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateIdoc(e,r);return i.success?this.trackSuccessfulOperation("validateIdoc"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateODataMetadata(e){this.ensureInitialized();try{let r=await this.coordinator.validateODataMetadata(e);return r.success?this.trackSuccessfulOperation("validateODataMetadata"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testODataEntitySet(e,r){this.ensureInitialized();try{let i=await this.coordinator.testODataEntitySet(e,r);return i.success?this.trackSuccessfulOperation("testODataEntitySet"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("validateMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateTransformation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.validateTransformation(e,r,i);return n.success?this.trackSuccessfulOperation("validateTransformation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async analyzeSod(e,r){this.ensureInitialized();try{let i=await this.coordinator.analyzeSod(e,r);return i.success?this.trackSuccessfulOperation("analyzeSod"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async handleContractVerified(e){let r=e.payload;(r.contractType==="soap"||r.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-verified:${r.contractId}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleQualityGate(e){let r=e.payload;r.checks.find(n=>n.name==="enterprise-integration")||await this.memory.set(`enterprise-integration:quality-gate-warning:${r.gateId}`,{warning:"Enterprise integration testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r.targetService?.includes("middleware")||r.targetService?.includes("esb")||r.targetService?.includes("broker")||r.targetService?.includes("mq"))&&await this.memory.set(`enterprise-integration:fault-correlation:${r.faultId||Date.now()}`,{targetService:r.targetService,faultType:r.faultType,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("EnterpriseIntegrationPlugin is not initialized");if(!this.coordinator)throw new Error("EnterpriseIntegrationPlugin coordinator is not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Vm(u,t,e,r){return new nl(u,t,e,r)}var _m={"test-generation":(u,t,e)=>Eo(u,t,e),"test-execution":(u,t)=>Fu(u,t),"coverage-analysis":(u,t)=>Zo(u,t),"quality-assessment":(u,t,e)=>lc(u,t,e),"defect-intelligence":(u,t,e)=>hd(u,t,e),"requirements-validation":(u,t,e)=>bd(u,t,e),"code-intelligence":(u,t,e)=>Tc(u,t,e),"security-compliance":(u,t,e)=>Uc(u,t,e),"contract-testing":(u,t,e)=>om(u,t,e),"visual-accessibility":(u,t,e)=>Sm(u,t,e),"chaos-resilience":(u,t,e)=>Am(u,t,e),"learning-optimization":(u,t,e)=>$m(u,t,e),"enterprise-integration":(u,t,e)=>Vm(u,t,e),coordination:(u,t,e)=>Om(u,t,e)},Yv={maxConcurrentAgents:Lr.MAX_CONCURRENT_AGENTS,memoryBackend:"hybrid",hnswEnabled:!0,lazyLoading:!0,enabledDomains:[...be],dataDir:void 0},sl=class{_eventBus;_coordinator;_plugins;_memory;_config;_startTime;_initialized=!1;_loopTracker;constructor(t={}){this._config={...Yv,...t},this._startTime=new Date,this._memory=new Da,this._eventBus=new on,this._coordinator=new cn(this._config.maxConcurrentAgents),this._plugins=new qr(this._eventBus,this._memory,this._config.lazyLoading),this._loopTracker=new ln}get eventBus(){return this._eventBus}get coordinator(){return this._coordinator}get plugins(){return this._plugins}get memory(){return this._memory}async initialize(){if(this._initialized)return;let t=cl(),e=this._config.dataDir||Qt.join(t,".agentic-qe");if(xa.existsSync(e)||xa.mkdirSync(e,{recursive:!0}),this._config.memoryBackend==="memory"){let i=Qt.join(Pa("os").tmpdir(),`aqe-test-${Date.now()}-${Jv().slice(0,12)}.db`);await ul({dbPath:i})}else this._memory=new ll({sqlite:{path:Qt.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:ol.BUSY_TIMEOUT_MS},enableFallback:!0,defaultNamespace:"qe-kernel"}),this._plugins=new qr(this._eventBus,this._memory,this._config.lazyLoading);for(let i of this._config.enabledDomains){let n=_m[i];n&&this._plugins.registerFactory(i,async(s,a)=>Promise.resolve(n(s,a,this._coordinator)))}await this._memory.initialize();let r=new dn({agentId:"qe-kernel"});this._eventBus.registerMiddleware(r);try{let i=Qt.join(e,"plugins"),n=new dl({cacheDir:i}),a=new ml({cache:n}).resolveLoadOrder();for(let o of a.ordered){let c=o.manifest,l=n.get(c.name,c.version);if(!l)continue;let d=Qt.join(l.path,c.entryPoint);for(let m of c.domains){let g=m;if(_m[g])continue;this._plugins.registerFactory(g,async(b,w)=>{let C=await import(d),S=C.default??C.createPlugin;if(typeof S!="function")throw new Error(`Plugin "${c.name}" entry point must export a default function or "createPlugin" function`);return S(b,w,this._coordinator)})}}}catch{}this._config.lazyLoading||await this._plugins.loadAll();try{let{isAgentMemoryBranchingEnabled:i,isRVFPatternStoreEnabled:n}=await import("./feature-flags-6ALWBTHS.js");if(i()&&n()){let{getSharedRvfAdapter:s}=await import("./shared-rvf-adapter-BMFIVWMJ.js"),{AgentMemoryBranch:a}=await import("./agent-memory-branch-YCVTQEMJ.js"),o=s(e,384);if(o){let c=new a(o,{branchDir:Qt.join(e,"branches")});this._coordinator.setMemoryBranch(c)}}}catch{}try{let{getRvfMigrationStage:i}=await import("./feature-flags-6ALWBTHS.js"),n=i();if(n>=2){let{RvfMigrationCoordinator:s}=await import("./rvf-migration-coordinator-6BY5GI47.js");await s.getInstance({stage:n}).initialize()}}catch{}this._initialized=!0}async dispose(){await this._plugins.disposeAll(),await this._coordinator.dispose(),await this._eventBus.dispose(),await this._memory.dispose(),this._initialized=!1}getDomainAPI(t){return this._plugins.getPlugin(t)?.getAPI()}async getDomainAPIAsync(t){let e=this._plugins.getPlugin(t);if(!e&&this._config.lazyLoading&&this._config.enabledDomains.includes(t))try{e=await this._plugins.load(t)}catch(r){console.error(`[QEKernel] Failed to lazy load domain ${t}:`,r);return}return e?.getAPI()}async ensureDomainLoaded(t){if(this._plugins.isLoaded(t))return!0;if(!this._config.enabledDomains.includes(t))return console.warn(`[QEKernel] Domain ${t} is not enabled`),!1;try{return await this._plugins.load(t),!0}catch(e){return console.error(`[QEKernel] Failed to load domain ${t}:`,e),!1}}isDomainLoaded(t){return this._plugins.isLoaded(t)}getLoadedDomains(){return this._plugins.getLoaded()}getPendingDomains(){let t=new Set(this._plugins.getLoaded());return this._config.enabledDomains.filter(e=>!t.has(e))}getHealth(){let t=this._coordinator.listAgents(),e={};for(let c of this._plugins.getLoaded()){let l=this._plugins.getPlugin(c);l&&(e[c]=l.getHealth())}for(let c of be)if(!e[c]){let l=this._config.enabledDomains.includes(c),d=this._config.lazyLoading&&l;e[c]={status:d?"healthy":l?"degraded":"healthy",agents:{total:0,active:0,idle:0,failed:0},errors:d?[]:l?["Domain not yet loaded"]:[],loaded:!1,lazyLoadable:d}}let r=this._coordinator.getActiveCount(),i=0,n=Number.MAX_SAFE_INTEGER;if(this._memory instanceof Da){let c=this._memory.getStats();i=c.entries+c.vectors}else i=0;let a=this._eventBus.getMiddlewares().find(c=>c.name==="semantic-anti-drift"),o=a?a.getStats():void 0;return{status:this.determineOverallStatus(e),uptime:Date.now()-this._startTime.getTime(),domains:e,agents:{total:t.length,active:r,maxAllowed:this._config.maxConcurrentAgents},memory:{used:i,available:n},...o?{antiDrift:o}:{}}}determineOverallStatus(t){let e=Object.values(t).map(r=>r.status);return e.some(r=>r==="unhealthy")?"unhealthy":e.some(r=>r==="degraded")?"degraded":"healthy"}getConfig(){return{...this._config}}checkToolCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return this._loopTracker.trackCall(t,e,r);let i=this._loopTracker.trackCall(t,e,r);if(i.action==="warn"){let n={id:`loop-warn-${t}-${Date.now()}`,type:za.LOOP_WARNING,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature}};this._eventBus.publish(n)}else if(i.action==="steer"){let n={id:`loop-detected-${t}-${Date.now()}`,type:za.LOOP_DETECTED,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature,steeringMessage:i.steeringMessage}};this._eventBus.publish(n)}return i}get loopTracker(){return this._loopTracker}};function i6(u){return new sl(u)}export{Tt as a,mt as b,cr as c,dr as d,Ot as e,Sc as f,he as g,_e as h,zt as i,xc as j,qs as k,Tr as l,Ar as m,fa as n,Pr as o,Ir as p,Gt as q,Ht as r,Wt as s,Te as t,Ae as u,sl as v,i6 as w};
3022
+ // Execute action: {{action}}`,variables:r}}extractPatternContext(t){let e=new Set,r,i;for(let n of t){let s=n.state.context;if(s.language&&(r=s.language),s.framework&&(i=s.framework),s.tags&&Array.isArray(s.tags))for(let a of s.tags)e.add(a)}return{language:r,framework:i,tags:Array.from(e)}}calculateConsolidatedConfidence(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.confidence*n}return r}calculateWeightedSuccessRate(t){let e=t.reduce((i,n)=>i+n.usageCount,0),r=0;for(let i of t){let n=e>0?i.usageCount/e:1/t.length;r+=i.successRate*n}return r}detectAnomalies(t){let e=[],r=this.calculateAverageReward(t),i=this.calculateStdDev(t.map(n=>n.reward));for(let n of t){let s=Math.abs(n.reward-r)/(i||1);if(s>this.config.anomalyDeviationThreshold){let a="outlier-reward";n.result.success&&n.reward<r?a="unexpected-success":!n.result.success&&n.reward>r&&(a="unexpected-failure"),e.push({experienceId:n.id,type:a,description:`Reward ${n.reward.toFixed(2)} deviates ${s.toFixed(2)} std from mean ${r.toFixed(2)}`,deviation:s})}}return e}calculateStdDev(t){if(t.length===0)return 0;let e=t.reduce((i,n)=>i+n,0)/t.length,r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}generateRecommendations(t,e,r){let i=[];return e<.5&&i.push("Low success rate detected. Consider reviewing the approach or gathering more training data."),r.length>t.length*.1&&i.push("High anomaly rate detected. Investigate unexpected outcomes for potential improvements."),t.reduce((s,a)=>s+a.result.duration,0)/t.length>6e4&&i.push("Average operation duration is high. Consider optimizing performance."),t.length<10&&i.push("Limited experience data. Collect more data points for better insights."),i.length===0&&i.push("Performance metrics are within acceptable ranges. Continue monitoring."),i}actionsSimilar(t,e){let r=s=>s.toLowerCase().replace(/[^a-z]/g,""),i=r(t),n=r(e);return!!(i===n||i.includes(n)||n.includes(i))}calculateCentroid(t){let e={},r={};for(let i of t)for(let[n,s]of Object.entries(i.state.metrics))e[n]=(e[n]||0)+s,r[n]=(r[n]||0)+1;for(let i of Object.keys(e))e[i]/=r[i];return{context:{},metrics:e}}isConstraintViolated(t,e){switch(t.operator){case"lt":return e>=t.value;case"gt":return e<=t.value;case"lte":return e>t.value;case"gte":return e<t.value;case"eq":return e!==t.value;default:return!1}}};A();var Vv={maxKnowledgeItems:1e3,relevanceThreshold:.5,transferDecayFactor:.1,crossDomainBoost:.2},Ht=class{constructor(t,e={}){this.memory=t;this.config={...Vv,...e}}memory;config;async shareKnowledge(t,e){try{await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0});for(let r of e)await this.memory.set(`learning:knowledge:access:${r.value}:${t.id}`,{knowledgeId:t.id,agentId:r.value,sharedAt:new Date,accessed:!1},{namespace:"learning-optimization",ttl:86400*7});return await this.recordSharingEvent(t,e),f(void 0)}catch(r){return p(y(r))}}async queryKnowledge(t){try{let e=[],r;t.domain?r=await this.memory.search(`learning:knowledge:*:${t.domain}:*`,t.limit||100):r=await this.memory.search("learning:knowledge:shared:*",t.limit||100);for(let i of r){let n=await this.memory.get(i);n&&this.matchesQuery(n,t)&&e.push(n)}if(e.sort((i,n)=>n.relevanceScore-i.relevanceScore),t.embedding&&t.embedding.length>0){let i=await this.memory.vectorSearch(t.embedding,t.limit||10);for(let n of i){let s=await this.memory.get(n.key);s&&!e.some(a=>a.id===s.id)&&this.matchesQuery(s,t)&&e.push(s)}}return f(e.slice(0,t.limit||100))}catch(e){return p(y(e))}}async synthesizeKnowledge(t){try{if(t.length<2)return p(new Error("Need at least 2 knowledge items to synthesize"));let e=[];for(let c of t){let l=await this.getKnowledgeById(c);l&&e.push(l)}if(e.length<2)return p(new Error("Not enough valid knowledge items found"));let r=this.determineSynthesizedType(e),i=this.determineSynthesizedDomain(e),n=this.mergeKnowledgeContent(e),s=e.reduce((c,l)=>c+l.relevanceScore,0)/e.length,a=Math.min(1,s+this.config.crossDomainBoost),o={id:v(),type:r,domain:i,content:n,sourceAgentId:e[0].sourceAgentId,targetDomains:this.mergeTargetDomains(e),relevanceScore:a,version:1,createdAt:new Date};return await this.storeKnowledge(o),await this.recordSynthesisEvent(o,t),f(o)}catch(e){return p(y(e))}}async transferKnowledge(t,e){try{if(t.domain===e)return p(new Error("Cannot transfer knowledge to the same domain"));let r=this.calculateTransferredRelevance(t,e);if(r<this.config.relevanceThreshold)return p(new Error(`Transferred relevance ${r} below threshold ${this.config.relevanceThreshold}`));let i=await this.adaptContentForDomain(t.content,t.domain,e),n={id:v(),type:t.type,domain:e,content:i,sourceAgentId:t.sourceAgentId,targetDomains:[e],relevanceScore:r,version:t.version+1,createdAt:new Date};return await this.storeKnowledge(n),await this.recordTransferEvent(t,n),f(n)}catch(r){return p(y(r))}}async validateRelevance(t,e){try{let r=t.relevanceScore;if(e.language&&t.content.metadata?.language===e.language&&(r+=.1),e.framework&&t.content.metadata?.framework===e.framework&&(r+=.1),e.tags.length>0&&t.content.metadata?.tags){let a=t.content.metadata.tags,o=e.tags.filter(c=>a.includes(c));r+=o.length/e.tags.length*.2}let n=(Date.now()-t.createdAt.getTime())/(1e3*60*60*24),s=Math.exp(-this.config.transferDecayFactor*n/30);return r*=s,t.expiresAt&&new Date>t.expiresAt&&(r*=.5),f(Math.min(1,Math.max(0,r)))}catch(r){return p(y(r))}}async createKnowledge(t,e,r,i,n=[],s){try{let a={id:v(),type:t,domain:e,content:{format:this.inferContentFormat(r),data:r,metadata:s},sourceAgentId:i,targetDomains:n,relevanceScore:1,version:1,createdAt:new Date};return await this.storeKnowledge(a),t==="embedding"&&Array.isArray(r)&&await this.memory.storeVector(`learning:knowledge:vector:${a.id}`,r,{knowledgeId:a.id}),f(a)}catch(a){return p(y(a))}}async getKnowledgeById(t){return await this.memory.get(`learning:knowledge:shared:${t}`)||null}async bulkTransfer(t,e,r){try{let i=await this.memory.search(`learning:knowledge:project:${t}:*`,500),n=[];for(let s of i){let a=await this.memory.get(s);if(!a||r?.types&&!r.types.includes(a.type)||r?.minRelevance&&a.relevanceScore<r.minRelevance)continue;let o=await this.adaptContentForProject(a.content,t,e),c={...a,id:v(),content:o,relevanceScore:a.relevanceScore*(1-this.config.transferDecayFactor),version:a.version+1,createdAt:new Date};await this.memory.set(`learning:knowledge:project:${e}:${c.id}`,c,{namespace:"learning-optimization",persist:!0}),n.push({knowledgeId:c.id,sourceDomain:a.domain,targetDomain:a.domain,originalRelevance:a.relevanceScore,transferredRelevance:c.relevanceScore,adaptations:["project-context-adapted"]})}return f(n)}catch(i){return p(y(i))}}async storeKnowledge(t){await this.memory.set(`learning:knowledge:shared:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:knowledge:type:${t.type}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}matchesQuery(t,e){if(e.type&&t.type!==e.type||e.domain&&t.domain!==e.domain||e.minRelevance!==void 0&&t.relevanceScore<e.minRelevance)return!1;if(e.tags&&e.tags.length>0){let r=t.content.metadata?.tags||[];if(!e.tags.some(n=>r.includes(n)))return!1}return!0}determineSynthesizedType(t){let e=new Map;for(let n of t)e.set(n.type,(e.get(n.type)||0)+1);let r=t[0].type,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}determineSynthesizedDomain(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r=t[0].domain,i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}mergeKnowledgeContent(t){let e={},r=[];for(let i of t)if(r.push(i.content.data),i.content.metadata)for(let[n,s]of Object.entries(i.content.metadata))if(Array.isArray(s)){let a=e[n]||[];e[n]=[...new Set([...a,...s])]}else e[n]=s;return{format:"json",data:{synthesized:!0,sources:r},metadata:{...e,synthesizedFrom:t.map(i=>i.id),synthesizedAt:new Date().toISOString()}}}mergeTargetDomains(t){let e=new Set;for(let r of t){e.add(r.domain);for(let i of r.targetDomains)e.add(i)}return Array.from(e)}calculateTransferredRelevance(t,e){let r=t.relevanceScore;r*=1-this.config.transferDecayFactor;let i=this.getDomainCompatibility(t.domain,e);return r*=i,t.targetDomains.includes(e)&&(r+=this.config.crossDomainBoost),Math.min(1,Math.max(0,r))}getDomainCompatibility(t,e){let r={"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence"],"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:be.filter(i=>i!=="coordination")};return t===e?1:r[t]?.includes(e)?.8:.5}async adaptContentForDomain(t,e,r){return{...t,metadata:{...t.metadata||{},adaptedFrom:e,adaptedTo:r,adaptedAt:new Date().toISOString()}}}async adaptContentForProject(t,e,r){return{...t,metadata:{...t.metadata||{},sourceProject:e,targetProject:r,transferredAt:new Date().toISOString()}}}inferContentFormat(t){return typeof t=="string"?"text":Array.isArray(t)&&t.every(e=>typeof e=="number")?"embedding":"json"}async recordSharingEvent(t,e){await this.memory.set(`learning:knowledge:events:share:${t.id}:${Date.now()}`,{type:"share",knowledgeId:t.id,targetAgents:e.map(r=>r.value),timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordSynthesisEvent(t,e){await this.memory.set(`learning:knowledge:events:synthesis:${t.id}`,{type:"synthesis",synthesizedId:t.id,sourceIds:e,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}async recordTransferEvent(t,e){await this.memory.set(`learning:knowledge:events:transfer:${e.id}`,{type:"transfer",originalId:t.id,transferredId:e.id,originalDomain:t.domain,targetDomain:e.domain,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*30})}};A();se();var _v={defaultConfidenceLevel:.95,minSamplesForOptimization:20,maxOptimizationIterations:100,improvementThreshold:.05,explorationRate:.1},zv=["__proto__","constructor","prototype"];function Ui(u){return!zv.includes(u)}var Wt=class{constructor(t,e={}){this.memory=t;this.config={..._v,...e}}memory;config;async optimizeStrategy(t,e,r){try{if(r.length<this.config.minSamplesForOptimization)return p(new Error(`Need at least ${this.config.minSamplesForOptimization} experiences for optimization`));let i=this.evaluateStrategyPerformance(t,r,e),n=await this.optimizeParameters(t.parameters,r,e),s={name:`${t.name}-optimized`,parameters:n,expectedOutcome:this.predictOutcome(n,r)},a=await this.validateOptimization(t,s,r.slice(-10)),o=this.evaluateStrategyPerformance(s,r,e),c=this.calculateImprovement(i,o,e),l=this.calculateOptimizationConfidence(r.length,c,a),d=this.inferDomainFromExperiences(r),m={id:v(),domain:d,objective:e,currentStrategy:t,optimizedStrategy:s,improvement:c,confidence:l,validationResults:a};return await this.storeOptimizationResult(m),f(m)}catch(i){return p(y(i))}}async runABTest(t,e,r){try{let i=await this.collectStrategyMetrics(t,r.metric,r.minSamples),n=await this.collectStrategyMetrics(e,r.metric,r.minSamples),s=this.calculateMean(i),a=this.calculateMean(n),o=this.calculateStdDev(i),c=this.calculateStdDev(n),l=this.calculatePValue(i,n),d;l<1-r.confidenceLevel?d=s>a?"A":"B":d="inconclusive";let m={winner:d,strategyAMetrics:{[r.metric]:s,stdDev:o,samples:i.length},strategyBMetrics:{[r.metric]:a,stdDev:c,samples:n.length},pValue:l,sampleSizeA:i.length,sampleSizeB:n.length};return await this.storeABTestResult(t,e,m),f(m)}catch(i){return p(y(i))}}async recommendStrategy(t){try{let e=await this.memory.search("learning:strategy:optimized:*",100),r=[];for(let i of e){let n=await this.memory.get(i);if(n&&n.confidence>.6){let s=this.scoreContextMatch(n,t),a=n.improvement*n.confidence;r.push({strategy:n.optimizedStrategy,score:s*.4+a*.6})}}return r.length===0?f({name:"default-strategy",parameters:this.getDefaultParameters(t),expectedOutcome:{success_rate:.7}}):(r.sort((i,n)=>n.score-i.score),f(r[0].strategy))}catch(e){return p(y(e))}}async evaluateStrategy(t,e){try{let r={},i=this.calculateSuccessRate(e),n=this.calculateAverageDuration(e),s=this.calculateAverageReward(e);r.success_rate=i,r.avg_duration_ms=n,r.avg_reward=s;let a=[];i>.8&&a.push("High success rate"),n<5e3&&a.push("Fast execution"),s>.7&&a.push("Consistently good rewards");let o=[];i<.5&&o.push("Low success rate needs investigation"),n>3e4&&o.push("Slow execution time"),s<.3&&o.push("Low reward values");let c=this.identifyImprovementAreas(t,r,e),l={strategy:t,metrics:r,strengths:a,weaknesses:o,improvementAreas:c};return await this.storeStrategyEvaluation(l),f(l)}catch(r){return p(y(r))}}async trackMetrics(t,e){try{let r={strategyId:t,metrics:e,timestamp:new Date,samples:1},i=`learning:metrics:history:${t}:${Date.now()}`;return await this.memory.set(i,r,{namespace:"learning-optimization",ttl:86400*30}),await this.updateAggregatedMetrics(t,e),f(void 0)}catch(r){return p(y(r))}}async getMetricsHistory(t,e=100){try{let r=await this.memory.search(`learning:metrics:history:${t}:*`,e),i=[];for(let n of r){let s=await this.memory.get(n);s&&i.push(s)}return i.sort((n,s)=>n.timestamp.getTime()-s.timestamp.getTime()),f(i)}catch(r){return p(y(r))}}async gridSearchOptimize(t,e,r){try{let i=this.generateParameterCombinations(t),n={},s=e.direction==="maximize"?-1/0:1/0;for(let a of i){let o=this.scoreParameters(a,r,e);(e.direction==="maximize"?o>s:o<s)&&(s=o,n=a)}return f(n)}catch(i){return p(y(i))}}evaluateStrategyPerformance(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.outcome[r.metric]??0;i+=a,n++}return n>0?i/n:0}async optimizeParameters(t,e,r){let i={...t};for(let[n,s]of Object.entries(t))if(Ui(n)&&typeof s=="number"){let a=[-.1,-.05,0,.05,.1],o=0,c=this.scoreParameters(i,e,r);for(let l of a){let d={...i,[n]:s*(1+l)},m=this.scoreParameters(d,e,r);(r.direction==="maximize"?m>c:m<c)&&(c=m,o=l)}i[n]=s*(1+o)}return i}scoreParameters(t,e,r){let i=0,n=0;for(let s of e){let a=s.result.success?1:.5,o=this.calculateParamSimilarity(t,s.state.context),c=s.result.outcome[r.metric]??0;i+=o*c*a,n+=a}return n>0?i/n:0}calculateParamSimilarity(t,e){let r=0,i=0;for(let[n,s]of Object.entries(t))if(e[n]!==void 0)if(i++,typeof s=="number"&&typeof e[n]=="number"){let a=Math.abs(s-e[n]),o=Math.max(Math.abs(s),Math.abs(e[n]),1);r+=1-a/o}else s===e[n]&&r++;return i>0?r/i:.5}predictOutcome(t,e){let r={},i={},n={};for(let s of e)if(s.result.success)for(let[a,o]of Object.entries(s.result.outcome))Ui(a)&&typeof o=="number"&&(i[a]=(i[a]||0)+o,n[a]=(n[a]||0)+1);for(let[s,a]of Object.entries(i))Ui(s)&&(r[s]=a/n[s]);return r}async validateOptimization(t,e,r){let i=[];for(let n of r){let s=e.expectedOutcome,a=Object.entries(s).every(([o,c])=>{let l=n.result.outcome[o]??0;return Math.abs(l-c)/Math.max(c,1)<.2});i.push({testId:n.id,passed:a,metrics:n.state.metrics})}return i}calculateImprovement(t,e,r){if(t===0)return e>0?1:0;let i=e-t,n=r.direction==="maximize"?i/t:-i/t;return Math.max(-1,Math.min(1,n))}calculateOptimizationConfidence(t,e,r){let i=Math.min(1,t/(this.config.minSamplesForOptimization*2)),n=r.filter(a=>a.passed).length/Math.max(r.length,1),s=Math.abs(e)>this.config.improvementThreshold?1:.5;return i*.3+n*.5+s*.2}inferDomainFromExperiences(t){let e=new Map;for(let n of t)e.set(n.domain,(e.get(n.domain)||0)+1);let r="learning-optimization",i=0;for(let[n,s]of e)s>i&&(i=s,r=n);return r}async collectStrategyMetrics(t,e,r){let i=await this.memory.search("learning:metrics:history:*:*",r*2),n=[];for(let s of i){let a=await this.memory.get(s);a&&a.metrics[e]!==void 0&&n.push(a.metrics[e])}for(;n.length<r;){let s=t.expectedOutcome[e]||.5,a=(L()-.5)*.2;n.push(s+a)}return n}calculateMean(t){return t.length===0?0:t.reduce((e,r)=>e+r,0)/t.length}calculateStdDev(t){if(t.length===0)return 0;let e=this.calculateMean(t),r=t.map(i=>Math.pow(i-e,2));return Math.sqrt(r.reduce((i,n)=>i+n,0)/t.length)}calculatePValue(t,e){let r=this.calculateMean(t),i=this.calculateMean(e),n=Math.pow(this.calculateStdDev(t),2),s=Math.pow(this.calculateStdDev(e),2),a=t.length,o=e.length,c=Math.sqrt(n/a+s/o);if(c===0)return .5;let l=Math.abs(r-i)/c,d=2*(1-this.normalCDF(l));return Math.max(0,Math.min(1,d))}normalCDF(t){let e=.254829592,r=-.284496736,i=1.421413741,n=-1.453152027,s=1.061405429,a=.3275911,o=t<0?-1:1;t=Math.abs(t)/Math.sqrt(2);let c=1/(1+a*t),l=1-((((s*c+n)*c+i)*c+r)*c+e)*c*Math.exp(-t*t);return .5*(1+o*l)}scoreContextMatch(t,e){let r=0,i=0;return e.tags.some(n=>n===t.objective.metric)&&(r+=1),i+=1,e.tags.some(n=>n===t.domain)&&(r+=1),i+=1,i>0?r/i:.5}getDefaultParameters(t){let e={timeout:3e4,retryCount:3,concurrency:4};return t.framework&&(e.framework=t.framework),t.language&&(e.language=t.language),e}calculateSuccessRate(t){return t.length===0?0:t.filter(e=>e.result.success).length/t.length}calculateAverageDuration(t){return t.length===0?0:t.reduce((e,r)=>e+r.result.duration,0)/t.length}calculateAverageReward(t){return t.length===0?0:t.reduce((e,r)=>e+r.reward,0)/t.length}identifyImprovementAreas(t,e,r){let i=[];e.success_rate<.8&&i.push("Increase success rate by tuning parameters"),e.avg_duration_ms>1e4&&i.push("Optimize for faster execution"),e.avg_reward<.5&&i.push("Improve reward through better strategy selection");let n=t.parameters;return n.retryCount<2&&i.push("Consider increasing retry count for resilience"),n.concurrency>8&&i.push("High concurrency may cause resource contention"),i}generateParameterCombinations(t){let e=Object.keys(t);if(e.length===0)return[{}];let r=[];function i(n,s){if(n===e.length){r.push({...s});return}let a=e[n];if(!Ui(a)){i(n+1,s);return}for(let o of t[a])s[a]=o,i(n+1,s)}return i(0,{}),r}async updateAggregatedMetrics(t,e){let r=`learning:metrics:aggregated:${t}`,n=(await this.memory.get(r))?.metrics||{};for(let[s,a]of Object.entries(e))Ui(s)&&(n[s]||(n[s]={sum:0,count:0}),n[s].sum+=a,n[s].count+=1);await this.memory.set(r,{metrics:n,updatedAt:new Date},{namespace:"learning-optimization",persist:!0})}async storeOptimizationResult(t){await this.memory.set(`learning:strategy:optimized:${t.id}`,t,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`learning:strategy:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async storeABTestResult(t,e,r){let i=v();await this.memory.set(`learning:abtest:${i}`,{testId:i,strategyA:t.name,strategyB:e.name,result:r,timestamp:new Date},{namespace:"learning-optimization",persist:!0})}async storeStrategyEvaluation(t){let e=v();await this.memory.set(`learning:evaluation:${e}`,{...t,evaluatedAt:new Date},{namespace:"learning-optimization",ttl:86400*7})}};A();var Bv={metricsRetentionDays:90,anomalyThreshold:2.5,trendWindowSize:7,alertThresholds:{error_rate:.05,latency_p99:5e3,memory_usage:.9,cpu_usage:.8}},jt=class{constructor(t,e={}){this.memory=t;this.config={...Bv,...e}}memory;config;async recordMetric(t,e,r,i,n=[]){try{let s={id:v(),name:t,value:e,unit:r,domain:i,tags:n,timestamp:new Date};return await this.memory.set(`production:metric:${s.id}`,s,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400}),await this.indexMetric(s),await this.checkForAnomalies(s),f(s.id)}catch(s){return p(y(s))}}async recordMetricsBatch(t){try{let e=[];for(let r of t){let i=await this.recordMetric(r.name,r.value,r.unit,r.domain,r.tags);i.success&&e.push(i.value)}return f(e)}catch(e){return p(y(e))}}async getMetricsHistory(t,e,r){try{let i=r?`production:metric:index:${t}:${r}:*`:`production:metric:index:${t}:*`,n=await this.memory.search(i,1e3),s=[];for(let a of n){let o=await this.memory.get(a);if(o){let c=await this.memory.get(`production:metric:${o}`);c&&e.contains(c.timestamp)&&s.push(c)}}return s.sort((a,o)=>a.timestamp.getTime()-o.timestamp.getTime()),f(s)}catch(i){return p(y(i))}}async recordIncident(t,e,r,i,n){try{let s={id:v(),severity:t,title:e,description:r,domain:i,metrics:n,startedAt:new Date};return await this.memory.set(`production:incident:${s.id}`,s,{namespace:"learning-optimization",persist:!0}),await this.indexIncident(s),await this.createExperienceFromIncident(s),f(s)}catch(s){return p(y(s))}}async resolveIncident(t,e,r){try{let i=await this.memory.get(`production:incident:${t}`);if(!i)return p(new Error(`Incident ${t} not found`));let n={...i,rootCause:e,resolution:r,resolvedAt:new Date};return await this.memory.set(`production:incident:${t}`,n,{namespace:"learning-optimization",persist:!0}),await this.updateExperienceWithResolution(n),f(n)}catch(i){return p(y(i))}}async getRecentIncidents(t=10,e){try{let r=e?`production:incident:index:domain:${e}:*`:"production:incident:*",i=await this.memory.search(r,t*2),n=[];for(let a of i)if(a.includes(":index:")){let o=await this.memory.get(a);if(o){let c=await this.memory.get(`production:incident:${o}`);c&&n.push(c)}}else{let o=await this.memory.get(a);o&&n.push(o)}n.sort((a,o)=>o.startedAt.getTime()-a.startedAt.getTime());let s=Array.from(new Map(n.map(a=>[a.id,a])).values());return f(s.slice(0,t))}catch(r){return p(y(r))}}async getProductionHealth(){try{let t=["test-generation","test-execution","coverage-analysis","quality-assessment","defect-intelligence","code-intelligence","security-compliance","learning-optimization"],e={},r={},i="healthy",n=0,s=0;for(let d of t){let m=await this.getDomainHealth(d);e[d]=m,m.status==="degraded"&&n++,m.status==="unhealthy"&&s++;for(let[g,h]of Object.entries(m.metrics))r[`${d}_${g}`]=h}s>0?i="unhealthy":n>t.length/3&&(i="degraded");let a=await this.calculateTrends(),o=await this.getRecentIncidents(5),c=o.success?o.value:[],l=this.generateHealthRecommendations(e,r,c);return f({overall:i,domains:e,metrics:r,trends:a,recentIncidents:c,recommendations:l})}catch(t){return p(y(t))}}async getDomainHealth(t){let e=_e.lastNDays(1),r=await this.getMetricsHistory("*",e,t),i={};if(r.success)for(let o of r.value)i[o.name],i[o.name]=o.value;let n=await this.getRecentIncidents(100,t),s=n.success?n.value.filter(o=>!o.resolvedAt).length:0,a="healthy";return s>2?a="unhealthy":s>0&&(a="degraded"),i.error_rate>this.config.alertThresholds.error_rate?a="unhealthy":i.latency_p99>this.config.alertThresholds.latency_p99&&(a="degraded"),{status:a,metrics:i,activeIncidents:s}}async calculateTrends(){let t=[],e=["error_rate","latency_p99","success_rate"],r=this.config.trendWindowSize;for(let i of e)for(let n=0;n<r;n++){let s=new Date;s.setDate(s.getDate()-n),s.setHours(0,0,0,0);let a=new Date(s);a.setHours(23,59,59,999);let o=_e.create(s,a),c=await this.getMetricsHistory(i,o);if(c.success&&c.value.length>0){let l=c.value.reduce((d,m)=>d+m.value,0)/c.value.length;t.push({timestamp:s,metric:i,value:l})}}return t}generateHealthRecommendations(t,e,r){let i=[];for(let[a,o]of Object.entries(t))o.status==="unhealthy"?i.push(`Domain ${a} is unhealthy. Review active incidents and metrics.`):o.status==="degraded"&&i.push(`Domain ${a} is degraded. Monitor closely.`);for(let[a,o]of Object.entries(e)){let c=a.split("_").slice(-2).join("_"),l=this.config.alertThresholds[c];l&&o>l&&i.push(`Metric ${a} (${o.toFixed(2)}) exceeds threshold (${l})`)}let n=r.filter(a=>!a.resolvedAt);return n.length>3&&i.push(`${n.length} unresolved incidents require attention`),r.reduce((a,o)=>(a[o.severity]=(a[o.severity]||0)+1,a),{}).critical>2&&i.push("Multiple critical incidents detected. Consider system-wide review."),i.length===0&&i.push("All systems operating within normal parameters."),i}async extractInsights(t,e){try{let r=await this.getMetricsHistory("*",t,e),i=r.success?r.value:[],n=await this.getRecentIncidents(50,e),s=n.success?n.value:[],a=i.length,o=s.filter(g=>g.resolvedAt),c=s.length>0?o.length/s.length:1,l=this.calculateRewardFromIncidents(s),d=this.generateInsightRecommendations(i,s),m=this.detectMetricAnomalies(i);return f({experienceCount:a,successRate:c,avgReward:l,patterns:[],anomalies:m,recommendations:d})}catch(r){return p(y(r))}}async recordMilestone(t,e,r){try{let i={name:t,achievedAt:new Date,domain:e};return await this.memory.set(`production:milestone:${v()}`,{...i,metrics:r},{namespace:"learning-optimization",persist:!0}),f(i)}catch(i){return p(y(i))}}async getRecentMilestones(t=10){try{let e=await this.memory.search("production:milestone:*",t),r=[];for(let i of e){let n=await this.memory.get(i);n&&r.push(n)}return r.sort((i,n)=>n.achievedAt.getTime()-i.achievedAt.getTime()),f(r.slice(0,t))}catch(e){return p(y(e))}}async indexMetric(t){await this.memory.set(`production:metric:index:${t.name}:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",ttl:this.config.metricsRetentionDays*86400})}async indexIncident(t){await this.memory.set(`production:incident:index:domain:${t.domain}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0}),await this.memory.set(`production:incident:index:severity:${t.severity}:${t.id}`,t.id,{namespace:"learning-optimization",persist:!0})}async checkForAnomalies(t){let e=_e.lastNDays(7),r=await this.getMetricsHistory(t.name,e,t.domain);if(!r.success||r.value.length<10)return;let i=r.value.map(o=>o.value),n=i.reduce((o,c)=>o+c,0)/i.length,s=Math.sqrt(i.reduce((o,c)=>o+Math.pow(c-n,2),0)/i.length),a=Math.abs(t.value-n)/(s||1);a>this.config.anomalyThreshold&&await this.memory.set(`production:anomaly:${v()}`,{metricId:t.id,metricName:t.name,value:t.value,mean:n,stdDev:s,deviation:a,timestamp:new Date},{namespace:"learning-optimization",ttl:86400*7})}async createExperienceFromIncident(t){let e={context:{incidentId:t.id,severity:t.severity,domain:t.domain},metrics:t.metrics},r={success:!1,outcome:t.metrics,duration:0},i={id:v(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`incident-${t.severity}`,state:e,result:r,reward:this.calculateIncidentReward(t),timestamp:t.startedAt};await this.memory.set(`learning:experience:${i.id}`,i,{namespace:"learning-optimization",ttl:86400*30})}async updateExperienceWithResolution(t){if(!t.resolvedAt)return;let e={context:{incidentId:t.id,rootCause:t.rootCause,resolution:t.resolution},metrics:t.metrics},r=t.resolvedAt.getTime()-t.startedAt.getTime(),i={success:!0,outcome:{...t.metrics,resolution_time_ms:r},duration:r},n={id:v(),agentId:{value:"production-intel",domain:"learning-optimization",type:"analyzer"},domain:t.domain,action:`resolution-${t.severity}`,state:e,result:i,reward:1-this.calculateIncidentReward(t),timestamp:t.resolvedAt};await this.memory.set(`learning:experience:${n.id}`,n,{namespace:"learning-optimization",ttl:86400*30})}calculateIncidentReward(t){return-({critical:.9,high:.7,medium:.4,low:.2}[t.severity]||.5)}calculateRewardFromIncidents(t){if(t.length===0)return .8;let e={critical:.1,high:.3,medium:.6,low:.8},r=0,i=0;for(let n of t){let s=e[n.severity]||.5,a=n.resolvedAt?.2:0;r+=s+a,i++}return i>0?r/i:.8}generateInsightRecommendations(t,e){let r=[],i=new Map;for(let n of t){let s=i.get(n.name)||[];s.push(n.value),i.set(n.name,s)}for(let[n,s]of i){let a=this.calculateTrendDirection(s);a==="increasing"&&n.includes("error")?r.push(`${n} is trending upward. Investigate root causes.`):a==="decreasing"&&n.includes("success")&&r.push(`${n} is declining. Review recent changes.`)}if(e.length>0){let n=new Map;for(let s of e)n.set(s.domain,(n.get(s.domain)||0)+1);for(let[s,a]of n)a>3&&r.push(`Domain ${s} has ${a} incidents. Consider preventive measures.`)}return r}detectMetricAnomalies(t){let e=[],r=new Map;for(let i of t){let n=r.get(i.name)||[];n.push(i),r.set(i.name,n)}for(let[i,n]of r){if(n.length<5)continue;let s=n.map(c=>c.value),a=s.reduce((c,l)=>c+l,0)/s.length,o=Math.sqrt(s.reduce((c,l)=>c+Math.pow(l-a,2),0)/s.length);for(let c of n){let l=Math.abs(c.value-a)/(o||1);l>this.config.anomalyThreshold&&e.push({experienceId:c.id,type:"outlier-reward",description:`${i} value ${c.value.toFixed(2)} is ${l.toFixed(1)} std deviations from mean`,deviation:l})}}return e}calculateTrendDirection(t){if(t.length<3)return"stable";let e=t.slice(0,Math.floor(t.length/2)),r=t.slice(Math.floor(t.length/2)),i=e.reduce((a,o)=>a+o,0)/e.length,s=(r.reduce((a,o)=>a+o,0)/r.length-i)/(i||1);return s>.1?"increasing":s<-.1?"decreasing":"stable"}};async function xm(u,t,e){await u.set(`learning:strategy:current:${t}`,e,{namespace:"learning-optimization",persist:!0})}function Pm(u,t){let e=u.map(r=>r.result.outcome[t]??0).filter(r=>!isNaN(r));return e.length===0?0:e.reduce((r,i)=>r+i,0)/e.length}function km(u){return{"test-generation":["test-execution","coverage-analysis"],"test-execution":["test-generation","coverage-analysis","quality-assessment"],"coverage-analysis":["test-generation","test-execution","quality-assessment"],"quality-assessment":["test-execution","coverage-analysis","defect-intelligence"],"defect-intelligence":["quality-assessment","code-intelligence"],"requirements-validation":["test-generation","quality-assessment"],"code-intelligence":["defect-intelligence","security-compliance"],"security-compliance":["code-intelligence","quality-assessment"],"contract-testing":["test-generation","test-execution"],"visual-accessibility":["quality-assessment"],"chaos-resilience":["test-execution","quality-assessment"],"learning-optimization":be.filter(e=>e!=="learning-optimization"),"enterprise-integration":["contract-testing","security-compliance","quality-assessment"],coordination:be.filter(e=>e!=="coordination")}[u]||[]}function Im(u){let t=[],e=new Set;for(let r of u){if(e.has(r.id))continue;let i=[r];e.add(r.id);for(let n of u)e.has(n.id)||r.type===n.type&&r.domain===n.domain&&qv(r.context,n.context)&&(i.push(n),e.add(n.id));i.length>=2&&t.push(i)}return t}function qv(u,t){return u.tags.some(e=>t.tags.includes(e))}function Dm(u,t,e){let r=JSON.stringify({patternCount:u.length,knowledgeCount:t.length,strategyCount:e.length,patternIds:u.map(n=>n.id).sort(),knowledgeIds:t.map(n=>n.id).sort(),strategyIds:e.map(n=>n.id).sort()}),i=0;for(let n=0;n<r.length;n++){let s=r.charCodeAt(n);i=(i<<5)-i+s,i=i&i}return Math.abs(i).toString(16)}M();var Fr=R.create("learning-optimization/consensus");async function Mm(u,t,e,r){let i=V({id:v(),type:"pattern-recommendation",confidence:t,description:`Verify pattern recommendation: ${u.name} (${u.type}) for domain ${u.domain}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:t>.9?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Pattern recommendation '${u.name}' verified by consensus`),!0):(Fr.warn(`Pattern recommendation '${u.name}' NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}async function Fm(u,t,e,r){let i=V({id:v(),type:"optimization-suggestion",confidence:t,description:`Verify optimization: ${u.metric} from ${u.currentValue} to ${u.targetValue} via ${u.strategy}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:t>.85?"high":"medium"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Optimization suggestion for '${u.metric}' verified by consensus`),!0):(Fr.warn(`Optimization suggestion for '${u.metric}' NOT verified`),!1)}return!0}async function Lm(u,t,e,r){let i=V({id:v(),type:"cross-domain-insight",confidence:t,description:`Verify cross-domain insight: ${u.description}`,payload:u,detectedBy:"learning-optimization-coordinator",severity:"high"});if(e.requiresConsensus(i)){let n=await e.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Fr.info(`Cross-domain insight verified by consensus for ${u.targetDomains.length} target domains`),!0):(Fr.warn(`Cross-domain insight NOT verified: ${n.success?n.value.verdict:n.error.message}`),!1)}return!0}var Wv={maxConcurrentWorkflows:3,defaultTimeout:12e4,enableAutoOptimization:!0,publishEvents:!0,learningCycleIntervalMs:36e5,enableDreamScheduler:!0,dreamCycleIntervalMs:36e5,enableExperienceTrigger:!0,experienceThreshold:50,enableQualityGateFailureTrigger:!0,autoApplyHighConfidenceInsights:!1,autoApplyConfidenceThreshold:.8,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Re=R.create("learning-optimization"),Ta=class extends Q{constructor(e,r,i,n={}){let s={...Wv,...n};super(e,"learning-optimization",s,{verifyFindingTypes:["pattern-recommendation","optimization-suggestion","cross-domain-insight"]});this.memory=r;this.agentCoordinator=i;this.learningService=new Gt({memory:r}),this.transferService=new Ht(r),this.optimizerService=new Wt(r),this.productionIntel=new jt(r)}memory;agentCoordinator;learningService;transferService;optimizerService;productionIntel;sona=null;dreamScheduler=null;async onInitialize(){try{this.sona=await me({domain:"learning-optimization",loadOnInit:!0,autoSaveInterval:6e4,maxPatterns:1e4,minConfidence:.5}),Re.info("PersistentSONAEngine initialized for pattern learning")}catch(e){Re.error("Failed to initialize PersistentSONAEngine:",e instanceof Error?e:void 0),Re.warn("Continuing without SONA pattern persistence"),this.sona=null}if(this.config.enableDreamScheduler)try{let e=await Sl();await e.initialize(),this.dreamScheduler=Rl({dreamEngine:e,eventBus:this.eventBus,memoryBackend:this.memory},{autoScheduleIntervalMs:this.config.dreamCycleIntervalMs,enableExperienceTrigger:this.config.enableExperienceTrigger,experienceThreshold:this.config.experienceThreshold,enableQualityGateFailureTrigger:this.config.enableQualityGateFailureTrigger,autoApplyHighConfidenceInsights:this.config.autoApplyHighConfidenceInsights,insightConfidenceThreshold:this.config.autoApplyConfidenceThreshold}),await this.dreamScheduler.initialize(),this.dreamScheduler.start(),Re.info("DreamScheduler initialized and started")}catch{Re.warn("Failed to initialize DreamScheduler:")}this.subscribeToEvents(),await this.loadWorkflowState()}async onDispose(){if(await this.saveWorkflowState(),this.dreamScheduler){try{await this.dreamScheduler.dispose(),Re.info("DreamScheduler disposed")}catch(e){Re.error("Error disposing DreamScheduler:",e instanceof Error?e:void 0)}this.dreamScheduler=null}if(this.initialized&&this.sona)try{await this.sona.close()}catch(e){Re.error("Error closing SONA engine:",e instanceof Error?e:void 0)}}getActiveWorkflows(){return super.getActiveWorkflows()}async runLearningCycle(e){let r=v();try{if(this.startWorkflow(r,"learning-cycle"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, using conservative strategy for learning cycle"),this.minCutMixin.shouldPauseOperations())return p(new Error("Learning cycle paused: topology is in critical state"));let i=await this.spawnLearningAgent(r,e);if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);this.addAgentToWorkflow(r,i.value);let n=_e.lastNDays(1),s=await this.getExperiencesForDomain(e,n),a=s.success?s.value:[];this.updateWorkflowProgress(r,20);let o=await this.learningService.mineExperiences(e,n),c=o.success?o.value.patterns.length:0;this.updateWorkflowProgress(r,50);let l=0,d=[];if(a.length>=10){let h={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(e),w=await this.optimizerService.optimizeStrategy(b,h,a);w.success&&(l=1,d.push({metric:h.metric,before:this.calculateMetricValue(a,h.metric),after:w.value.optimizedStrategy.expectedOutcome[h.metric]||0,percentChange:w.value.improvement*100}))}this.updateWorkflowProgress(r,80);let m=0;o.success&&o.value.recommendations.length>0&&(await this.transferService.createKnowledge("heuristic",e,o.value.recommendations,{value:`learning-agent-${r.slice(0,8)}`,domain:"learning-optimization",type:"analyzer"},[e])).success&&(m=1),this.completeWorkflow(r),await this.agentCoordinator.stop(i.value);let g={domain:e,experiencesProcessed:a.length,patternsLearned:c,strategiesOptimized:l,knowledgeGenerated:m,improvements:d};return this.config.publishEvents&&c>0&&await this.publishPatternConsolidated(c,[e]),f(g)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async optimizeAllStrategies(){let e=v();try{if(this.startWorkflow(e,"optimization"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, using conservative optimization strategy"),this.minCutMixin.shouldPauseOperations())return p(new Error("Optimization paused: topology is in critical state"));let r={},i=0,n=0,s=0,a=be.filter(c=>c!=="learning-optimization");for(let c=0;c<a.length;c++){let l=a[c];this.updateWorkflowProgress(e,Math.round(c/a.length*100));let d=_e.lastNDays(7),m=await this.getExperiencesForDomain(l,d);if(!m.success||m.value.length<10)continue;let g=m.value,h={metric:"success_rate",direction:"maximize",constraints:[]},b=await this.getCurrentStrategy(l),w=await this.optimizerService.optimizeStrategy(b,h,g);w.success&&(i++,n+=w.value.improvement,s++,r[l]={strategiesOptimized:1,avgImprovement:w.value.improvement,bestStrategy:w.value.optimizedStrategy},await this.storeStrategy(l,w.value.optimizedStrategy))}this.completeWorkflow(e);let o={domainsOptimized:s,totalStrategies:i,avgImprovement:i>0?n/i:0,byDomain:r};return this.config.publishEvents&&i>0&&await this.publishOptimizationApplied(o),f(o)}catch(r){return this.failWorkflow(e,String(r)),p(y(r))}}async shareCrossDomainLearnings(){let e=v();try{if(this.startWorkflow(e,"transfer"),this.config.enableMinCutAwareness&&!this.isTopologyHealthy()&&Re.warn("Topology degraded, limiting cross-domain transfer scope"),this.minCutMixin.shouldPauseOperations())return p(new Error("Cross-domain sharing paused: topology is in critical state"));let r=0,i=[],n=0,s=0,a=0,o=await this.transferService.queryKnowledge({minRelevance:.7,limit:100});if(!o.success)return this.failWorkflow(e,o.error.message),p(o.error);let c=o.value;for(let m of c){let g=this.getRelatedDomains(m.domain);for(let h of g){if(h===m.domain)continue;s++,(await this.transferService.transferKnowledge(m,h)).success&&(a++,r++,i.includes(h)||i.push(h))}this.updateWorkflowProgress(e,Math.round(r/(c.length*2)*100))}let l=await this.learningService.getPatternStats();if(l.success){let m=l.value.topPatterns;if(m.length>=2){let g=this.findSimilarPatterns(m);for(let h of g)h.length>=2&&(await this.learningService.consolidatePatterns(h.map(w=>w.id))).success&&n++}}this.completeWorkflow(e);let d={knowledgeShared:r,domainsUpdated:i,transferSuccessRate:s>0?a/s:1,newPatternsCreated:n};return this.config.publishEvents&&r>0&&await this.publishTransferCompleted(d),f(d)}catch(r){return this.failWorkflow(e,String(r)),p(y(r))}}async getLearningDashboard(){try{let e=await this.learningService.getPatternStats(),r=e.success?e.value:null,i=await this.transferService.queryKnowledge({limit:1e3}),n=i.success?i.value.length:0,s=_e.lastNDays(1),a=0;for(let b of be){let w=await this.getExperiencesForDomain(b,s);w.success&&(a+=w.value.length)}let o=await this.productionIntel.getProductionHealth(),c=o.success?o.value.trends:[],l=await this.productionIntel.getRecentMilestones(5),d=l.success?l.value:[],m=r?r.avgSuccessRate*.6+r.avgConfidence*.4:.5,g=[];if(r){let b=Object.entries(r.byDomain).filter(([w,C])=>C>0).map(([w,C])=>({domain:w,score:C})).sort((w,C)=>C.score-w.score);g.push(...b.slice(0,3).map(w=>w.domain))}let h={overallLearningRate:m,totalPatterns:r?.totalPatterns||0,totalKnowledge:n,experiencesLast24h:a,topPerformingDomains:g,learningTrend:c,recentMilestones:d};return f(h)}catch(e){return p(y(e))}}learnPattern(e,r,i,n,s,a){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.createPattern(e,r,i,n,s,a)}ensureInitialized(){if(!this.initialized)throw new Error("[LearningOptimizationCoordinator] Not initialized. Call initialize() first.")}ensureSONAAvailable(){if(!this.sona)throw new Error("[LearningOptimizationCoordinator] SONA engine is not available. Pattern persistence failed during initialization.")}async adaptPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.adaptPattern(e,r,i)}getSONAStats(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getStats()}getSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getAllPatterns()}getSONAPatternsByType(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByType(e)}getSONAPatternsByDomain(e){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.getPatternsByDomain(e)}updateSONAPattern(e,r,i){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.updatePattern(e,r,i)}forceSONALearning(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.forceLearn()}isSONAAvailable(){return this.initialized&&this.sona!==null}exportSONAPatterns(){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.exportPatterns()}importSONAPatterns(e){this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.importPatterns(e)}async verifySONAPerformance(e=100){return this.ensureInitialized(),this.ensureSONAAvailable(),this.sona.verifyPerformance(e)}async triggerDreamCycle(e){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");let r=await this.dreamScheduler.triggerDream(e);return this.config.publishEvents&&await this.publishDreamCycleCompleted(r.cycle.id,r.cycle.durationMs??0,r.cycle.conceptsProcessed,r.insights.map(i=>({id:i.id,type:i.type,description:i.description,noveltyScore:i.noveltyScore,confidenceScore:i.confidenceScore,actionable:i.actionable,suggestedAction:i.suggestedAction,sourceConcepts:i.sourceConcepts})),r.patternsCreated),r}getDreamStatus(){return this.dreamScheduler?.getStatus()??null}isDreamSchedulerAvailable(){return this.dreamScheduler!==null}getLastDreamResult(){return this.dreamScheduler?.getLastDreamResult()??null}async triggerQuickDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerQuickDream()}async triggerFullDream(){if(!this.dreamScheduler)throw new Error("[LearningOptimizationCoordinator] DreamScheduler not initialized");return this.dreamScheduler.triggerFullDream()}async exportModels(e){let r=v();try{this.startWorkflow(r,"export");let i=e||be,n=[],s=[],a=[];for(let m of i){let g=await this.memory.search("learning:pattern:*",500);for(let h of g){let b=await this.memory.get(h);b&&i.includes(b.domain)&&n.push(b)}this.updateWorkflowProgress(r,Math.round(n.length/100*30))}let o=await this.transferService.queryKnowledge({limit:1e3});if(o.success)for(let m of o.value)i.includes(m.domain)&&s.push(m);this.updateWorkflowProgress(r,60);let c=await this.memory.search("learning:strategy:optimized:*",200);for(let m of c){let g=await this.memory.get(m);g&&i.includes(g.domain)&&a.push(g)}this.updateWorkflowProgress(r,90);let l=this.calculateChecksum(n,s,a);return this.completeWorkflow(r),f({version:"1.0.0",exportedAt:new Date,patterns:n,knowledge:s,strategies:a,checksum:l})}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async importModels(e){let r=v();try{if(this.startWorkflow(r,"import"),this.calculateChecksum(e.patterns,e.knowledge,e.strategies)!==e.checksum)return this.failWorkflow(r,"Checksum mismatch"),p(new Error("Import failed: checksum mismatch"));let n=0,s=0,a=0,o=[];for(let l of e.patterns){let d=await this.memory.get(`learning:pattern:${l.id}`);d?d.confidence<l.confidence?(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++,o.push({type:"pattern",id:l.id,reason:"Existing pattern had lower confidence",resolution:"overwrite"})):o.push({type:"pattern",id:l.id,reason:"Existing pattern has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:pattern:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),n++),this.updateWorkflowProgress(r,Math.round(n/e.patterns.length*30))}for(let l of e.knowledge){let d=await this.memory.get(`learning:knowledge:shared:${l.id}`);d?l.version>d.version?(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++,o.push({type:"knowledge",id:l.id,reason:"Import has newer version",resolution:"overwrite"})):o.push({type:"knowledge",id:l.id,reason:"Existing knowledge is same or newer version",resolution:"skip"}):(await this.memory.set(`learning:knowledge:shared:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),s++),this.updateWorkflowProgress(r,30+Math.round(s/e.knowledge.length*30))}for(let l of e.strategies){let d=await this.memory.get(`learning:strategy:optimized:${l.id}`);d?l.confidence>d.confidence?(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),a++,o.push({type:"strategy",id:l.id,reason:"Import has higher confidence",resolution:"overwrite"})):o.push({type:"strategy",id:l.id,reason:"Existing strategy has higher confidence",resolution:"skip"}):(await this.memory.set(`learning:strategy:optimized:${l.id}`,l,{namespace:"learning-optimization",persist:!0}),a++),this.updateWorkflowProgress(r,60+Math.round(a/e.strategies.length*40))}return this.completeWorkflow(r),f({patternsImported:n,knowledgeImported:s,strategiesImported:a,conflicts:o,resolved:!0})}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}subscribeToEvents(){this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("learning.ExperienceCaptured",this.handleExperienceCaptured.bind(this))}async handleTestRunCompleted(e){let{runId:r,passed:i,failed:n,duration:s}=e.payload,a=i+n>0?i/(i+n):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r},metrics:{passed:i,failed:n,duration:s}},result:{success:a>.8,outcome:{success_rate:a,passed:i,failed:n},duration:s},reward:a})}async handleCoverageGap(e){let{gapId:r,file:i,riskScore:n}=e.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:r,file:i},metrics:{riskScore:n}},result:{success:!0,outcome:{risk_score:n},duration:0},reward:1-n})}async handleQualityGate(e){let{gateId:r,passed:i}=e.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:r},metrics:{passed:i?1:0}},result:{success:i,outcome:{gate_passed:i?1:0},duration:0},reward:i?1:0})}async handleExperienceCaptured(e){let{experience:r}=e.payload;if(!r.success||r.quality<.7)return;let i=r.domain||"learning-optimization";if(await this.learningService.recordExperience({agentId:{value:r.agent||"unknown",domain:i,type:"specialist"},domain:i,action:r.task,state:{context:{experienceId:r.id,trajectoryId:r.trajectoryId,model:r.model},metrics:{durationMs:r.durationMs,stepCount:r.steps.length,quality:r.quality}},result:{success:r.success,outcome:{quality:r.quality,patterns_extracted:r.patterns?.length||0},duration:r.durationMs},reward:r.quality}),r.patterns&&r.patterns.length>0&&r.domain){let n=this.getRelatedDomains(r.domain);for(let s of n)s!==r.domain&&await this.transferService.transferKnowledge({id:`exp-${r.id}`,domain:r.domain,type:"workflow",content:{format:"json",data:{task:r.task,steps:r.steps,quality:r.quality,patterns:r.patterns}},sourceAgentId:{value:r.agent||"experience-capture",domain:r.domain,type:"specialist"},targetDomains:[s],relevanceScore:r.quality,version:1,createdAt:new Date(r.startedAt)},s);Re.info(`[LearningOptimizationCoordinator] Experience ${r.id} transferred to ${n.length} related domains`)}this.dreamScheduler&&this.dreamScheduler.recordExperience({id:r.id,agentType:r.agent||"unknown",domain:i,taskType:r.task,success:r.success,duration:r.durationMs,context:{quality:r.quality,steps:r.steps.length,patterns:r.patterns?.length||0},timestamp:new Date(r.startedAt)})}async publishPatternConsolidated(e,r){let i={patternCount:e,domains:r,improvements:0},n=D(Ge.PatternConsolidated,"learning-optimization",i);await this.eventBus.publish(n)}async publishTransferCompleted(e){let r={sourceProject:"current",targetProject:"current",patternsTransferred:e.knowledgeShared,successRate:e.transferSuccessRate},i=D(Ge.TransferCompleted,"learning-optimization",r);await this.eventBus.publish(i)}async publishOptimizationApplied(e){let r=D(Ge.OptimizationApplied,"learning-optimization",{domainsOptimized:e.domainsOptimized,avgImprovement:e.avgImprovement});await this.eventBus.publish(r)}async publishDreamCycleCompleted(e,r,i,n,s){if(!this.config.publishEvents)return;let a={cycleId:e,durationMs:r,conceptsProcessed:i,insights:n,patternsCreated:s},o=D(Ge.DreamCycleCompleted,"learning-optimization",a);await this.eventBus.publish(o),Re.info(`[LearningOptimizationCoordinator] Published dream cycle completion: ${n.length} insights for ${i} concepts`)}async spawnLearningAgent(e,r){if(!this.agentCoordinator.canSpawn())return p(new Error("Agent limit reached"));let i={name:`learning-agent-${e.slice(0,8)}`,domain:"learning-optimization",type:"optimizer",capabilities:["pattern-learning","experience-mining",r],config:{workflowId:e,targetDomain:r}};return this.agentCoordinator.spawn(i)}async loadWorkflowState(){let e=await this.memory.get("learning-optimization:coordinator:workflows");if(e)for(let r of e)r.status==="running"&&(r.status="failed",r.error="Coordinator restarted",r.completedAt=new Date),this.workflows.set(r.id,r)}async saveWorkflowState(){let e=Array.from(this.workflows.values());await this.memory.set("learning-optimization:coordinator:workflows",e,{namespace:"learning-optimization",persist:!0})}async getExperiencesForDomain(e,r){let i=await this.memory.search(`learning:experience:index:domain:${e}:*`,500),n=[];for(let s of i){let a=await this.memory.get(s);if(a){let o=await this.memory.get(`learning:experience:${a}`);o&&r.contains(o.timestamp)&&n.push(o)}}return f(n)}async getCurrentStrategy(e){let r=`learning:strategy:current:${e}`,i=await this.memory.get(r);return i||{name:`default-${e}`,parameters:{timeout:3e4,retryCount:3,concurrency:4},expectedOutcome:{success_rate:.8}}}async storeStrategy(e,r){await xm(this.memory,e,r)}calculateMetricValue(e,r){return Pm(e,r)}getRelatedDomains(e){return km(e)}findSimilarPatterns(e){return Im(e)}calculateChecksum(e,r,i){return Dm(e,r,i)}async verifyPatternRecommendation(e,r){return Mm(e,r,this.consensusMixin,this.domainName)}async verifyOptimizationSuggestion(e,r){return Fm(e,r,this.consensusMixin,this.domainName)}async verifyCrossDomainInsight(e,r){return Lm(e,r,this.consensusMixin,this.domainName)}};A();var tl=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;learningService=null;transferService=null;optimizerService=null;productionIntel=null;pluginConfig;get name(){return"learning-optimization"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{isSONAAvailable:()=>this.coordinator?.isSONAAvailable()??!1,runLearningCycle:this.runLearningCycle.bind(this),optimizeAllStrategies:this.optimizeAllStrategies.bind(this),shareCrossDomainLearnings:this.shareCrossDomainLearnings.bind(this),getLearningDashboard:this.getLearningDashboard.bind(this),exportModels:this.exportModels.bind(this),importModels:this.importModels.bind(this),learnPattern:this.learnPattern.bind(this),findMatchingPatterns:this.findMatchingPatterns.bind(this),applyPattern:this.applyPattern.bind(this),updatePatternFeedback:this.updatePatternFeedback.bind(this),getPatternStats:this.getPatternStats.bind(this),queryKnowledge:this.queryKnowledge.bind(this),transferKnowledge:this.transferKnowledge.bind(this),optimizeStrategy:this.optimizeStrategy.bind(this),runABTest:this.runABTest.bind(this),recommendStrategy:this.recommendStrategy.bind(this),evaluateStrategy:this.evaluateStrategy.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[],getLearningService:()=>this.learningService,getTransferService:()=>this.transferService,getOptimizerService:()=>this.optimizerService,getProductionIntelService:()=>this.productionIntel}}getTaskHandlers(){return new Map([["run-learning-cycle",async e=>{if(!this.coordinator)return p(new Error("Coordinator not initialized"));let r=e.domain;return r?this.coordinator.runLearningCycle(r):p(new Error("Invalid run-learning-cycle payload: missing domain"))}],["optimize-strategies",async e=>this.coordinator?this.coordinator.optimizeAllStrategies():p(new Error("Coordinator not initialized"))],["share-learnings",async e=>this.coordinator?this.coordinator.shareCrossDomainLearnings():p(new Error("Coordinator not initialized"))],["learn-pattern",async e=>{if(!this.learningService)return p(new Error("Learning service not initialized"));let r=e.experiences;return!r||r.length===0?p(new Error("Invalid learn-pattern payload: missing experiences")):this.learningService.learnPattern(r)}],["query-knowledge",async e=>{if(!this.transferService)return p(new Error("Transfer service not initialized"));let r=e.query;return r?this.transferService.queryKnowledge(r):p(new Error("Invalid query-knowledge payload: missing query"))}]])}async onInitialize(){this.learningService=new Gt({memory:this.memory},this.pluginConfig.learningService),this.transferService=new Ht(this.memory,this.pluginConfig.transferService),this.optimizerService=new Wt(this.memory,this.pluginConfig.optimizerService),this.productionIntel=new jt(this.memory,this.pluginConfig.productionIntel),this.coordinator=new Ta(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null,this.learningService=null,this.transferService=null,this.optimizerService=null,this.productionIntel=null}subscribeToEvents(){this.eventBus.subscribe("test-generation.TestGenerated",this.handleTestGenerated.bind(this)),this.eventBus.subscribe("test-execution.TestRunCompleted",this.handleTestRunCompleted.bind(this)),this.eventBus.subscribe("coverage-analysis.CoverageGapDetected",this.handleCoverageGap.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("defect-intelligence.DefectPredicted",this.handleDefectPredicted.bind(this)),this.eventBus.subscribe("code-intelligence.ImpactAnalysisCompleted",this.handleImpactAnalysis.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"test-generation.TestGenerated":await this.handleTestGenerated(e);break;case"test-execution.TestRunCompleted":await this.handleTestRunCompleted(e);break;case"coverage-analysis.CoverageGapDetected":await this.handleCoverageGap(e);break;default:break}}async runLearningCycle(e){this.ensureInitialized();try{let r=await this.coordinator.runLearningCycle(e);return r.success?this.trackSuccessfulOperation("learning-cycle"):this.trackFailedOperation("learning-cycle",r.error),r}catch(r){return this.handleError(r)}}async optimizeAllStrategies(){this.ensureInitialized();try{let e=await this.coordinator.optimizeAllStrategies();return e.success?this.trackSuccessfulOperation("optimization"):this.trackFailedOperation("optimization",e.error),e}catch(e){return this.handleError(e)}}async shareCrossDomainLearnings(){this.ensureInitialized();try{return await this.coordinator.shareCrossDomainLearnings()}catch(e){return this.handleError(e)}}async getLearningDashboard(){this.ensureInitialized();try{return await this.coordinator.getLearningDashboard()}catch(e){return this.handleError(e)}}async exportModels(e){this.ensureInitialized();try{return await this.coordinator.exportModels(e)}catch(r){return this.handleError(r)}}async importModels(e){this.ensureInitialized();try{return await this.coordinator.importModels(e)}catch(r){return this.handleError(r)}}async learnPattern(e){this.ensureInitialized();try{return await this.learningService.learnPattern(e)}catch(r){return this.handleError(r)}}async findMatchingPatterns(e,r){this.ensureInitialized();try{return await this.learningService.findMatchingPatterns(e,r)}catch(i){return this.handleError(i)}}async applyPattern(e,r){this.ensureInitialized();try{return await this.learningService.applyPattern(e,r)}catch(i){return this.handleError(i)}}async updatePatternFeedback(e,r){this.ensureInitialized();try{return await this.learningService.updatePatternFeedback(e,r)}catch(i){return this.handleError(i)}}async getPatternStats(e){this.ensureInitialized();try{return await this.learningService.getPatternStats(e)}catch(r){return this.handleError(r)}}async queryKnowledge(e){this.ensureInitialized();try{return await this.transferService.queryKnowledge(e)}catch(r){return this.handleError(r)}}async transferKnowledge(e,r){this.ensureInitialized();try{return await this.transferService.transferKnowledge(e,r)}catch(i){return this.handleError(i)}}async optimizeStrategy(e,r,i){this.ensureInitialized();try{return await this.optimizerService.optimizeStrategy(e,r,i)}catch(n){return this.handleError(n)}}async runABTest(e,r,i){this.ensureInitialized();try{return await this.optimizerService.runABTest(e,r,i)}catch(n){return this.handleError(n)}}async recommendStrategy(e){this.ensureInitialized();try{return await this.optimizerService.recommendStrategy(e)}catch(r){return this.handleError(r)}}async evaluateStrategy(e,r){this.ensureInitialized();try{return await this.optimizerService.evaluateStrategy(e,r)}catch(i){return this.handleError(i)}}async handleTestGenerated(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"test-generation",domain:"test-generation",type:"generator"},domain:"test-generation",action:"test-generated",state:{context:{testId:r.testId,testType:r.testType},metrics:{}},result:{success:!0,outcome:{generated:1},duration:0},reward:.8})}async handleTestRunCompleted(e){let r=e.payload,i=r.passed+r.failed>0?r.passed/(r.passed+r.failed):0;await this.learningService.recordExperience({agentId:{value:"test-execution",domain:"test-execution",type:"tester"},domain:"test-execution",action:"test-run",state:{context:{runId:r.runId},metrics:{passed:r.passed,failed:r.failed,duration:r.duration}},result:{success:i>.8,outcome:{success_rate:i,passed:r.passed,failed:r.failed},duration:r.duration},reward:i}),await this.productionIntel.recordMetric("test_success_rate",i,"ratio","test-execution",["automated"])}async handleCoverageGap(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"coverage-analysis",domain:"coverage-analysis",type:"analyzer"},domain:"coverage-analysis",action:"gap-detection",state:{context:{gapId:r.gapId,file:r.file},metrics:{riskScore:r.riskScore}},result:{success:!0,outcome:{risk_score:r.riskScore},duration:0},reward:1-r.riskScore})}async handleQualityGate(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"quality-assessment",domain:"quality-assessment",type:"validator"},domain:"quality-assessment",action:"gate-evaluation",state:{context:{gateId:r.gateId},metrics:{passed:r.passed?1:0}},result:{success:r.passed,outcome:{gate_passed:r.passed?1:0},duration:0},reward:r.passed?1:0})}async handleDefectPredicted(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"defect-intelligence",domain:"defect-intelligence",type:"analyzer"},domain:"defect-intelligence",action:"defect-prediction",state:{context:{predictionId:r.predictionId},metrics:{probability:r.probability}},result:{success:!0,outcome:{probability:r.probability},duration:0},reward:.7})}async handleImpactAnalysis(e){let r=e.payload;await this.learningService.recordExperience({agentId:{value:"code-intelligence",domain:"code-intelligence",type:"analyzer"},domain:"code-intelligence",action:"impact-analysis",state:{context:{analysisId:r.analysisId},metrics:{changedFiles:r.changedFiles.length,impactedFiles:r.impactedFiles.length}},result:{success:!0,outcome:{changed_count:r.changedFiles.length,impacted_count:r.impactedFiles.length},duration:0},reward:.8})}ensureInitialized(){if(!this._initialized)throw new Error("LearningOptimizationPlugin is not initialized");if(!this.coordinator||!this.learningService||!this.transferService||!this.optimizerService||!this.productionIntel)throw new Error("LearningOptimizationPlugin services are not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),p(r)}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e,r){let i=this.getHealth();this.updateHealth({agents:{...i.agents,failed:i.agents.failed+1},errors:[...i.errors.slice(-9),r.message]})}};function $m(u,t,e,r){return new tl(u,t,e,r)}var rl=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;workflowOrchestrator=null;pluginConfig;get name(){return"coordination"}get version(){return"1.0.0"}get dependencies(){return be.filter(e=>e!=="coordination")}getAPI(){return{listWorkflows:async()=>{if(!this.workflowOrchestrator)throw new Error("Workflow orchestrator not initialized");return this.workflowOrchestrator.listWorkflows()}}}async onInitialize(){this.workflowOrchestrator=Tl(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.workflowConfig),await this.workflowOrchestrator.initialize(),this.updateHealth({status:"healthy",agents:{total:0,active:0,idle:0,failed:0}})}async onDispose(){this.workflowOrchestrator&&(await this.workflowOrchestrator.dispose(),this.workflowOrchestrator=null)}async onEvent(e){e.type.startsWith("coordination.")&&await this.handleCoordinationEvent(e)}subscribeToEvents(){this.eventBus.subscribe("coordination.workflow.execute",async e=>{await this.handleEvent(e)})}async handleCoordinationEvent(e){e.type.split(".")[1]==="workflow"&&await this.handleWorkflowEvent(e)}async handleWorkflowEvent(e){this.workflowOrchestrator}};function Om(u,t,e,r){return new rl(u,t,e,r)}var Te={CoverageAnalyzerService:"coverage-analysis.CoverageAnalyzerService",SecurityScannerService:"security-compliance.SecurityScannerService",isSemgrepAvailable:"security-compliance.isSemgrepAvailable",runSemgrepWithRules:"security-compliance.runSemgrepWithRules",convertSemgrepFindings:"security-compliance.convertSemgrepFindings",createTestGeneratorService:"test-generation.createTestGeneratorService",KnowledgeGraphService:"code-intelligence.KnowledgeGraphService",QualityAnalyzerService:"quality-assessment.QualityAnalyzerService"},il=class{factories=new Map;register(t,e){this.factories.set(t,e)}resolve(t){let e=this.factories.get(t);if(!e)throw new Error(`DomainServiceRegistry: service '${t}' not registered. Ensure the domain module is initialized before coordination.`);return e}has(t){return this.factories.has(t)}clear(){this.factories.clear()}keys(){return Array.from(this.factories.keys())}},Ae=new il;Ae.register(Te.createTestGeneratorService,u=>Tt(u));Ae.register(Te.CoverageAnalyzerService,u=>new mt(u));Ae.register(Te.SecurityScannerService,u=>new $e(u));Ae.register(Te.isSemgrepAvailable,Vi);Ae.register(Te.runSemgrepWithRules,Gs);Ae.register(Te.convertSemgrepFindings,Hs);Ae.register(Te.KnowledgeGraphService,u=>new Rt(u));A();Ae.register(Te.QualityAnalyzerService,u=>new Ye(u));A();M();A();var Ut={SoapOperationTested:"enterprise-integration.SoapOperationTested",MessageFlowTested:"enterprise-integration.MessageFlowTested",BapiTested:"enterprise-integration.BapiTested",IDocValidated:"enterprise-integration.IDocValidated",ODataTested:"enterprise-integration.ODataTested",SodAnalyzed:"enterprise-integration.SodAnalyzed",MiddlewareFlowTested:"enterprise-integration.MiddlewareFlowTested",IntegrationValidationFailed:"enterprise-integration.IntegrationValidationFailed"},Kv={maxConcurrentWorkflows:8,defaultTimeout:12e4,publishEvents:!0,enableMinCutAwareness:!0,topologyHealthThreshold:.5,pauseOnCriticalTopology:!1,enableConsensus:!0,consensusThreshold:.7,consensusStrategy:"weighted",consensusMinModels:2},Aa=R.create("enterprise-integration"),Ea=class extends Q{constructor(e,r,i,n={}){let s={...Kv,...n};super(e,"enterprise-integration",s,{verifyFindingTypes:["soap-fault","message-ordering-violation","rfc-compatibility-break","idoc-validation-failure","odata-contract-break","sod-conflict"],modelTimeout:12e4});this.memory=r;this.agentCoordinator=i}memory;agentCoordinator;async onInitialize(){this.subscribeToEvents(),Aa.info("Enterprise Integration Coordinator initialized")}async onDispose(){}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}getActiveWorkflows(){return super.getActiveWorkflows()}async validateWsdl(e){let r=v();try{if(this.startWorkflow(r,"soap"),this.minCutMixin.shouldPauseOperations())return p(new Error("WSDL validation paused: topology is in critical state"));let i=await this.spawnAgent(r,"qe-soap-tester",{task:"validate-wsdl",url:e});if(!i.success)return this.failWorkflow(r,i.error.message),i;let n={url:e,version:"1.1",services:[],schemas:[]};return await this.memory.set(`enterprise-integration:wsdl:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async testSoapOperation(e,r,i){let n=v();try{this.startWorkflow(n,"soap");let s=await this.spawnAgent(n,"qe-soap-tester",{task:"test-operation",wsdl:e,operation:r,input:i});if(!s.success)return this.failWorkflow(n,s.error.message),p(s.error);let a={operation:r,passed:!0,request:JSON.stringify(i),response:"",validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.SoapOperationTested,this.domainName,{operation:r,wsdlUrl:e.url,passed:a.passed,errors:a.validationErrors.length})),this.completeWorkflow(n),f(a)}catch(s){return this.failWorkflow(n,String(s)),p(y(s))}}async testMessageFlow(e,r){let i=v();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-message-flow",brokerConfig:e,testCase:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={testCaseId:r.id,passed:!0,sentAt:new Date,receivedAt:new Date,latency:0,actualOutcome:r.expectedOutcome,errors:[]};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.MessageFlowTested,this.domainName,{protocol:e.protocol,queue:r.queue,passed:s.passed,latency:s.latency})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async testDlqHandling(e,r){let i=v();try{this.startWorkflow(i,"messaging");let n=await this.spawnAgent(i,"qe-message-broker-tester",{task:"test-dlq",brokerConfig:e,queue:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={queue:r,messageCount:0,poisonMessages:0,reprocessable:0,errors:[]};return this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async testBapiCall(e,r){let i=v();try{if(this.startWorkflow(i,"rfc"),this.minCutMixin.shouldPauseOperations())return p(new Error("BAPI testing paused: topology is in critical state"));let n=await this.spawnAgent(i,"qe-sap-rfc-tester",{task:"test-bapi",connection:e,bapi:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={bapiName:r.name,passed:!0,returnMessages:[],exportValues:{},tableData:{},duration:0,transactionCommitted:!1};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.BapiTested,this.domainName,{bapiName:r.name,passed:s.passed,returnType:s.returnMessages.length>0?s.returnMessages[0].type:"S"})),await this.memory.set(`enterprise-integration:bapi:${r.name}:${Date.now()}`,{bapiName:r.name,importParams:Object.keys(r.importParams),passed:s.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateIdoc(e,r){let i=v();try{this.startWorkflow(i,"idoc");let n=await this.spawnAgent(i,"qe-sap-idoc-tester",{task:"validate-idoc",definition:e,content:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={idocType:e.type,direction:"inbound",passed:!0,statusCode:3,statusMessage:"IDoc validated successfully",segmentValidation:[],processingTime:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.IDocValidated,this.domainName,{idocType:e.type,direction:s.direction,passed:s.passed,statusCode:s.statusCode})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateODataMetadata(e){let r=v();try{this.startWorkflow(r,"odata");let i=await this.spawnAgent(r,"qe-odata-contract-tester",{task:"validate-metadata",serviceUrl:e});if(!i.success)return this.failWorkflow(r,i.error.message),p(i.error);let n={version:"v4",serviceUrl:e,entitySets:[],functionImports:[],actions:[]};return await this.memory.set(`enterprise-integration:odata:${encodeURIComponent(e)}`,n,{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(r),f(n)}catch(i){return this.failWorkflow(r,String(i)),p(y(i))}}async testODataEntitySet(e,r){let i=v();try{this.startWorkflow(i,"odata");let n=await this.spawnAgent(i,"qe-odata-contract-tester",{task:"test-entity-set",metadata:e,entitySet:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={entitySet:r,operation:"CRUD",passed:!0,statusCode:200,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.ODataTested,this.domainName,{entitySet:r,operation:s.operation,passed:s.passed,version:e.version})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateMessageFlow(e,r){let i=v();try{this.startWorkflow(i,"middleware");let n=await this.spawnAgent(i,"qe-middleware-validator",{task:"validate-flow",flow:e,input:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={flowName:e.name,passed:!0,routingCorrect:!0,transformationCorrect:!0,errorHandlingCorrect:!0,validationErrors:[],duration:0};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.MiddlewareFlowTested,this.domainName,{flowName:e.name,passed:s.passed,routingCorrect:s.routingCorrect,transformationCorrect:s.transformationCorrect})),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async validateTransformation(e,r,i){let n=v();try{this.startWorkflow(n,"middleware");let s=await this.spawnAgent(n,"qe-middleware-validator",{task:"validate-transformation",spec:e,input:r,expectedOutput:i});return s.success?(this.completeWorkflow(n),f(!0)):(this.failWorkflow(n,s.error.message),p(s.error))}catch(s){return this.failWorkflow(n,String(s)),p(y(s))}}async analyzeSod(e,r){let i=v();try{this.startWorkflow(i,"sod");let n=await this.spawnAgent(i,"qe-sod-analyzer",{task:"analyze-sod",userId:e,ruleset:r});if(!n.success)return this.failWorkflow(i,n.error.message),p(n.error);let s={userId:e,conflicts:[],riskScore:0,compliant:!0,recommendations:[]};return this.config.publishEvents&&await this.eventBus.publish(D(Ut.SodAnalyzed,this.domainName,{userId:e,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore})),await this.memory.set(`enterprise-integration:sod:${e}:${Date.now()}`,{userId:e,ruleset:r.name,conflicts:s.conflicts.length,compliant:s.compliant,riskScore:s.riskScore,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",persist:!0}),this.completeWorkflow(i),f(s)}catch(n){return this.failWorkflow(i,String(n)),p(y(n))}}async spawnAgent(e,r,i){let n={name:`${r}-${e.slice(0,8)}`,domain:"enterprise-integration",type:r,capabilities:[r],config:{workflowId:e,...i}},s=await this.agentCoordinator.spawn(n);return s.success&&this.addAgentToWorkflow(e,s.value),s}async verifyCriticalFinding(e,r){let i=V({id:v(),type:e.type,confidence:r,description:e.description,payload:e.payload,detectedBy:"enterprise-integration-coordinator",severity:r>.9?"critical":"high"});if(this.consensusMixin.requiresConsensus(i)){let n=await this.consensusMixin.verifyFinding(i);return n.success&&n.value.verdict==="verified"?(Aa.info(`Finding verified by consensus: ${e.type}`),!0):(Aa.warn(`Finding NOT verified: ${e.type}`),!1)}return!0}async handleContractVerified(e){let r=e.payload;(r?.contractType==="soap"||r?.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-event:${Date.now()}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r?.targetService?.includes("middleware")||r?.targetService?.includes("esb"))&&Aa.info(`Middleware fault injection detected: ${r.targetService}`)}};var nl=class extends W{constructor(e,r,i,n={}){super(e,r);this.agentCoordinator=i;this.pluginConfig=n}agentCoordinator;coordinator=null;pluginConfig;get name(){return"enterprise-integration"}get version(){return"1.0.0"}get dependencies(){return[]}getAPI(){return{validateWsdl:this.validateWsdl.bind(this),testSoapOperation:this.testSoapOperation.bind(this),testMessageFlow:this.testMessageFlow.bind(this),testDlqHandling:this.testDlqHandling.bind(this),testBapiCall:this.testBapiCall.bind(this),validateIdoc:this.validateIdoc.bind(this),validateODataMetadata:this.validateODataMetadata.bind(this),testODataEntitySet:this.testODataEntitySet.bind(this),validateMessageFlow:this.validateMessageFlow.bind(this),validateTransformation:this.validateTransformation.bind(this),analyzeSod:this.analyzeSod.bind(this),getCoordinator:()=>this.coordinator,getActiveWorkflows:()=>this.coordinator?.getActiveWorkflows()||[]}}getTaskHandlers(){return new Map([["enterprise-integration:soap-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.wsdl,i=e.operation,n=e.input;return e.url&&!r?this.coordinator.validateWsdl(e.url):!r||!i?p(new Error("Invalid soap-test payload: missing wsdl or operation")):this.coordinator.testSoapOperation(r,i,n)}],["enterprise-integration:message-broker-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.brokerConfig,i=e.testCase,n=e.queue;return r?n&&!i?this.coordinator.testDlqHandling(r,n):i?this.coordinator.testMessageFlow(r,i):p(new Error("Invalid message-broker-test payload: missing testCase")):p(new Error("Invalid message-broker-test payload: missing brokerConfig"))}],["enterprise-integration:sap-rfc-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.connection,i=e.bapi;return!r||!i?p(new Error("Invalid sap-rfc-test payload: missing connection or bapi")):this.coordinator.testBapiCall(r,i)}],["enterprise-integration:sap-idoc-validate",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.definition,i=e.content;return!r||!i?p(new Error("Invalid sap-idoc-validate payload: missing definition or content")):this.coordinator.validateIdoc(r,i)}],["enterprise-integration:odata-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.serviceUrl,i=e.metadata,n=e.entitySet;return r&&!i?this.coordinator.validateODataMetadata(r):!i||!n?p(new Error("Invalid odata-test payload: missing metadata or entitySet")):this.coordinator.testODataEntitySet(i,n)}],["enterprise-integration:esb-flow-test",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.flow,i=e.input,n=e.spec;if(n){let s=e.transformInput,a=e.expectedOutput;return!s||!a?p(new Error("Invalid esb-flow-test payload: missing transformInput or expectedOutput for transformation")):this.coordinator.validateTransformation(n,s,a)}return!r||!i?p(new Error("Invalid esb-flow-test payload: missing flow or input")):this.coordinator.validateMessageFlow(r,i)}],["enterprise-integration:sod-analyze",async e=>{if(!this.coordinator)return p(new Error("Enterprise integration coordinator not initialized"));let r=e.userId,i=e.ruleset;return!r||!i?p(new Error("Invalid sod-analyze payload: missing userId or ruleset")):this.coordinator.analyzeSod(r,i)}]])}async onInitialize(){this.coordinator=new Ea(this.eventBus,this.memory,this.agentCoordinator,this.pluginConfig.coordinator),await this.coordinator.initialize(),this.updateHealth({status:"idle",agents:{total:0,active:0,idle:0,failed:0},lastActivity:new Date,errors:[]})}async onDispose(){this.coordinator&&await this.coordinator.dispose(),this.coordinator=null}subscribeToEvents(){this.eventBus.subscribe("contract-testing.ContractVerified",this.handleContractVerified.bind(this)),this.eventBus.subscribe("quality-assessment.QualityGateEvaluated",this.handleQualityGate.bind(this)),this.eventBus.subscribe("chaos-resilience.FaultInjected",this.handleFaultInjected.bind(this))}async onEvent(e){switch(this.updateHealth({lastActivity:new Date}),e.type){case"contract-testing.ContractVerified":await this.handleContractVerified(e);break;case"quality-assessment.QualityGateEvaluated":await this.handleQualityGate(e);break;case"chaos-resilience.FaultInjected":await this.handleFaultInjected(e);break;default:break}}async validateWsdl(e){this.ensureInitialized();try{let r=await this.coordinator.validateWsdl(e);return r.success?this.trackSuccessfulOperation("validateWsdl"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testSoapOperation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.testSoapOperation(e,r,i);return n.success?this.trackSuccessfulOperation("testSoapOperation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async testMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.testMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("testMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testDlqHandling(e,r){this.ensureInitialized();try{let i=await this.coordinator.testDlqHandling(e,r);return i.success?this.trackSuccessfulOperation("testDlqHandling"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async testBapiCall(e,r){this.ensureInitialized();try{let i=await this.coordinator.testBapiCall(e,r);return i.success?this.trackSuccessfulOperation("testBapiCall"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateIdoc(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateIdoc(e,r);return i.success?this.trackSuccessfulOperation("validateIdoc"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateODataMetadata(e){this.ensureInitialized();try{let r=await this.coordinator.validateODataMetadata(e);return r.success?this.trackSuccessfulOperation("validateODataMetadata"):this.trackFailedOperation(new Error(r.error.message)),r}catch(r){return this.handleError(r)}}async testODataEntitySet(e,r){this.ensureInitialized();try{let i=await this.coordinator.testODataEntitySet(e,r);return i.success?this.trackSuccessfulOperation("testODataEntitySet"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateMessageFlow(e,r){this.ensureInitialized();try{let i=await this.coordinator.validateMessageFlow(e,r);return i.success?this.trackSuccessfulOperation("validateMessageFlow"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async validateTransformation(e,r,i){this.ensureInitialized();try{let n=await this.coordinator.validateTransformation(e,r,i);return n.success?this.trackSuccessfulOperation("validateTransformation"):this.trackFailedOperation(new Error(n.error.message)),n}catch(n){return this.handleError(n)}}async analyzeSod(e,r){this.ensureInitialized();try{let i=await this.coordinator.analyzeSod(e,r);return i.success?this.trackSuccessfulOperation("analyzeSod"):this.trackFailedOperation(new Error(i.error.message)),i}catch(i){return this.handleError(i)}}async handleContractVerified(e){let r=e.payload;(r.contractType==="soap"||r.contractType==="odata")&&await this.memory.set(`enterprise-integration:contract-verified:${r.contractId}`,{contractId:r.contractId,type:r.contractType,passed:r.passed,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleQualityGate(e){let r=e.payload;r.checks.find(n=>n.name==="enterprise-integration")||await this.memory.set(`enterprise-integration:quality-gate-warning:${r.gateId}`,{warning:"Enterprise integration testing not included in quality gate",timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:86400})}async handleFaultInjected(e){let r=e.payload;(r.targetService?.includes("middleware")||r.targetService?.includes("esb")||r.targetService?.includes("broker")||r.targetService?.includes("mq"))&&await this.memory.set(`enterprise-integration:fault-correlation:${r.faultId||Date.now()}`,{targetService:r.targetService,faultType:r.faultType,timestamp:new Date().toISOString()},{namespace:"enterprise-integration",ttl:3600})}ensureInitialized(){if(!this._initialized)throw new Error("EnterpriseIntegrationPlugin is not initialized");if(!this.coordinator)throw new Error("EnterpriseIntegrationPlugin coordinator is not available")}handleError(e){let r=y(e),i=this.getHealth();return this.updateHealth({errors:[...i.errors.slice(-9),r.message],status:i.errors.length>=5?"degraded":i.status}),{success:!1,error:r}}trackSuccessfulOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,total:r.agents.total+1,idle:r.agents.idle+1},lastActivity:new Date})}trackFailedOperation(e){let r=this.getHealth();this.updateHealth({agents:{...r.agents,failed:r.agents.failed+1},errors:[...r.errors.slice(-9),e.message]})}};function Vm(u,t,e,r){return new nl(u,t,e,r)}var _m={"test-generation":(u,t,e)=>Eo(u,t,e),"test-execution":(u,t)=>Fu(u,t),"coverage-analysis":(u,t)=>Zo(u,t),"quality-assessment":(u,t,e)=>lc(u,t,e),"defect-intelligence":(u,t,e)=>hd(u,t,e),"requirements-validation":(u,t,e)=>bd(u,t,e),"code-intelligence":(u,t,e)=>Tc(u,t,e),"security-compliance":(u,t,e)=>Uc(u,t,e),"contract-testing":(u,t,e)=>om(u,t,e),"visual-accessibility":(u,t,e)=>Sm(u,t,e),"chaos-resilience":(u,t,e)=>Am(u,t,e),"learning-optimization":(u,t,e)=>$m(u,t,e),"enterprise-integration":(u,t,e)=>Vm(u,t,e),coordination:(u,t,e)=>Om(u,t,e)},Yv={maxConcurrentAgents:Lr.MAX_CONCURRENT_AGENTS,memoryBackend:"hybrid",hnswEnabled:!0,lazyLoading:!0,enabledDomains:[...be],dataDir:void 0},sl=class{_eventBus;_coordinator;_plugins;_memory;_config;_startTime;_initialized=!1;_loopTracker;constructor(t={}){this._config={...Yv,...t},this._startTime=new Date,this._memory=new Da,this._eventBus=new on,this._coordinator=new cn(this._config.maxConcurrentAgents),this._plugins=new qr(this._eventBus,this._memory,this._config.lazyLoading),this._loopTracker=new ln}get eventBus(){return this._eventBus}get coordinator(){return this._coordinator}get plugins(){return this._plugins}get memory(){return this._memory}async initialize(){if(this._initialized)return;let t=cl(),e=this._config.dataDir||Qt.join(t,".agentic-qe");if(xa.existsSync(e)||xa.mkdirSync(e,{recursive:!0}),this._config.memoryBackend==="memory"){let i=Qt.join(Pa("os").tmpdir(),`aqe-test-${Date.now()}-${Jv().slice(0,12)}.db`);await ul({dbPath:i})}else this._memory=new ll({sqlite:{path:Qt.join(e,"memory.db"),walMode:!0,poolSize:3,busyTimeout:ol.BUSY_TIMEOUT_MS},enableFallback:!0,defaultNamespace:"qe-kernel"}),this._plugins=new qr(this._eventBus,this._memory,this._config.lazyLoading);for(let i of this._config.enabledDomains){let n=_m[i];n&&this._plugins.registerFactory(i,async(s,a)=>Promise.resolve(n(s,a,this._coordinator)))}await this._memory.initialize();let r=new dn({agentId:"qe-kernel"});this._eventBus.registerMiddleware(r);try{let i=Qt.join(e,"plugins"),n=new dl({cacheDir:i}),a=new ml({cache:n}).resolveLoadOrder();for(let o of a.ordered){let c=o.manifest,l=n.get(c.name,c.version);if(!l)continue;let d=Qt.join(l.path,c.entryPoint);for(let m of c.domains){let g=m;if(_m[g])continue;this._plugins.registerFactory(g,async(b,w)=>{let C=await import(d),S=C.default??C.createPlugin;if(typeof S!="function")throw new Error(`Plugin "${c.name}" entry point must export a default function or "createPlugin" function`);return S(b,w,this._coordinator)})}}}catch{}this._config.lazyLoading||await this._plugins.loadAll();try{let{isAgentMemoryBranchingEnabled:i,isRVFPatternStoreEnabled:n}=await import("./feature-flags-3WIZC67K.js");if(i()&&n()){let{getSharedRvfAdapter:s}=await import("./shared-rvf-adapter-UZVFV2RJ.js"),{AgentMemoryBranch:a}=await import("./agent-memory-branch-56GIYNGH.js"),o=s(e,384);if(o){let c=new a(o,{branchDir:Qt.join(e,"branches")});this._coordinator.setMemoryBranch(c)}}}catch{}try{let{getRvfMigrationStage:i}=await import("./feature-flags-3WIZC67K.js"),n=i();if(n>=2){let{RvfMigrationCoordinator:s}=await import("./rvf-migration-coordinator-5RBME46Y.js");await s.getInstance({stage:n}).initialize()}}catch{}this._initialized=!0}async dispose(){await this._plugins.disposeAll(),await this._coordinator.dispose(),await this._eventBus.dispose(),await this._memory.dispose(),this._initialized=!1}getDomainAPI(t){return this._plugins.getPlugin(t)?.getAPI()}async getDomainAPIAsync(t){let e=this._plugins.getPlugin(t);if(!e&&this._config.lazyLoading&&this._config.enabledDomains.includes(t))try{e=await this._plugins.load(t)}catch(r){console.error(`[QEKernel] Failed to lazy load domain ${t}:`,r);return}return e?.getAPI()}async ensureDomainLoaded(t){if(this._plugins.isLoaded(t))return!0;if(!this._config.enabledDomains.includes(t))return console.warn(`[QEKernel] Domain ${t} is not enabled`),!1;try{return await this._plugins.load(t),!0}catch(e){return console.error(`[QEKernel] Failed to load domain ${t}:`,e),!1}}isDomainLoaded(t){return this._plugins.isLoaded(t)}getLoadedDomains(){return this._plugins.getLoaded()}getPendingDomains(){let t=new Set(this._plugins.getLoaded());return this._config.enabledDomains.filter(e=>!t.has(e))}getHealth(){let t=this._coordinator.listAgents(),e={};for(let c of this._plugins.getLoaded()){let l=this._plugins.getPlugin(c);l&&(e[c]=l.getHealth())}for(let c of be)if(!e[c]){let l=this._config.enabledDomains.includes(c),d=this._config.lazyLoading&&l;e[c]={status:d?"healthy":l?"degraded":"healthy",agents:{total:0,active:0,idle:0,failed:0},errors:d?[]:l?["Domain not yet loaded"]:[],loaded:!1,lazyLoadable:d}}let r=this._coordinator.getActiveCount(),i=0,n=Number.MAX_SAFE_INTEGER;if(this._memory instanceof Da){let c=this._memory.getStats();i=c.entries+c.vectors}else i=0;let a=this._eventBus.getMiddlewares().find(c=>c.name==="semantic-anti-drift"),o=a?a.getStats():void 0;return{status:this.determineOverallStatus(e),uptime:Date.now()-this._startTime.getTime(),domains:e,agents:{total:t.length,active:r,maxAllowed:this._config.maxConcurrentAgents},memory:{used:i,available:n},...o?{antiDrift:o}:{}}}determineOverallStatus(t){let e=Object.values(t).map(r=>r.status);return e.some(r=>r==="unhealthy")?"unhealthy":e.some(r=>r==="degraded")?"degraded":"healthy"}getConfig(){return{...this._config}}checkToolCall(t,e,r){if(process.env.AQE_LOOP_DETECTION_ENABLED==="false")return this._loopTracker.trackCall(t,e,r);let i=this._loopTracker.trackCall(t,e,r);if(i.action==="warn"){let n={id:`loop-warn-${t}-${Date.now()}`,type:za.LOOP_WARNING,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature}};this._eventBus.publish(n)}else if(i.action==="steer"){let n={id:`loop-detected-${t}-${Date.now()}`,type:za.LOOP_DETECTED,timestamp:new Date,source:"coordination",correlationId:t,payload:{agentId:t,toolName:e,callCount:i.callCount,signature:i.signature,steeringMessage:i.steeringMessage}};this._eventBus.publish(n)}return i}get loopTracker(){return this._loopTracker}};function i6(u){return new sl(u)}export{Tt as a,mt as b,cr as c,dr as d,Ot as e,Sc as f,he as g,_e as h,zt as i,xc as j,qs as k,Tr as l,Ar as m,fa as n,Pr as o,Ir as p,Gt as q,Ht as r,Wt as s,Te as t,Ae as u,sl as v,i6 as w};