ebman 0.45.0

k9s-style TUI for AWS Elastic Beanstalk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
//! `ebman lint [--env NAME] [--regions r1,r2,r3] [--json] [--severity LVL]
//! [--rules ID1,ID2] [--quiet] [--fix (--yes | --dry-run)]` —
//! rule-engine diagnostics for git hooks / CI gates / monitoring,
//! with opt-in auto-remediation via `--fix`.
//!
//! Exit codes (per the 0.13 CLI charter):
//! - 0 clean / fix applied successfully
//! - 1 AWS-layer error (or `--fix` dispatch failure)
//! - 2 usage error
//! - 3 issues found (NOT used in `--fix` mode — operator's intent
//!   is "see issues then fix them"; a clean apply stays exit 0)
//!
//! `--fix` dispatches each rule's auto-remediation through the same
//! `update_env_option_settings` path the TUI uses. Respects
//! `safety.envs.NAME.read_only` + `safety.accounts.NAME.read_only`
//! pins (matched against `AWS_PROFILE`) so a TUI-locked env can't
//! be written from the CLI. Per-rule opt-out via `lint.fix_disable`.

use color_eyre::eyre::Result;

use crate::lint::inputs::{
    build_lint_context, fetch_env_lint_inputs, fetch_stale_platform_issues, run_rules_for_env,
    EnvLintInputs,
};
use crate::{audit, aws, config, lint, project};

/// Print `--against-baseline --json` diff body. Hand-rolled to
/// avoid pulling serde_json; uses `crate::util::json_string` for
/// the value escapes. Shape:
///
/// ```json
/// {
///   "new": [{ "rule_id": "...", "env": "...", "title": "..." }, ...],
///   "cleared": [{ "rule_id": "...", "env": "...", "title": "..." }, ...]
/// }
/// ```
fn print_baseline_diff_json(new: &[&lint::Issue], cleared: &[&lint::BaselineIssue]) {
    let mut out = String::from("{\"new\":[");
    for (i, issue) in new.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push_str(&format!(
            "{{\"rule_id\":{},\"env\":{},\"title\":{}}}",
            crate::util::json_string(&issue.rule_id),
            crate::util::json_string(issue.env_name.as_deref().unwrap_or("")),
            crate::util::json_string(&issue.title),
        ));
    }
    out.push_str("],\"cleared\":[");
    for (i, b) in cleared.iter().enumerate() {
        if i > 0 {
            out.push(',');
        }
        out.push_str(&format!(
            "{{\"rule_id\":{},\"env\":{},\"title\":{}}}",
            crate::util::json_string(&b.rule_id),
            crate::util::json_string(b.env_name.as_deref().unwrap_or("")),
            crate::util::json_string(&b.title),
        ));
    }
    out.push_str("]}");
    println!("{out}");
}

/// Fully-resolved `ebman lint` arguments: flags parsed, interval and
/// region-CSV resolved, and all cross-flag validation already passed.
/// Separated from [`run`] so the whole parse+validate surface (every
/// exit-2 usage path) is unit-testable without `std::process::exit` or
/// the live config/AWS I/O that follows it.
#[derive(Debug, PartialEq, Eq)]
struct LintArgs {
    env_name: Option<String>,
    regions: Vec<Option<String>>,
    json: bool,
    quiet: bool,
    severity_filter: Option<lint::Severity>,
    rule_filter: Vec<String>,
    fix: bool,
    dry_run: bool,
    yes: bool,
    watch: bool,
    interval_secs: u64,
    baseline_write: Option<String>,
    baseline_against: Option<String>,
    probe_live: bool,
    webhook: Option<String>,
}

/// Whether `lint --fix` may dispatch option-setting writes.
///
/// Extracted because it is a WRITE gate sitting inline in a 622-line
/// async body: dropping the `yes` half dispatches
/// `update_env_option_settings` against a live account on a run the
/// operator asked to preview, and nothing could reach it to say so.
/// Verified NOT CAUGHT by mutation before this existed.
fn fix_may_dispatch(yes: bool, pending: usize) -> bool {
    yes && pending > 0
}

/// Whether the account-level EBL015 pass should run.
///
/// Skipped when the operator scoped the run to one env — the pass is
/// account-wide, so it would report platforms unrelated to what they
/// asked about — and when EBL015 is disabled, since `lint.disable` is a
/// per-env registry and this pass sits outside it. Both halves survived
/// mutation, so an ignored `lint.disable` and an unwanted extra
/// `ListPlatformVersions` call on every scoped run were equally
/// invisible.
fn should_run_account_pass(env_scoped: bool, disabled: &[String]) -> bool {
    !env_scoped && !disabled.iter().any(|d| d == "EBL015")
}

/// Pure: one-line webhook body for a lint cycle. Caps at 5 issues so
/// a noisy fleet doesn't blow out the Slack message; an empty set
/// renders the all-clear (sent on the dirty→clean transition).
fn webhook_summary(issues: &[lint::Issue]) -> String {
    if issues.is_empty() {
        return "lint: ✓ clean (previous issues cleared)".to_string();
    }
    let mut parts: Vec<String> = issues
        .iter()
        .take(5)
        .map(|i| {
            format!(
                "{} {} {}: {}",
                i.severity.as_str(),
                i.rule_id,
                i.env_name.as_deref().unwrap_or("-"),
                i.title
            )
        })
        .collect();
    if issues.len() > 5 {
        parts.push(format!("…and {} more", issues.len() - 5));
    }
    format!("lint: {} issue(s) — {}", issues.len(), parts.join("; "))
}

/// Pure parser + validator for `ebman lint`. Returns `Err(msg)` for
/// every usage error (all exit-2 here, so the code is left implicit).
/// Ordering note: validation runs here, before [`run`] loads config —
/// a usage error now exits before the (silent) config read rather than
/// after. No observable change; strictly less wasted work.
fn parse_lint_args(args: &[String]) -> Result<LintArgs, String> {
    let mut env_name: Option<String> = None;
    let mut regions_csv: Option<String> = None;
    let mut json = false;
    let mut quiet = false;
    let mut severity_filter: Option<lint::Severity> = None;
    let mut rule_filter: Vec<String> = Vec::new();
    let mut fix = false;
    let mut dry_run = false;
    let mut yes = false;
    let mut watch = false;
    let mut interval_str: Option<String> = None;
    let mut baseline_write: Option<String> = None;
    let mut baseline_against: Option<String> = None;
    let mut probe_live = false;
    let mut webhook: Option<String> = None;
    let mut iter = args.iter().skip(1);
    // Every value-taking flag rejects a missing value or a following
    // flag. Silently swallowing either was dangerous: a forgotten
    // `--env` value on `--fix --yes` widened scope to the whole
    // fleet, and `--rules --json` filtered every issue out (exit 0)
    // while eating the JSON flag.
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            "--env" => {
                env_name = Some(crate::cli::take_value(
                    &mut iter,
                    "ebman lint",
                    "--env",
                    "an env name",
                )?)
            }
            "--regions" => {
                regions_csv = Some(crate::cli::take_value(
                    &mut iter,
                    "ebman lint",
                    "--regions",
                    "a region list",
                )?)
            }
            "--json" => json = true,
            "--quiet" => quiet = true,
            "--fix" => fix = true,
            "--dry-run" => dry_run = true,
            "--yes" => yes = true,
            "--watch" => watch = true,
            "--interval" => {
                interval_str = Some(crate::cli::take_value(
                    &mut iter,
                    "ebman lint",
                    "--interval",
                    "a duration",
                )?)
            }
            "--probe-live" => probe_live = true,
            "--webhook" => {
                let Some(u) = iter.next() else {
                    return Err("ebman lint: --webhook expects a URL".into());
                };
                if u.starts_with("--") {
                    return Err(format!(
                        "ebman lint: --webhook expects a URL, got flag '{u}'"
                    ));
                }
                webhook = Some(u.clone());
            }
            "--baseline" => {
                let Some(p) = iter.next() else {
                    return Err("ebman lint: --baseline expects a file path".into());
                };
                if p.starts_with("--") {
                    return Err(format!(
                        "ebman lint: --baseline expects a file path, got flag '{p}'"
                    ));
                }
                baseline_write = Some(p.clone());
            }
            "--against-baseline" => {
                let Some(p) = iter.next() else {
                    return Err("ebman lint: --against-baseline expects a file path".into());
                };
                if p.starts_with("--") {
                    return Err(format!(
                        "ebman lint: --against-baseline expects a file path, got flag '{p}'"
                    ));
                }
                baseline_against = Some(p.clone());
            }
            "--severity" => {
                let Some(v) = iter.next() else {
                    return Err(
                        "ebman lint: --severity expects a value (info / warn / error)".into(),
                    );
                };
                let Some(sev) = lint::Severity::parse(v) else {
                    return Err(format!(
                        "ebman lint: unknown severity '{v}' (info / warn / error)"
                    ));
                };
                severity_filter = Some(sev);
            }
            "--rules" => {
                let v = crate::cli::take_value(
                    &mut iter,
                    "ebman lint",
                    "--rules",
                    "a comma-separated rule id list",
                )?;
                rule_filter = crate::util::split_csv(&v);
                if rule_filter.is_empty() {
                    return Err(format!("ebman lint: --rules got '{v}' — no rule ids in it"));
                }
            }
            other => {
                return Err(format!("ebman lint: unknown flag '{other}'"));
            }
        }
    }

    if watch && fix {
        return Err("ebman lint: --watch and --fix are mutually exclusive (use one)".into());
    }
    if webhook.is_some() && !watch {
        return Err(
            "ebman lint: --webhook only makes sense with --watch (one-shot runs print their findings)"
                .into(),
        );
    }
    if baseline_write.is_some() && baseline_against.is_some() {
        return Err(
            "ebman lint: --baseline (write) and --against-baseline (compare) are mutually exclusive"
                .into(),
        );
    }
    if (baseline_write.is_some() || baseline_against.is_some()) && (fix || watch) {
        return Err(
            "ebman lint: --baseline / --against-baseline are incompatible with --fix / --watch"
                .into(),
        );
    }
    if fix && !yes && !dry_run {
        return Err(
            "ebman lint --fix: requires --yes to dispatch writes (or --dry-run to preview)".into(),
        );
    }
    if fix && yes && dry_run {
        return Err("ebman lint --fix: --yes and --dry-run are mutually exclusive".into());
    }
    // Default interval = 60s. Parse the same way other deadlines
    // are parsed (`5m / 30m / 1h`); accept a bare integer as
    // seconds for monitoring-friendly shapes like `--interval 30`.
    let interval_secs: u64 = match interval_str.as_deref() {
        None => 60,
        Some(s) => {
            if let Ok(n) = s.parse::<u64>() {
                if n == 0 {
                    return Err("ebman lint: --interval must be > 0".into());
                }
                n
            } else if let Some(ms) = aws::parse_window_ms(s) {
                ((ms / 1000) as u64).max(1)
            } else {
                return Err(
                    "ebman lint: --interval expects seconds (`30`) or a duration (`5m`/`1h`)"
                        .into(),
                );
            }
        }
    };

    let regions: Vec<Option<String>> = match regions_csv {
        Some(csv) => {
            let parsed: Vec<String> = crate::util::split_csv(&csv);
            if parsed.is_empty() {
                return Err("ebman lint: --regions list is empty".into());
            }
            parsed.into_iter().map(Some).collect()
        }
        None => vec![None],
    };

    Ok(LintArgs {
        env_name,
        regions,
        json,
        quiet,
        severity_filter,
        rule_filter,
        fix,
        dry_run,
        yes,
        watch,
        interval_secs,
        baseline_write,
        baseline_against,
        probe_live,
        webhook,
    })
}

/// Everything one lint cycle produced, including what it failed to do.
///
/// ARCHITECTURE.md rule 6 as a type. The cycle reported through four
/// mutable locals and one process-global, read a page or more from
/// where they were written — and all three lint defects this file has
/// shipped lived in that wiring rather than in the pure helpers, which
/// were tested. A fetch that fails now has to put its failure
/// somewhere, instead of choosing between `degrade` and an `eprintln!`
/// that leaves the cycle looking clean. One arm chose the second, and
/// nothing noticed until an architecture review read it.
#[derive(Debug, Default)]
pub(crate) struct CycleReport {
    pub issues: Vec<lint::Issue>,
    /// WHY the cycle is incomplete, not just that it is. Printed
    /// unconditionally and carried into `--json`: gating these on
    /// `!quiet` produced a non-zero exit with an empty log, the one
    /// combination a CI step cannot act on.
    pub degrade_reasons: Vec<String>,
    /// A `--fix` dispatch failed. Distinct from degraded: the cycle
    /// saw the fleet correctly and could not change it.
    pub fix_dispatch_failed: bool,
    /// The operator asked for something that cannot be done — today,
    /// `--env NAME` where NAME is not in the only context being
    /// linted. Returned rather than exited.
    ///
    /// `run_cycle` used to call `exit_after_drain(2)` here, inside the
    /// function extracted to make the cycle testable. No test can
    /// cover a branch that kills the test binary, so the single most
    /// likely `ebman lint --env X` mistake was the one path the seam
    /// could not reach. `run` owns the exit; the cycle reports.
    pub usage_error: Option<String>,
}

impl CycleReport {
    /// Incomplete coverage: some region, environment or account-level
    /// pass did not answer, so the issue set is not a full picture —
    /// the webhook must not page on it and `--baseline` must not adopt
    /// it.
    ///
    /// Derived, never stored. A caller cannot mark the cycle degraded
    /// without saying why, and the flag cannot drift from the reason.
    pub(crate) fn degraded(&self) -> bool {
        !self.degrade_reasons.is_empty()
    }

    /// Record a failure that makes this cycle incomplete. The only way
    /// to reach that state.
    pub(crate) fn degrade(&mut self, reason: String) {
        eprintln!("warning: {reason}");
        self.degrade_reasons.push(reason);
    }
}

/// Should this `lint --watch` cycle post to the webhook?
///
/// Only a CHANGE from a known previous state, or first findings. A first
/// cycle that is already clean posts nothing: the all-clear body claims
/// issues cleared, and none did.
///
/// Extracted from `run`'s watch loop, where both halves of the condition
/// were survivable. Getting either wrong is a pager consequence — the
/// `!=` re-posts an unchanged set every interval, and dropping the
/// first-cycle-clean test pages "all clear" at someone who never had an
/// alert.
pub(crate) fn should_post_webhook(
    previous: Option<&std::collections::BTreeSet<String>>,
    current: &std::collections::BTreeSet<String>,
) -> bool {
    let first_cycle_clean = previous.is_none() && current.is_empty();
    !first_cycle_clean && previous != Some(current)
}

/// Apply the operator's `--min-severity` and `--rule` filters.
///
/// Written out twice inside `run` — once on the main path and once on
/// the `--watch` cycle path — and both copies carried the same
/// survivors. Which issues reach the operator is the whole output of
/// this subcommand, so it is worth being able to assert.
pub(crate) fn filter_issues(
    issues: &mut Vec<lint::Issue>,
    severity_filter: Option<lint::Severity>,
    rule_filter: &[String],
) {
    if let Some(min) = severity_filter {
        issues.retain(|i| i.severity >= min);
    }
    if !rule_filter.is_empty() {
        issues.retain(|i| rule_filter.contains(&i.rule_id));
    }
}

/// The process exit code for a completed lint run.
///
/// This is what gates CI, and the matrix in `docs/headless.md` is the
/// contract: 0 clean, 3 issues found, 1 an AWS/degraded run. The
/// ordering matters — "issues found" beats "degraded" because exit 3 is
/// actionable, while a *clean but incomplete* run must NOT pass green,
/// since a region skipped on expired credentials would otherwise look
/// identical to a passing check.
///
/// `--fix` reports on the dispatch rather than on cleanliness: fixing
/// issues is the point, so finding them is not a failure.
///
/// Extracted from the tail of `run`, where each branch called
/// `std::process::exit` inline and none was reachable from a test.
pub(crate) fn lint_exit_code(
    fix: bool,
    fix_dispatch_failed: bool,
    degraded: bool,
    clean: bool,
) -> i32 {
    if fix {
        if fix_dispatch_failed || degraded {
            1
        } else {
            0
        }
    } else if !clean {
        3
    } else if degraded {
        1
    } else {
        0
    }
}

/// The two sides of a `--baseline` comparison: issues present now that
/// the baseline did not record, and baseline issues that no longer
/// reproduce.
pub(crate) struct BaselineDrift<'a> {
    pub new_issues: Vec<&'a lint::Issue>,
    pub cleared: Vec<&'a lint::BaselineIssue>,
    /// Distinct baseline identities. Deduplicated, so a baseline file
    /// listing the same issue twice counts once — which is what the
    /// "N issues stable" line means.
    pub baseline_count: usize,
}

/// Compare the current findings against a recorded baseline.
///
/// `ebman lint --baseline` is a CI gate: `new_issues` is what fails the
/// build, so a bug here either lets a regression through or breaks a
/// build over an issue the operator already accepted. Both directions
/// are computed by identity (`lint::issue_identity`), not by rule id —
/// the same rule firing on a different env is a *different* issue.
///
/// Extracted from `run`'s watch loop, where it sat inline between two
/// pages of printing and no test could reach it.
pub(crate) fn baseline_drift<'a>(
    all_issues: &'a [lint::Issue],
    baseline_issues: &'a [lint::BaselineIssue],
) -> BaselineDrift<'a> {
    let baseline_set: std::collections::HashSet<&str> = baseline_issues
        .iter()
        .map(|b| b.identity.as_str())
        .collect();
    let current_identities: Vec<String> = all_issues.iter().map(lint::issue_identity).collect();
    let current_set: std::collections::HashSet<&str> =
        current_identities.iter().map(String::as_str).collect();

    let new_issues: Vec<&lint::Issue> = all_issues
        .iter()
        .zip(current_identities.iter())
        .filter(|(_, id)| !baseline_set.contains(id.as_str()))
        .map(|(i, _)| i)
        .collect();
    let cleared: Vec<&lint::BaselineIssue> = baseline_issues
        .iter()
        .filter(|b| !current_set.contains(b.identity.as_str()))
        .collect();
    BaselineDrift {
        new_issues,
        cleared,
        baseline_count: baseline_set.len(),
    }
}

/// How long `--watch` sleeps before the next cycle.
///
/// The interval is start-to-start: a cycle that took 20s of a 60s
/// interval sleeps 40s, so `--interval 60s` fires every ~60s rather
/// than every 60s-plus-however-long-the-fleet-scan-took. A cycle that
/// overran its interval sleeps zero and starts again immediately.
///
/// Takes the elapsed time as a `chrono::Duration` so that the
/// clock-going-backwards case is decided here rather than by an
/// `unwrap_or_default()` at the call site: a negative elapsed means the
/// wall clock moved under us (NTP step, suspend/resume), and the safe
/// reading is "no time passed", i.e. sleep the whole interval.
pub(crate) fn watch_sleep(
    interval_secs: u64,
    cycle_elapsed: chrono::Duration,
) -> std::time::Duration {
    std::time::Duration::from_secs(interval_secs)
        .saturating_sub(cycle_elapsed.to_std().unwrap_or_default())
}

/// Run one lint cycle: every region, every environment, the
/// account-level pass, and the `--fix` dispatch.
///
/// Extracted from `run`'s watch loop. The pure decision helpers here
/// were always testable — `lint_exit_code`, `should_post_webhook`,
/// `filter_issues`, `fix_may_dispatch` — and all three defects this
/// file has shipped lived in the WIRING between them, which no test
/// could reach because the loop built its own AWS clients inline.
///
/// `client_for` is that seam. Production passes
/// `AwsClient::with(None, region)`; a test passes a closure over mock
/// SDK clients and can then assert on the returned `CycleReport`
/// rather than on a process exit code. Extraction without this
/// parameter would have made the function shorter and no more
/// testable, which is a readability change wearing a defect-risk
/// argument — the two were worth separating.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn run_cycle<F, Fut>(
    regions: &[Option<String>],
    env_name: &Option<String>,
    disabled: &[String],
    probe_live: bool,
    fix: bool,
    yes: bool,
    quiet: bool,
    json: bool,
    severity_filter: Option<lint::Severity>,
    rule_filter: &[String],
    // Ambient and disk-derived state arrives as arguments so a test
    // touches neither the developer's config nor their environment —
    // which is what makes the wiring reachable at all.
    safety_cfg: &config::Config,
    fix_disabled: &[String],
    active_profile_for_safety: &Option<String>,
    client_for: F,
    now: chrono::DateTime<chrono::Utc>,
) -> CycleReport
where
    F: Fn(Option<String>) -> Fut,
    Fut: std::future::Future<Output = color_eyre::eyre::Result<aws::AwsClient>>,
{
    let mut report = CycleReport::default();
    // Pure, so computed here rather than threaded in.
    let rules = lint::default_rules(disabled);
    let multi_region = regions.len() > 1;
    // For `--env NAME` across several regions: was NAME seen anywhere,
    // and did every region actually answer? See `env_not_found_anywhere`.
    let mut env_found = false;
    let mut every_region_answered = true;
    for region_opt in regions {
        // Through the seam, not `AwsClient::with` directly — the
        // latter is what made this loop unreachable from a test.
        let aws = match client_for(region_opt.clone()).await {
            Ok(c) => c,
            Err(e) => {
                let region_label = region_opt.as_deref().unwrap_or("default");
                report.degrade(format!(
                    "skipping region '{region_label}' — AwsClient::with: {e}"
                ));
                every_region_answered = false;
                continue;
            }
        };
        let envs = match aws.list_environments().await {
            Ok(envs) => envs,
            Err(e) => {
                let region_label = aws.context.region.as_str();
                report.degrade(format!(
                    "skipping region '{region_label}' — list_environments: {e}"
                ));
                every_region_answered = false;
                continue;
            }
        };
        // Per-region one-shot fetch for EBL008 (stale platform):
        // `ListAvailableSolutionStacks` is region-scoped + cheap
        // (single call, no pagination). On failure EBL008 is skipped
        // for the region rather than aborting lint — but the cycle is
        // DEGRADED, not clean.
        //
        // This was the twin of the EBL015 bug 0.44 fixed, 45 lines
        // apart in the same function and missed by the same pass. An
        // empty map makes `newer_stack_available` `None`, which makes
        // `StalePlatformVersion::applies` return `None` — so a run
        // whose stack listing never happened exited 0 and
        // `--baseline` snapshotted it as good. The comment here used
        // to justify it as "the same tolerance pattern the per-env
        // fetches use below"; those fetches degrade.
        //
        // The failure is carried in `Platforms`, and reported once for
        // the region below (`Platforms::report_once`) once the envs in
        // scope are known.
        let platforms =
            lint::inputs::Platforms::from_listing(aws.list_solution_stacks().await, |e| {
                e.to_string()
            });

        let targets: Vec<&aws::Environment> = match env_name.as_deref() {
            Some(name) => match envs.iter().find(|e| e.name == name) {
                Some(env) => {
                    env_found = true;
                    vec![env]
                }
                None => {
                    if multi_region && !quiet {
                        let region_label = aws.context.region.as_str();
                        eprintln!(
                            "warning: env '{name}' not in region '{region_label}' — skipping"
                        );
                    } else if !multi_region {
                        report.usage_error =
                            Some(format!("env '{name}' not found in current context"));
                        return report;
                    }
                    continue;
                }
            },
            None => envs.iter().collect(),
        };
        // One failed listing is one degrade line for the region, naming
        // it — not one per env over the same cause — and only when an
        // env in scope could have had EBL008 fire.
        let platforms = platforms.report_once(
            targets
                .iter()
                .any(|e| lint::inputs::ebl008_could_fire(disabled, e)),
            |why| {
                let region_label = aws.context.region.as_str();
                report.degrade(format!("EBL008 skipped — region '{region_label}': {why}"));
            },
        );

        for env in targets {
            // Fetch + build + run via the shared assembly path
            // (`fetch_env_lint_inputs` / `run_rules_for_env`) —
            // the same pair the MCP `lint` tool calls.
            let inputs = match fetch_env_lint_inputs(
                &aws,
                env,
                &platforms,
                probe_live,
                disabled,
                &safety_cfg.required_tags,
            )
            .await
            {
                Ok(inputs) => inputs,
                Err(e) => {
                    report.degrade(format!(
                        "skipping {} — fetch_env_option_settings: {e}",
                        env.name
                    ));
                    continue;
                }
            };
            // A probe that could not run is not a clean result. The
            // rule still skips — a failed probe must never become a
            // false positive — but silence here made an
            // AccessDenied on iam:SimulatePrincipalPolicy look
            // identical to a passing check, in output that gates CI.
            for w in &inputs.coverage_warnings {
                report.degrade(w.clone());
            }
            let mut issues = run_rules_for_env(&rules, env, &inputs, &safety_cfg.required_tags);
            filter_issues(&mut issues, severity_filter, rule_filter);
            if let Some(region) = region_opt {
                for issue in &mut issues {
                    issue.fields.insert("region".into(), region.clone());
                }
            }

            if fix
                && !issues.is_empty()
                && apply_fixes_for_env(
                    &aws,
                    env,
                    &inputs,
                    &issues,
                    &rules,
                    yes,
                    quiet,
                    json,
                    fix_disabled,
                    safety_cfg,
                    active_profile_for_safety,
                )
                .await
            {
                report.fix_dispatch_failed = true;
            }

            report.issues.extend(issues);
        }

        // EBL015 — account-level pass (stale custom platforms) via
        // the assembly shared with the MCP lint tool. Outside the
        // per-env registry, so `lint.disable` is honoured here;
        // skipped when linting a single --env (the operator scoped
        // the run) and in the common zero-custom-platform account
        // the extra cost is one empty list call.
        if should_run_account_pass(env_name.is_some(), disabled) {
            // The cycle's clock, passed in. EBL015's staleness threshold is
            // date-dependent, so reading the wall clock here meant the
            // account-level pass could not be tested at a fixed time —
            // inside the function extracted to make the cycle testable.
            match fetch_stale_platform_issues(&aws, now).await {
                Ok((mut issues, warnings)) => {
                    // A branch whose `DescribePlatformVersion` failed
                    // is EBL015 coverage that did not happen, so it
                    // DEGRADES the cycle — the same reasoning the Err
                    // arm below carries, one level down.
                    //
                    // This printed and continued until 0.45. 0.44
                    // fixed the failure of the pass as a WHOLE; the
                    // per-branch one beside it was not, so a partial
                    // EBL015 failure still exited 0, the webhook
                    // stayed quiet, and `--baseline` snapshotted a run
                    // whose stale-platform check never ran for that
                    // branch. Gated on `!quiet`, which erased the only
                    // evidence — the exact pairing the `--quiet` bug
                    // taught, and which the Err arm's comment below
                    // already names.
                    //
                    // `every_degrade_goes_through_the_helper` cannot
                    // catch this class: it checks that sites which DO
                    // degrade use the helper, and is blind to a site
                    // that should and does not.
                    for w in warnings {
                        report.degrade(w);
                    }
                    filter_issues(&mut issues, severity_filter, rule_filter);
                    if let Some(region) = region_opt {
                        for issue in &mut issues {
                            issue.fields.insert("region".into(), region.clone());
                        }
                    }
                    report.issues.extend(issues);
                }
                Err(e) => {
                    // Through `degrade`, like every other fetch
                    // failure in this cycle. It printed and
                    // returned, so an EBL015 fetch failure left
                    // the cycle looking CLEAN: exit 0, and
                    // `--baseline` would snapshot a run whose
                    // account-level pass never happened. `--quiet`
                    // suppressed the only evidence, which is the
                    // exact pairing the `--quiet` bug taught
                    // (a non-zero exit with an empty log).
                    //
                    // `every_degrade_goes_through_the_helper`
                    // could not catch this: it checks that sites
                    // which DO degrade use the helper, and cannot
                    // see a site that should and does not.
                    report.degrade(format!("EBL015 skipped — ListPlatformVersions: {e}"));
                }
            }
        }
    }
    if let Some(msg) = env_not_found_anywhere(
        env_name.as_deref(),
        regions.len(),
        env_found,
        every_region_answered,
    ) {
        report.usage_error = Some(msg);
    }
    report
}

/// `--env NAME` across several regions, found in none of them: a usage
/// error, exactly as it is for one region.
///
/// Each region used to print "not in region X — skipping" (behind
/// `--quiet`) and move on, and nothing checked afterwards whether NAME
/// had turned up ANYWHERE. So a typo'd env in a multi-region CI gate
/// exited 0 with "No issues found".
///
/// Only when every region answered. If one could not be listed, NAME
/// may be there — the run is already degraded, and calling it a typo
/// would be a claim the evidence does not support. Single-region runs
/// return their usage error inside the loop, so this is `None` for
/// them. Shared by `lint` and `drift`, which had the same gap.
pub(crate) fn env_not_found_anywhere(
    env_name: Option<&str>,
    region_count: usize,
    found: bool,
    every_region_answered: bool,
) -> Option<String> {
    let name = env_name?;
    (region_count > 1 && !found && every_region_answered)
        .then(|| format!("env '{name}' not found in any of the {region_count} regions checked"))
}

/// `ebman lint` — run the diagnostic rule engine over the fleet.
///
/// Exit codes are [`lint_exit_code`]'s: 0 clean, 3 issues found, 1 a
/// degraded run (a region, env, input fetch or probe failed — so a
/// "clean" result is not full coverage) or a failed `--fix` dispatch,
/// and 2 a usage error. `--baseline` also exits 1 rather than snapshot
/// a degraded run.
pub async fn run(args: &[String]) -> Result<()> {
    let LintArgs {
        env_name,
        regions,
        json,
        quiet,
        severity_filter,
        rule_filter,
        fix,
        // `dry_run` is consumed entirely by the parser's validation
        // (--fix needs --yes XOR --dry-run); the apply path below keys
        // on `yes` alone, so it isn't bound here.
        dry_run: _,
        yes,
        watch,
        interval_secs,
        baseline_write,
        baseline_against,
        probe_live,
        webhook,
    } = match parse_lint_args(args) {
        Ok(parsed) => parsed,
        Err(msg) => {
            eprintln!("{msg}");
            std::process::exit(2);
        }
    };

    let mut disabled: Vec<String> = config::load_lint_disables();
    disabled.extend(project::load_lint_disables_from_cwd());

    let mut fix_disabled: Vec<String> = config::load_lint_fix_disables();
    fix_disabled.extend(project::load_lint_fix_disables_from_cwd());

    let safety_cfg = config::load();
    let active_profile_for_safety = std::env::var("AWS_PROFILE").ok();
    // `run_cycle` computes its own; this one is for the printing
    // and baseline branches below, which stayed in `run`.
    let multi_region = regions.len() > 1;
    // Cross-process fleet freeze: a real fix dispatch (--fix --yes)
    // must refuse while a live TUI session holds :freeze-deploys /
    // :incident (a --dry-run plans nothing, so it stays allowed).
    // This path had the same blind spot action/replay had.
    if fix && yes {
        crate::cli::refuse_if_frozen(
            "ebman lint --fix",
            crate::verb::Verb::SetOption.audit_label(),
        )
        .await;
    }
    if webhook.is_some() {
        // CLI mode installs no tracing subscriber — route webhook
        // delivery failures to stderr so a broken URL isn't silent.
        audit::webhook_errors_to_stderr();
    }

    // `--watch` wraps the existing one-shot body in a polling loop
    // that emits each cycle's issues and sleeps `interval_secs`.
    // Ctrl-C breaks; the exit code reflects the LAST cycle's state
    // so a clean shutdown after a clean cycle exits 0, after a
    // dirty cycle exits 3.
    // Tracks the most-recent cycle's "no issues found" state.
    // Initialised here so the post-loop exit-code branch can read
    // it even if the loop somehow exits without running a full
    // cycle (currently impossible — the unconditional first
    // iteration always sets it — but the initial value keeps the
    // borrow checker honest and documents the invariant).
    let mut last_cycle_clean;
    // Tracks whether the most-recent cycle skipped any region/env on
    // a fetch failure. A degraded "clean" run must exit 1 (the
    // documented AWS-error code), not 0 — expired credentials in a
    // CI gate previously produced a silent green pass.
    let mut last_cycle_degraded;
    // Survives the watch loop the same way `last_cycle_degraded` does.
    // This was a process-global `AtomicBool` written three loops deep
    // and read once at exit — a static only because the failure had no
    // other way out of the nesting. The report carries it out, so the
    // static dissolves.
    let mut last_fix_failed = false;
    // `--webhook` change-guard: identity set of the last cycle POSTed.
    // `None` until the first cycle, so the first findings (or first
    // clean state) always fire once.
    let mut last_webhook_identities: Option<std::collections::BTreeSet<String>> = None;
    // One ctrl_c future for the whole watch loop: creating a fresh
    // stream each iteration loses a SIGINT delivered mid-cycle (the
    // first ctrl_c() call overrides SIGINT's default disposition for
    // the process lifetime, and no listener is live while a cycle's
    // AWS fetches run — the keypress was silently swallowed).
    let ctrl_c = tokio::signal::ctrl_c();
    tokio::pin!(ctrl_c);
    loop {
        let cycle_started = chrono::Utc::now();
        if watch && !quiet && !json {
            println!("--- {} ---", cycle_started.to_rfc3339());
        }
        let report = run_cycle(
            &regions,
            &env_name,
            &disabled,
            probe_live,
            fix,
            yes,
            quiet,
            json,
            severity_filter,
            &rule_filter,
            &safety_cfg,
            &fix_disabled,
            &active_profile_for_safety,
            |region| async move { aws::AwsClient::with(None, region).await },
            cycle_started,
        )
        .await;

        // The cycle reports a usage error; `run` owns the exit. Same
        // message and same exit code 2 as the `exit_after_drain` call
        // this replaced — moved out so the branch is reachable from a
        // test.
        if let Some(msg) = report.usage_error.as_deref() {
            eprintln!("ebman lint: {msg}");
            crate::cli::exit_after_drain(2).await;
        }

        // `--webhook URL` (watch mode): POST the cycle's findings when
        // the issue SET changed since the last post — a 60s interval
        // must not re-page the channel with the same three warnings
        // every minute, but a new issue (or the all-clear) should land
        // immediately. Identity comes from `lint::issue_identity`, the
        // same key the baseline machinery uses.
        if let Some(url) = webhook.as_deref() {
            if report.degraded() {
                // Incomplete data: don't page, don't move the baseline.
                // The next full cycle compares against the last GOOD
                // state, so a real change during the outage still fires.
                if !quiet {
                    eprintln!("warning: cycle degraded (fetch failures) — webhook suppressed");
                }
            } else {
                let identities: std::collections::BTreeSet<String> =
                    report.issues.iter().map(lint::issue_identity).collect();
                // A first cycle that's already clean posts nothing —
                // the all-clear body claims issues cleared, and none
                // did. Only a change from a KNOWN previous state (or
                // first findings) is worth a page.
                if should_post_webhook(last_webhook_identities.as_ref(), &identities) {
                    let detail = webhook_summary(&report.issues);
                    audit::fire_webhook(
                        url,
                        None,
                        active_profile_for_safety.as_deref(),
                        if multi_region {
                            "multi"
                        } else {
                            regions[0].as_deref().unwrap_or("default")
                        },
                        &detail,
                        &cycle_started.to_rfc3339(),
                    );
                }
                last_webhook_identities = Some(identities);
            }
        }

        // Baseline modes (write / diff) handle their own output
        // shape; skip the standard text/json render in those paths.
        let baseline_mode = baseline_write.is_some() || baseline_against.is_some();
        if !quiet && !baseline_mode {
            if json {
                println!(
                    "{}",
                    lint::render_report_json(&report.issues, &report.degrade_reasons)
                );
            } else if report.issues.is_empty() {
                println!("✓ No issues found");
            } else {
                for issue in &report.issues {
                    let sev = issue.severity.as_str();
                    let env_str = issue.env_name.as_deref().unwrap_or("-");
                    if multi_region {
                        let region = issue
                            .fields
                            .get("region")
                            .map(String::as_str)
                            .unwrap_or("-");
                        println!(
                            "{region}\t{sev}\t{}\t{env_str}\t{}",
                            issue.rule_id, issue.title
                        );
                    } else {
                        println!("{sev}\t{}\t{env_str}\t{}", issue.rule_id, issue.title);
                    }
                    if let Some(s) = &issue.suggestion {
                        println!("\t→ {s}");
                    }
                }
            }
            use std::io::Write;
            let _ = std::io::stdout().flush();
        }

        // --baseline FILE: snapshot current issues to disk, exit 0.
        // Operators use this once when adopting `ebman lint` on a
        // fleet with existing warnings — grandfathers them so
        // subsequent runs only flag NEW issues.
        if let Some(path) = baseline_write.as_deref() {
            // A degraded run (skipped regions/envs) has an incomplete
            // issue set — snapshotting it would silently grandfather
            // whatever the outage hid, and the next --against-baseline
            // run would report the reappeared issues as NEW (or worse,
            // a fully-failed run writes an empty baseline).
            if report.degraded() {
                eprintln!(
                    "ebman lint --baseline: refusing to snapshot a degraded run \
                     (fetch failures above) — fix access and re-run"
                );
                std::process::exit(1);
            }
            let body = lint::render_issues_json(&report.issues);
            if let Err(e) = std::fs::write(path, &body) {
                eprintln!("ebman lint --baseline: write {path}: {e}");
                std::process::exit(1);
            }
            if !quiet {
                eprintln!(
                    "ebman lint --baseline: wrote {} issue(s) to {path}",
                    report.issues.len()
                );
            }
            last_cycle_clean = true; // snapshot ALWAYS exits 0
        } else if let Some(path) = baseline_against.as_deref() {
            // --against-baseline FILE: diff current issues against
            // the snapshot. NEW issues exit 3; CLEARED issues are
            // informational. Composes with --json (emits a single
            // {new:[...],cleared:[...]} blob).
            let baseline_text = match std::fs::read_to_string(path) {
                Ok(t) => t,
                Err(e) => {
                    eprintln!("ebman lint --against-baseline: read {path}: {e}");
                    std::process::exit(1);
                }
            };
            let baseline_issues = match lint::parse_baseline(&baseline_text) {
                Ok(v) => v,
                Err(e) => {
                    eprintln!("ebman lint --against-baseline: {e}");
                    std::process::exit(1);
                }
            };
            let BaselineDrift {
                new_issues,
                cleared,
                baseline_count,
            } = baseline_drift(&report.issues, &baseline_issues);

            if !quiet {
                if json {
                    print_baseline_diff_json(&new_issues, &cleared);
                } else {
                    if new_issues.is_empty() && cleared.is_empty() {
                        println!("✓ No drift vs baseline ({} issues stable)", baseline_count);
                    }
                    for issue in &new_issues {
                        let sev = issue.severity.as_str();
                        let env_str = issue.env_name.as_deref().unwrap_or("-");
                        println!(
                            "+ NEW\t{sev}\t{}\t{env_str}\t{}",
                            issue.rule_id, issue.title
                        );
                    }
                    for b in &cleared {
                        let env_str = b.env_name.as_deref().unwrap_or("-");
                        println!("✓ CLEARED\t{}\t{env_str}\t{}", b.rule_id, b.title);
                    }
                }
                use std::io::Write;
                let _ = std::io::stdout().flush();
            }

            last_cycle_clean = new_issues.is_empty();
        } else {
            last_cycle_clean = report.issues.is_empty();
        }
        last_cycle_degraded = report.degraded();
        // Sticky across cycles: a `--watch` run whose fix failed once
        // must not exit 0 because a later cycle had nothing to fix.
        // The static behaved this way by accident of being global;
        // here it is deliberate.
        last_fix_failed |= report.fix_dispatch_failed;

        if !watch {
            break;
        }
        // Sleep `interval_secs` or break on Ctrl-C — whichever
        // fires first. `tokio::signal::ctrl_c` panics if called
        // outside a Tokio runtime, but `run` is `#[tokio::main]`-
        // driven so we're always inside one here.
        tokio::select! {
            _ = &mut ctrl_c => {
                if !quiet && !json {
                    eprintln!("(watch interrupted)");
                }
                break;
            }
            _ = tokio::time::sleep(
                // Interval is start-to-start: subtract the cycle's own
                // duration so `--interval 60s` fires every ~60s, not
                // 60s + however long the fleet scan took.
                watch_sleep(interval_secs, chrono::Utc::now() - cycle_started),
            ) => {}
        }
    }

    // Drain in-flight webhook POSTs (lint --fix audit fan-out and
    // --watch --webhook cycle posts) before the process ends —
    // fire-and-forget tasks are cancelled at runtime drop.
    audit::drain_webhooks(std::time::Duration::from_secs(12)).await;
    let code = lint_exit_code(fix, last_fix_failed, last_cycle_degraded, last_cycle_clean);
    if code != 0 {
        std::process::exit(code);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn argv(parts: &[&str]) -> Vec<String> {
        parts.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn bare_lint_has_sane_defaults() {
        let p = parse_lint_args(&argv(&["lint"])).unwrap();
        assert_eq!(p.regions, vec![None]);
        assert_eq!(p.interval_secs, 60);
        assert!(!p.json && !p.quiet && !p.fix && !p.watch);
        assert!(p.severity_filter.is_none() && p.rule_filter.is_empty());
        assert!(p.baseline_write.is_none() && p.baseline_against.is_none());
    }

    #[test]
    fn collects_filters_and_flags() {
        let p = parse_lint_args(&argv(&[
            "lint",
            "--env",
            "prod",
            "--json",
            "--quiet",
            "--severity",
            "warn",
            "--rules",
            "EBL001, EBL004 ,EBL019",
        ]))
        .unwrap();
        assert_eq!(p.env_name.as_deref(), Some("prod"));
        assert!(p.json && p.quiet);
        assert_eq!(p.severity_filter, Some(lint::Severity::Warn));
        // CSV split + trimmed.
        assert_eq!(p.rule_filter, vec!["EBL001", "EBL004", "EBL019"]);
    }

    #[test]
    fn unknown_flag_and_severity_are_usage_errors() {
        assert!(parse_lint_args(&argv(&["lint", "--bogus"]))
            .unwrap_err()
            .contains("unknown flag"));
        assert!(parse_lint_args(&argv(&["lint", "--severity", "loud"]))
            .unwrap_err()
            .contains("unknown severity"));
    }

    #[test]
    fn baseline_flag_requires_a_path_not_another_flag() {
        // value-flag that swallows the next token must reject a flag
        // sitting where the path should be (the `--baseline --json` trap).
        let err = parse_lint_args(&argv(&["lint", "--baseline", "--json"])).unwrap_err();
        assert!(err.contains("--baseline expects a file path"), "got: {err}");
        // ...and a totally missing value is the same class of error.
        let err2 = parse_lint_args(&argv(&["lint", "--baseline"])).unwrap_err();
        assert!(
            err2.contains("--baseline expects a file path"),
            "got: {err2}"
        );
    }

    #[test]
    fn interval_accepts_bare_seconds_and_durations_rejects_zero_and_garbage() {
        assert_eq!(
            parse_lint_args(&argv(&["lint", "--interval", "30"]))
                .unwrap()
                .interval_secs,
            30
        );
        assert_eq!(
            parse_lint_args(&argv(&["lint", "--interval", "5m"]))
                .unwrap()
                .interval_secs,
            300
        );
        assert!(parse_lint_args(&argv(&["lint", "--interval", "0"]))
            .unwrap_err()
            .contains("must be > 0"));
        assert!(parse_lint_args(&argv(&["lint", "--interval", "soon"]))
            .unwrap_err()
            .contains("expects seconds"));
        // The docs' own example form — rejected until the 0.26
        // max-review added the seconds unit to parse_window_ms.
        assert_eq!(
            parse_lint_args(&argv(&["lint", "--interval", "60s"]))
                .unwrap()
                .interval_secs,
            60
        );
    }

    #[test]
    fn value_flags_reject_missing_or_flag_values() {
        // A trailing --env on `--fix --yes` used to silently widen
        // scope to the whole fleet; --rules eating --json used to
        // filter every issue out and exit 0.
        assert!(parse_lint_args(&argv(&["lint", "--fix", "--yes", "--env"]))
            .unwrap_err()
            .contains("--env expects"));
        assert!(parse_lint_args(&argv(&["lint", "--env", "--json"]))
            .unwrap_err()
            .contains("got flag"));
        assert!(parse_lint_args(&argv(&["lint", "--rules", "--json"]))
            .unwrap_err()
            .contains("got flag"));
        assert!(parse_lint_args(&argv(&["lint", "--rules", " , "]))
            .unwrap_err()
            .contains("no rule ids"));
        assert!(parse_lint_args(&argv(&["lint", "--regions"]))
            .unwrap_err()
            .contains("--regions expects"));
        assert!(parse_lint_args(&argv(&["lint", "--interval", "--watch"]))
            .unwrap_err()
            .contains("got flag"));
    }

    #[test]
    fn fix_requires_yes_or_dry_run() {
        // --fix alone is a usage error: it must pick apply (--yes) or
        // preview (--dry-run) explicitly.
        assert!(parse_lint_args(&argv(&["lint", "--fix"]))
            .unwrap_err()
            .contains("requires --yes"));
        // --fix --yes and --fix --dry-run both parse.
        assert!(
            parse_lint_args(&argv(&["lint", "--fix", "--yes"]))
                .unwrap()
                .fix
        );
        assert!(
            parse_lint_args(&argv(&["lint", "--fix", "--dry-run"]))
                .unwrap()
                .dry_run
        );
        // ...but not both at once.
        assert!(
            parse_lint_args(&argv(&["lint", "--fix", "--yes", "--dry-run"]))
                .unwrap_err()
                .contains("mutually exclusive")
        );
    }

    #[test]
    fn mutually_exclusive_mode_combinations_are_rejected() {
        assert!(
            parse_lint_args(&argv(&["lint", "--watch", "--fix", "--yes"]))
                .unwrap_err()
                .contains("--watch and --fix")
        );
        assert!(parse_lint_args(&argv(&[
            "lint",
            "--baseline",
            "b.json",
            "--against-baseline",
            "a.json"
        ]))
        .unwrap_err()
        .contains("mutually exclusive"));
        assert!(
            parse_lint_args(&argv(&["lint", "--baseline", "b.json", "--fix", "--yes"]))
                .unwrap_err()
                .contains("incompatible with --fix")
        );
    }

    #[test]
    fn empty_regions_csv_is_usage_error() {
        let err = parse_lint_args(&argv(&["lint", "--regions", " , "])).unwrap_err();
        assert!(err.contains("--regions list is empty"), "got: {err}");
    }

    #[test]
    fn probe_live_flag_parses() {
        let p = parse_lint_args(&argv(&["lint", "--probe-live"])).unwrap();
        assert!(p.probe_live);
        let p = parse_lint_args(&argv(&["lint"])).unwrap();
        assert!(!p.probe_live);
    }

    #[test]
    fn webhook_requires_watch_and_a_real_url() {
        let p = parse_lint_args(&argv(&[
            "lint",
            "--watch",
            "--webhook",
            "https://hooks.example/x",
        ]))
        .unwrap();
        assert_eq!(p.webhook.as_deref(), Some("https://hooks.example/x"));
        // Without --watch: usage error (one-shot runs print findings).
        let err =
            parse_lint_args(&argv(&["lint", "--webhook", "https://hooks.example/x"])).unwrap_err();
        assert!(err.contains("--watch"), "got: {err}");
        // Value-flag trap: a following flag is not a URL.
        let err = parse_lint_args(&argv(&["lint", "--watch", "--webhook", "--json"])).unwrap_err();
        assert!(err.contains("expects a URL"), "got: {err}");
        let err = parse_lint_args(&argv(&["lint", "--watch", "--webhook"])).unwrap_err();
        assert!(err.contains("expects a URL"), "got: {err}");
    }

    #[test]
    fn run_rules_for_env_wires_inputs_through_the_context() {
        // EBL017 fires on a bare env (managed actions absent) —
        // proves the shared builder produces a working context.
        let env = aws::Environment {
            name: "prod".into(),
            application: "shop".into(),
            status: "Ready".into(),
            health: "Green".into(),
            platform: "Node.js 20".into(),
            solution_stack: String::new(),
            tier: "Web".into(),
            cname: "prod.example.com".into(),
            version_label: "b1".into(),
            arn: None,
            updated: Some(chrono::Utc::now()),
            id: None,
            region: None,
        };
        let rules = lint::default_rules(&[]);
        let bare = EnvLintInputs::bare(vec![]);
        let issues = run_rules_for_env(&rules, &env, &bare, &[]);
        assert!(issues.iter().any(|i| i.rule_id == "EBL017"));
        // Probe inputs reach EBL016 / EBL018 through the same path
        // (the env is prod-named, so the WAF signal fires).
        let probed = EnvLintInputs {
            probe_failure: Some("HTTP 503".into()),
            waf_missing: Some(true),
            ..EnvLintInputs::bare(vec![])
        };
        let issues = run_rules_for_env(&rules, &env, &probed, &[]);
        assert!(issues.iter().any(|i| i.rule_id == "EBL016"));
        assert!(issues.iter().any(|i| i.rule_id == "EBL018"));
    }

    #[test]
    fn webhook_summary_caps_and_handles_all_clear() {
        assert!(webhook_summary(&[]).contains("clean"));
        let mk = |n: usize| lint::Issue {
            rule_id: format!("EBL00{n}"),
            severity: lint::Severity::Warn,
            env_name: Some(format!("env-{n}")),
            title: format!("issue {n}"),
            detail: String::new(),
            suggestion: None,
            fields: Default::default(),
        };
        let issues: Vec<lint::Issue> = (1..=7).map(mk).collect();
        let s = webhook_summary(&issues);
        assert!(s.starts_with("lint: 7 issue(s)"), "got: {s}");
        assert!(s.contains("EBL001 env-1: issue 1"), "got: {s}");
        assert!(s.contains("…and 2 more"), "got: {s}");
        assert!(!s.contains("issue 6"), "cap at 5, got: {s}");
    }
}

#[cfg(test)]
mod probe_outcome_tests {
    use crate::lint::inputs::ProbeOutcome;

    #[test]
    fn a_failed_probe_is_not_a_clean_result() {
        // The whole point. `Option<bool>` collapsed "the rule doesn't
        // apply" and "IAM denied the probe" into the same `None`, so
        // `ebman lint --json` — a CI gate — reported a clean bill of
        // health for a check that never ran.
        let denied = ProbeOutcome::Unknown("SimulatePrincipalPolicy failed: AccessDenied".into());
        assert_eq!(denied.verdict(), None, "the rule still skips");
        let warn = denied
            .coverage_warning("EBL020", "api-prod")
            .expect("an unrunnable check must say so");
        assert!(
            warn.contains("EBL020") && warn.contains("api-prod"),
            "{warn}"
        );
        assert!(
            warn.contains("NOT a clean result"),
            "the wording has to leave no room for reading it as a pass: {warn}"
        );
    }

    #[test]
    fn not_applicable_stays_silent() {
        // X-Ray off, no instance profile, not a prod ALB — a genuine
        // skip. Warning on these would train the operator to ignore the
        // warnings that matter.
        let na = ProbeOutcome::NotApplicable;
        assert_eq!(na.verdict(), None);
        assert_eq!(na.coverage_warning("EBL020", "api-prod"), None);
    }

    #[test]
    fn a_checked_probe_reports_its_verdict_and_warns_about_nothing() {
        assert_eq!(ProbeOutcome::Checked(true).verdict(), Some(true));
        assert_eq!(ProbeOutcome::Checked(false).verdict(), Some(false));
        assert_eq!(
            ProbeOutcome::Checked(false).coverage_warning("EBL018", "api-prod"),
            None
        );
    }

    #[test]
    fn the_three_outcomes_are_distinguishable() {
        // If two of them ever compared equal the distinction would be
        // decorative — which is what `Option<bool>` was.
        assert_ne!(ProbeOutcome::NotApplicable, ProbeOutcome::Checked(false));
        assert_ne!(
            ProbeOutcome::NotApplicable,
            ProbeOutcome::Unknown("x".into())
        );
        assert_ne!(
            ProbeOutcome::Checked(false),
            ProbeOutcome::Unknown("x".into())
        );
    }
}

#[cfg(test)]
mod disabled_rule_probes {
    use crate::lint::inputs::ProbeOutcome;

    /// A disabled rule must not produce a coverage warning.
    ///
    /// The panel's blocker: once a failed probe started marking the run
    /// degraded (exit 1), a rule the operator had switched off via
    /// `lint.disable` could still redden the pipeline — and the only
    /// remedy was changing IAM, because the documented escape hatch
    /// didn't reach the probe. `fetch_env_lint_inputs` takes the
    /// disabled list now and skips the probe entirely, which also stops
    /// paying for the IAM/WAF calls.
    #[test]
    fn a_disabled_rule_yields_no_coverage_warning() {
        // What a skipped probe returns, and what that means downstream.
        let skipped = ProbeOutcome::NotApplicable;
        assert_eq!(skipped.coverage_warning("EBL018", "api-prod"), None);
        assert_eq!(skipped.verdict(), None);

        // Contrast: an ENABLED rule whose probe failed still warns, and
        // still degrades the run. Collapsing these two would put the
        // original false-green bug straight back.
        let failed = ProbeOutcome::Unknown("GetWebACLForResource: AccessDenied".into());
        assert!(failed.coverage_warning("EBL018", "api-prod").is_some());
    }
}

#[cfg(test)]
mod disabled_rule_wiring {
    use crate::lint::inputs::ProbeOutcome;

    fn env() -> crate::aws::Environment {
        crate::aws::Environment {
            name: "api-prod".into(),
            application: "poly".into(),
            status: "Ready".into(),
            health: "Green".into(),
            platform: "Java 17".into(),
            solution_stack: "64bit Amazon Linux 2023 running Corretto 17".into(),
            tier: "Web".into(),
            cname: String::new(),
            version_label: "build-1".into(),
            arn: None,
            updated: None,
            id: None,
            region: None,
        }
    }

    /// A disabled rule's probe returns before touching AWS.
    ///
    /// The panel's blocker: a rule switched off via `lint.disable`
    /// could still redden CI, because the probe ran anyway and a failed
    /// probe marks the run degraded (exit 1). The only remedy was
    /// changing IAM — the documented escape hatch didn't reach here.
    ///
    /// Testable because the check lives INSIDE the probe. The earlier
    /// version checked at the call site, which meant reaching it
    /// required `fetch_env_lint_inputs` to get past
    /// `DescribeConfigurationSettings` first — which a stub client
    /// cannot — so that test was vacuous and said so in its own comment.
    #[tokio::test]
    async fn a_disabled_rules_probe_does_not_run() {
        let aws = crate::aws::AwsClient::stub();
        // Options that WOULD make the X-Ray probe fire: X-Ray on, with
        // an instance profile to look up.
        let options = vec![
            (
                "aws:elasticbeanstalk:xray".to_string(),
                "XRayEnabled".to_string(),
                "true".to_string(),
            ),
            (
                "aws:autoscaling:launchconfiguration".to_string(),
                "IamInstanceProfile".to_string(),
                "eb-ec2-role".to_string(),
            ),
            // ...and what makes the WAF probe fire: an ALB. Without
            // this the WAF probe returns NotApplicable for its OWN
            // reason, so removing the opt-out changed nothing and the
            // assertion below passed either way.
            (
                "aws:elasticbeanstalk:environment".to_string(),
                "LoadBalancerType".to_string(),
                "application".to_string(),
            ),
        ];

        // Disabled: NotApplicable, without an AWS call.
        assert_eq!(
            crate::lint::inputs::probe_xray_trace_denied(&aws, &options, &["EBL020".to_string()])
                .await,
            ProbeOutcome::NotApplicable
        );
        assert_eq!(
            crate::lint::inputs::probe_waf_missing(&aws, &env(), &options, &["EBL018".to_string()])
                .await,
            ProbeOutcome::NotApplicable
        );

        // Enabled: the probe runs and the stub fails it, which must
        // report Unknown — NOT a clean skip. Collapsing these two puts
        // the original false-green bug straight back.
        let enabled = crate::lint::inputs::probe_xray_trace_denied(&aws, &options, &[]).await;
        assert!(
            matches!(enabled, ProbeOutcome::Unknown(_)),
            "an enabled probe that cannot run must say so, got {enabled:?}"
        );
    }
}

/// When a failed EBL010/EBL012 input fetch is lost COVERAGE, and so
/// must be reported, versus a check that could never have fired.
#[cfg(test)]
mod lost_coverage {
    use crate::lint::inputs::{ebl010_could_fire, ebl012_could_fire};

    fn env(status: &str, health: &str) -> crate::aws::Environment {
        crate::aws::Environment {
            name: "api-prod".into(),
            application: "poly".into(),
            status: status.into(),
            health: health.into(),
            platform: "Java 17".into(),
            solution_stack: "64bit Amazon Linux 2023 running Corretto 17".into(),
            tier: "Web".into(),
            cname: String::new(),
            version_label: "build-1".into(),
            arn: None,
            updated: None,
            id: None,
            region: None,
        }
    }

    fn system_type(v: &str) -> Vec<(String, String, String)> {
        vec![(
            "aws:elasticbeanstalk:healthreporting:system".into(),
            "SystemType".into(),
            v.into(),
        )]
    }

    #[test]
    fn ebl010_is_lost_only_when_enabled_with_required_tags() {
        let tags = vec!["owner".to_string()];
        assert!(ebl010_could_fire(&[], &tags));
        assert!(!ebl010_could_fire(&["EBL010".into()], &tags), "disabled");
        assert!(
            !ebl010_could_fire(&[], &[]),
            "no required tags: nothing to check"
        );
    }

    #[test]
    fn ebl012_is_lost_on_a_ready_green_enhanced_env() {
        let enhanced = system_type("enhanced");
        assert!(ebl012_could_fire(&[], &env("Ready", "Green"), &enhanced));
        assert!(
            ebl012_could_fire(&[], &env("Ready", "Ok"), &enhanced),
            "Ok is Green"
        );
        // No SystemType reported at all: not known to be basic, so a
        // failure still counts.
        assert!(ebl012_could_fire(&[], &env("Ready", "Green"), &[]));
    }

    /// The false alarm this guards against: `DescribeEnvironmentHealth`
    /// is unavailable on basic health by design, so every basic-health
    /// env would otherwise degrade every run.
    #[test]
    fn ebl012_is_not_lost_on_basic_health() {
        for v in ["basic", "Basic", "BASIC"] {
            assert!(
                !ebl012_could_fire(&[], &env("Ready", "Green"), &system_type(v)),
                "{v}"
            );
        }
    }

    /// Outside the rule's own preconditions it could not have fired.
    #[test]
    fn ebl012_is_not_lost_when_the_rule_could_not_apply() {
        let enhanced = system_type("enhanced");
        assert!(!ebl012_could_fire(
            &[],
            &env("Updating", "Green"),
            &enhanced
        ));
        assert!(!ebl012_could_fire(&[], &env("Ready", "Red"), &enhanced));
        assert!(!ebl012_could_fire(
            &["EBL012".into()],
            &env("Ready", "Green"),
            &enhanced
        ));
    }
}

/// `env_not_found_anywhere`, shared by `lint` and `drift`.
#[cfg(test)]
mod env_not_found {
    use super::env_not_found_anywhere as f;

    #[test]
    fn a_name_found_nowhere_across_answering_regions_is_an_error() {
        let msg = f(Some("typo-env"), 3, false, true).expect("usage error");
        assert!(
            msg.contains("typo-env") && msg.contains("3 regions"),
            "{msg}"
        );
    }

    #[test]
    fn found_anywhere_is_not_an_error() {
        assert!(f(Some("real"), 3, true, true).is_none());
    }

    #[test]
    fn a_region_that_did_not_answer_withholds_the_verdict() {
        assert!(f(Some("maybe"), 3, false, false).is_none());
    }

    /// One region reports its usage error inside the loop; this must not
    /// report a second one.
    #[test]
    fn a_single_region_run_is_left_to_the_loop() {
        assert!(f(Some("typo"), 1, false, true).is_none());
    }

    #[test]
    fn no_env_asked_for_is_never_an_error() {
        assert!(f(None, 3, false, true).is_none());
    }
}

#[cfg(test)]
mod degrade_guard {
    /// Every degrade must go through `degrade`, so that printing the
    /// reason, keeping it for `--json`, and setting the flag cannot come
    /// apart again.
    ///
    /// They were three separate statements and two kept getting missed:
    /// all four sites gated the message on `!quiet` while still setting
    /// the flag, giving a non-zero exit with an empty log, and none
    /// reached the JSON payload. Consolidating fixed today's four; this
    /// stops the fifth being written the old way.
    ///
    /// Two things about HOW it scans, both learned the hard way in this
    /// codebase. The needle is assembled from fragments rather than
    /// written as one literal, because a guard whose own source contains
    /// what it searches for finds itself — the first version of this
    /// test failed with three matches, all of them its own doc comment,
    /// scan line and failure message. And it stops at the test module,
    /// so a future test that quotes the pattern cannot trip it either.
    #[test]
    fn every_degrade_goes_through_the_helper() {
        // Production source only. Was `src.find("#[cfg(test)]")` and a
        // prefix slice — which truncates at the first INLINE
        // `#[cfg(test)]` item, not at the test module, and so reported
        // clean over whatever followed. `production_half` excises test
        // modules wherever they appear and keeps the rest.
        let prod = crate::app::tests::scan::production_source("cli/lint.rs");
        let prod = prod.as_str();
        // A fetch failure that prints and returns is invisible to the
        // check below.
        //
        // That check asks whether every site which DEGRADES uses the
        // helper. It cannot ask whether every site that SHOULD degrade
        // does — and one did not: the EBL015 account-pass arm printed
        // `warning: EBL015 skipped` behind `!quiet` and left the cycle
        // looking clean, so the run exited 0, `--baseline` would have
        // snapshotted it, and `--quiet` suppressed the only evidence.
        //
        // This looks for the shape: a `warning: ... skipped` written
        // straight to stderr rather than through `degrade`, which
        // prints that prefix itself. Crude — it cannot know which
        // failures are load-bearing — but it catches the one that
        // happened, which is this repo's standard for a guard.
        // By STATEMENT, not by line. The line version matched
        // `eprintln!("warning:` and `skipped` on one line — which is
        // how the EBL015 instance happened to be written, and is NOT
        // how rustfmt writes one. A hundred-character warning wraps,
        // the two needles land on different lines, and the guard sees
        // nothing. The EBL008 twin sat 45 lines from the fixed site,
        // in this shape, through the release that claimed to close it.
        let lines: Vec<&str> = prod.lines().collect();
        for (i, line) in lines.iter().enumerate() {
            let stripped = crate::app::tests::scan::strip_line_comment(line);
            if !stripped.contains("eprintln!(") {
                continue;
            }
            let mut stmt = String::new();
            for l in lines.iter().skip(i).take(6) {
                stmt.push_str(crate::app::tests::scan::strip_line_comment(l));
                if crate::app::tests::scan::strip_line_comment(l)
                    .trim_end()
                    .ends_with(';')
                {
                    break;
                }
            }
            if stmt.contains("warning:") && stmt.contains("skipped") {
                panic!(
                    "line {}: a skipped fetch is printed directly rather than passed \
                     to `degrade`, so the cycle still reports clean and --baseline \
                     will snapshot it: {}",
                    i + 1,
                    stmt.trim()
                );
            }
        }

        // The degraded state must stay DERIVED, never stored.
        //
        // This used to check that the helper set a flag, and that
        // nothing assigned that flag directly — policing a drift that
        // could still happen, because the flag and the reason were two
        // things. They are one thing now: `degraded()` reads the
        // reasons, so a cycle cannot be degraded without saying why,
        // and cannot say why without being degraded. Reintroducing a
        // stored flag is what this guards.
        // Scoped to the STRUCT. `lint_exit_code` takes a `degraded:
        // bool` parameter, which is fine — it is told the answer. What
        // must not exist is a field storing it next to the reasons.
        let decl = prod
            .split("pub(crate) struct CycleReport {")
            .nth(1)
            .and_then(|r| r.split('}').next())
            .expect("CycleReport is declared here");
        // Comments stripped: a field's own doc comment says "Distinct
        // from degraded", and a raw search reads that as the field it
        // forbids. Third time this week a source guard has matched
        // prose — `strip_line_comment` exists for exactly this and
        // handles a `//` inside a string literal, which hand-rolled
        // strippers here did not.
        let decl: String = decl
            .lines()
            .map(crate::app::tests::scan::strip_line_comment)
            .collect::<Vec<_>>()
            .join("\n");
        assert!(
            !decl.contains("degraded"),
            "the degraded state must be DERIVED from `degrade_reasons`, not stored \
             beside them — a stored flag can disagree with the reasons, which is how \
             a run exited non-zero with an empty log: {decl}"
        );
        let derived = prod
            .split("fn degraded(&self) -> bool {")
            .nth(1)
            .expect("`CycleReport::degraded` must exist");
        assert!(
            derived[..derived.find("\n    }").unwrap_or(derived.len())]
                .contains("degrade_reasons.is_empty()"),
            "`degraded()` must read the reasons, or it is a stored flag wearing a \
             method's clothes"
        );

        // And the recorder must still do both halves.
        let helper = prod
            .split("fn degrade(&mut self, reason: String) {")
            .nth(1)
            .expect("`CycleReport::degrade` must exist");
        let body = &helper[..helper.find("\n    }").unwrap_or(helper.len())];
        assert!(body.contains("eprintln!"), "degrade must print the reason");
        assert!(
            body.contains("push(reason)"),
            "degrade must keep the reason for --json"
        );
    }
}

#[cfg(test)]
mod run_decision_tests {
    use super::{baseline_drift, filter_issues, lint_exit_code, watch_sleep};
    use crate::lint;

    // ── mutation-sweep triage, 2026-08-26 ────────────────────────────
    //
    // `run` held 57 of this file's 87 survivors in a single 622-line
    // body, every check written inline against a `println!` or a
    // `std::process::exit`. These cover the two decisions worth pulling
    // out of it first: which issues reach the operator, and what the
    // process exits with.

    // ── baseline drift ────────────────────────────────────────────────

    fn drift_issue(rule: &str, env: Option<&str>) -> lint::Issue {
        lint::Issue {
            rule_id: rule.into(),
            severity: lint::Severity::Warn,
            env_name: env.map(str::to_string),
            title: format!("{rule} fired"),
            detail: String::new(),
            suggestion: None,
            fields: Default::default(),
        }
    }

    /// Build the baseline entry that `issue` would have produced, so the
    /// test compares production identities rather than a string the test
    /// made up.
    fn as_baseline(issue: &lint::Issue) -> lint::BaselineIssue {
        lint::BaselineIssue {
            identity: lint::issue_identity(issue),
            rule_id: issue.rule_id.clone(),
            env_name: issue.env_name.clone(),
            title: issue.title.clone(),
        }
    }

    #[test]
    fn drift_splits_issues_into_new_and_cleared_and_ignores_the_stable_ones() {
        let stable = drift_issue("EBL001", Some("api-prod"));
        let appeared = drift_issue("EBL002", Some("api-prod"));
        let gone = drift_issue("EBL003", Some("api-prod"));

        let current = vec![stable.clone(), appeared.clone()];
        let baseline = vec![as_baseline(&stable), as_baseline(&gone)];

        let d = baseline_drift(&current, &baseline);

        assert_eq!(
            d.new_issues.iter().map(|i| &i.rule_id).collect::<Vec<_>>(),
            vec!["EBL002"],
            "only the issue absent from the baseline is new"
        );
        assert_eq!(
            d.cleared.iter().map(|b| &b.rule_id).collect::<Vec<_>>(),
            vec!["EBL003"],
            "only the baseline issue that stopped reproducing is cleared"
        );
    }

    #[test]
    fn drift_is_by_identity_so_the_same_rule_on_another_env_is_a_new_issue() {
        // The whole reason the comparison hashes env into the identity:
        // EBL001 on staging must not be excused by EBL001 on prod
        // sitting in the baseline. Comparing rule ids alone would let a
        // fleet-wide regression through a CI gate.
        let prod = drift_issue("EBL001", Some("api-prod"));
        let staging = drift_issue("EBL001", Some("api-staging"));

        let baseline = [as_baseline(&prod)];
        let d = baseline_drift(std::slice::from_ref(&staging), &baseline);

        assert_eq!(d.new_issues.len(), 1, "same rule, different env, is new");
        assert_eq!(d.new_issues[0].env_name.as_deref(), Some("api-staging"));
        assert_eq!(d.cleared.len(), 1, "and prod's issue reads as cleared");
    }

    #[test]
    fn drift_on_an_unchanged_fleet_is_empty_both_ways() {
        let a = drift_issue("EBL001", Some("api-prod"));
        let b = drift_issue("EBL002", None);
        let baseline = vec![as_baseline(&a), as_baseline(&b)];

        let current = [a.clone(), b.clone()];
        let d = baseline_drift(&current, &baseline);

        assert!(d.new_issues.is_empty() && d.cleared.is_empty());
        assert_eq!(d.baseline_count, 2, "both baseline issues counted stable");
    }

    #[test]
    fn drift_against_an_empty_baseline_makes_every_issue_new() {
        // The first `--baseline` run against a fresh file: everything is
        // new, nothing is cleared, and the stable count is zero.
        let issues = vec![
            drift_issue("EBL001", Some("a")),
            drift_issue("EBL002", Some("b")),
        ];
        let d = baseline_drift(&issues, &[]);
        assert_eq!(d.new_issues.len(), 2);
        assert!(d.cleared.is_empty());
        assert_eq!(d.baseline_count, 0);
    }

    #[test]
    fn drift_on_a_now_clean_fleet_clears_the_whole_baseline() {
        let was = drift_issue("EBL001", Some("api-prod"));
        let baseline = [as_baseline(&was)];
        let d = baseline_drift(&[], &baseline);
        assert!(d.new_issues.is_empty(), "nothing fires, so nothing is new");
        assert_eq!(d.cleared.len(), 1);
    }

    #[test]
    fn baseline_count_deduplicates_repeated_identities() {
        // A baseline file that lists the same issue twice describes one
        // issue; "2 issues stable" would be a lie to the operator.
        let a = drift_issue("EBL001", Some("api-prod"));
        let baseline = vec![as_baseline(&a), as_baseline(&a)];
        let d = baseline_drift(std::slice::from_ref(&a), &baseline);
        assert_eq!(d.baseline_count, 1);
    }

    // ── watch interval ────────────────────────────────────────────────

    #[test]
    fn watch_sleep_subtracts_the_cycle_so_the_interval_is_start_to_start() {
        let s = watch_sleep(60, chrono::Duration::seconds(20));
        assert_eq!(
            s,
            std::time::Duration::from_secs(40),
            "a 20s cycle in a 60s interval sleeps 40s, not 60s"
        );
    }

    #[test]
    fn watch_sleep_floors_at_zero_when_a_cycle_overruns_its_interval() {
        // A fleet scan slower than the interval must start the next
        // cycle immediately, not underflow.
        let s = watch_sleep(30, chrono::Duration::seconds(45));
        assert_eq!(s, std::time::Duration::ZERO);
    }

    #[test]
    fn watch_sleep_treats_a_backwards_clock_as_no_time_passed() {
        // NTP step or suspend/resume can make `now - started` negative.
        // `to_std()` fails on a negative duration and the fallback is a
        // full interval — the safe direction, since the alternative is a
        // hot loop hammering the AWS API.
        let s = watch_sleep(60, chrono::Duration::seconds(-5));
        assert_eq!(s, std::time::Duration::from_secs(60));
    }

    fn issue(rule: &str, sev: lint::Severity) -> lint::Issue {
        lint::Issue {
            rule_id: rule.into(),
            severity: sev,
            env_name: Some("api-prod".into()),
            title: format!("{rule} fired"),
            detail: String::new(),
            suggestion: None,
            fields: Default::default(),
        }
    }

    fn ids(issues: &[lint::Issue]) -> Vec<&str> {
        issues.iter().map(|i| i.rule_id.as_str()).collect()
    }

    #[test]
    fn min_severity_keeps_that_level_and_above() {
        let all = || {
            vec![
                issue("EBL001", lint::Severity::Info),
                issue("EBL002", lint::Severity::Warn),
                issue("EBL003", lint::Severity::Error),
            ]
        };

        // No filter → everything. Without this, "drop everything"
        // passes every case below.
        let mut v = all();
        filter_issues(&mut v, None, &[]);
        assert_eq!(ids(&v), ["EBL001", "EBL002", "EBL003"]);

        // `>= min`, so the named level is INCLUDED — the boundary is the
        // whole point of the flag, and `>` would silently drop exactly
        // the severity the operator asked for.
        let mut v = all();
        filter_issues(&mut v, Some(lint::Severity::Warn), &[]);
        assert_eq!(ids(&v), ["EBL002", "EBL003"], "warn keeps warn and error");

        let mut v = all();
        filter_issues(&mut v, Some(lint::Severity::Error), &[]);
        assert_eq!(ids(&v), ["EBL003"]);

        let mut v = all();
        filter_issues(&mut v, Some(lint::Severity::Info), &[]);
        assert_eq!(ids(&v), ["EBL001", "EBL002", "EBL003"], "info keeps all");
    }

    #[test]
    fn an_empty_rule_filter_is_no_filter_at_all() {
        let all = || {
            vec![
                issue("EBL001", lint::Severity::Warn),
                issue("EBL002", lint::Severity::Warn),
            ]
        };

        // The `!rule_filter.is_empty()` guard: without it, an empty
        // `--rule` would match nothing and report a clean fleet.
        let mut v = all();
        filter_issues(&mut v, None, &[]);
        assert_eq!(ids(&v), ["EBL001", "EBL002"], "no --rule means no filter");

        let mut v = all();
        filter_issues(&mut v, None, &["EBL002".to_string()]);
        assert_eq!(ids(&v), ["EBL002"]);

        let mut v = all();
        filter_issues(&mut v, None, &["EBL999".to_string()]);
        assert!(v.is_empty(), "an unmatched rule filter reports nothing");
    }

    #[test]
    fn the_two_filters_compose() {
        let mut v = vec![
            issue("EBL001", lint::Severity::Info),
            issue("EBL002", lint::Severity::Error),
            issue("EBL003", lint::Severity::Error),
        ];
        filter_issues(
            &mut v,
            Some(lint::Severity::Warn),
            &["EBL001".to_string(), "EBL002".to_string()],
        );
        assert_eq!(
            ids(&v),
            ["EBL002"],
            "an issue has to survive BOTH filters, not either"
        );
    }

    /// The exit-code matrix from `docs/headless.md`. This is what gates
    /// CI, so every cell is named.
    #[test]
    fn the_exit_code_matrix_holds() {
        // fix, fix_failed, degraded, clean → code
        for (fix, failed, degraded, clean, want, why) in [
            (false, false, false, true, 0, "clean run passes"),
            (false, false, false, false, 3, "issues found is exit 3"),
            (
                false,
                false,
                true,
                true,
                1,
                "clean but degraded must NOT pass green — a region skipped on \
                 expired credentials looks identical to a passing check",
            ),
            (
                false,
                false,
                true,
                false,
                3,
                "issues found beats degraded: exit 3 is the actionable one",
            ),
            (
                true,
                false,
                false,
                false,
                0,
                "--fix that dispatched cleanly passes",
            ),
            (
                true,
                true,
                false,
                false,
                1,
                "--fix with a failed dispatch is exit 1",
            ),
            (
                true,
                false,
                true,
                false,
                1,
                "--fix on a degraded run is exit 1",
            ),
            (
                true,
                false,
                false,
                true,
                0,
                "--fix reports on the dispatch, not on cleanliness",
            ),
        ] {
            assert_eq!(
                lint_exit_code(fix, failed, degraded, clean),
                want,
                "fix={fix} failed={failed} degraded={degraded} clean={clean}: {why}"
            );
        }
    }
}

#[cfg(test)]
mod webhook_gate_tests {
    use super::{fix_may_dispatch, should_post_webhook, should_run_account_pass};
    use std::collections::BTreeSet;

    fn set(items: &[&str]) -> BTreeSet<String> {
        items.iter().map(|s| s.to_string()).collect()
    }

    /// `lint --watch --webhook` posts on a CHANGE, and only on a change.
    ///
    /// Both halves of this condition survived the sweep, and each has a
    /// pager consequence: re-posting an unchanged set fires every
    /// interval until someone mutes it, and dropping the
    /// first-cycle-clean test pages "all clear" at an operator who never
    /// had an alert.
    #[test]
    fn the_watch_webhook_posts_only_on_a_change() {
        // First cycle with findings → post. This is the "first findings"
        // case the guard deliberately allows.
        assert!(should_post_webhook(None, &set(&["EBL001:api-prod"])));

        // First cycle already clean → nothing. An all-clear body claims
        // issues cleared, and none did.
        assert!(
            !should_post_webhook(None, &set(&[])),
            "a first cycle that is already clean has nothing to report"
        );

        // Unchanged between cycles → nothing, however many cycles pass.
        let seen = set(&["EBL001:api-prod"]);
        assert!(
            !should_post_webhook(Some(&seen), &seen),
            "an unchanged finding set must not re-post every interval"
        );

        // Changed → post, in both directions.
        assert!(
            should_post_webhook(Some(&seen), &set(&["EBL001:api-prod", "EBL002:worker"])),
            "a new finding is a change"
        );
        assert!(
            should_post_webhook(Some(&seen), &set(&[])),
            "going clean after findings IS worth an all-clear"
        );
        assert!(
            should_post_webhook(Some(&set(&[])), &seen),
            "and findings after a known-clean cycle"
        );

        // A different set of the same size still counts as a change.
        assert!(should_post_webhook(Some(&seen), &set(&["EBL009:other"])));
    }

    /// `lint --fix` must not dispatch without `--yes`.
    ///
    /// This is a write gate — it guards `update_env_option_settings`
    /// against a live account. It sat inline in a 622-line async body
    /// where nothing could reach it, so dropping the `yes` half made a
    /// preview run write to AWS with the whole suite green.
    #[test]
    fn fix_dispatches_only_with_yes_and_something_to_do() {
        assert!(
            !fix_may_dispatch(false, 3),
            "a preview must never dispatch, however much it planned"
        );
        assert!(
            !fix_may_dispatch(true, 0),
            "nothing planned means no call — an empty write is still a \
             round trip against someone's account"
        );
        assert!(fix_may_dispatch(true, 1), "confirmed, with work to do");
    }

    /// The account-level EBL015 pass is skipped when scoped, and when
    /// disabled.
    ///
    /// Both halves survived mutation. Ignoring `lint.disable` runs a
    /// rule the operator turned off; ignoring the scope reports
    /// account-wide platforms on a run about one environment, and costs
    /// a `ListPlatformVersions` call every time.
    #[test]
    fn the_account_pass_respects_scope_and_disables() {
        let none: Vec<String> = vec![];
        let off = vec!["EBL015".to_string()];

        assert!(
            should_run_account_pass(false, &none),
            "fleet-wide run with the rule enabled"
        );
        assert!(
            !should_run_account_pass(true, &none),
            "a run scoped to one env must not report account-wide findings"
        );
        assert!(
            !should_run_account_pass(false, &off),
            "a disabled rule must stay disabled here too"
        );
        assert!(!should_run_account_pass(true, &off), "and both together");

        // A different disabled rule must not suppress this one.
        assert!(
            should_run_account_pass(false, &["EBL001".to_string()]),
            "disabling a sibling rule must not disable EBL015"
        );
    }

    /// Both extracted gates must be WIRED into `run`.
    ///
    /// Neither call site is reachable from a test — that is why the
    /// decisions sat there unguarded in the first place — so the helper
    /// tests above prove nothing about production on their own.
    ///
    /// The scan is bounded to the code BEFORE the first `#[cfg(test)]`,
    /// following this file's own precedent. Without that bound it would
    /// match the literals in these very tests, and a textual mutation
    /// that rewrote the call site would rewrite the needle too and keep
    /// passing — which happened to a sibling guard earlier and read as
    /// a clean result.
    #[test]
    fn the_extracted_gates_are_wired_into_run() {
        let prod = crate::app::tests::scan::production_source("cli/lint.rs");

        assert!(
            prod.contains("fix_may_dispatch(yes, to_set.len())"),
            "the option-write dispatch must go through the tested gate, \
             or `--fix` can write without `--yes` again"
        );
        // Matched without the borrow form. The needle was
        // `(env_name.is_some(), &disabled)` and a clippy fix removing
        // the `&` broke it — a guard coupled to incidental syntax
        // fails for a reason that has nothing to do with what it
        // guards, and the next person reads that as the guard being
        // wrong rather than the code.
        assert!(
            prod.contains("should_run_account_pass(env_name.is_some(),"),
            "the EBL015 account pass must go through the tested gate"
        );
        // Canary: the production slice must be real, or both `contains`
        // above would fail loudly rather than silently — but the
        // negative below would pass on an empty string.
        assert!(
            prod.contains("pub async fn run"),
            "the production slice is not finding `run`"
        );
        assert!(
            !prod.contains("if !to_set.is_empty() && yes {"),
            "the inline gate came back alongside the helper"
        );
    }
}

/// The seam exists to be driven. This drives it.
/// Plan and dispatch `--fix` for one environment. Returns whether a
/// dispatch failed (or a `--yes` run was refused), which is what
/// decides `lint`'s exit code.
///
/// Extracted from `run_cycle` in 0.45. It was ~170 lines inline and
/// the seam's tests could not reach any of it: `run_with` hardcoded
/// `fix = false`, so the refusal accounting and the dispatch-failure
/// flag were exactly as untested after the extraction that was
/// supposed to expose them as before it. `fix_dispatch_failed` was
/// asserted once, as `false`.
#[allow(clippy::too_many_arguments)]
async fn apply_fixes_for_env(
    aws: &aws::AwsClient,
    env: &aws::Environment,
    inputs: &EnvLintInputs,
    issues: &[lint::Issue],
    rules: &[Box<dyn lint::Rule>],
    yes: bool,
    quiet: bool,
    json: bool,
    fix_disabled: &[String],
    safety_cfg: &config::Config,
    active_profile_for_safety: &Option<String>,
) -> bool {
    let mut dispatch_failed = false;
    // Through the shared gate, not `pin_reason` alone.
    // `active_freeze: None` because the freeze is
    // handled once up front for the whole run — a
    // per-env freeze check would print the same refusal
    // N times, and this loop skips the env rather than
    // exiting. Passing it explicitly rather than
    // reaching for `pin_reason` keeps this path on the
    // shared decision even so.
    // A `--dry-run` preview goes through the pure
    // half: it dispatched nothing, so filing
    // `stage=refused` would fill the log with refusals
    // of writes that were never going to happen. Same
    // reasoning the exit-code branch below already
    // applies.
    let refusal = if yes {
        crate::cli::write_refusal(
            safety_cfg,
            &env.name,
            active_profile_for_safety,
            None,
            Some(aws.context.region.as_str()),
            // The label the fix DISPATCH logs, so a
            // refusal correlates with it under `ebman
            // audit --action SetOption`.
            crate::verb::Verb::SetOption.audit_label(),
        )
    } else {
        crate::cli::write_refusal_unaudited(safety_cfg, &env.name, active_profile_for_safety, None)
            .map(|(_, message, _)| message)
    };
    if let Some(reason) = refusal {
        if !quiet {
            eprintln!("ebman lint --fix: {reason}");
        }
        // Only a real (--yes) run treats the refusal as a dispatch
        // failure — a --dry-run preview dispatched nothing and must
        // not exit 1. `return yes`, not `return true`: the extraction
        // first wrote the latter, which would have made a refused
        // preview exit 1. Caught by clippy noticing the assignment it
        // made dead.
        return yes;
    }
    // The client's resolved region, not the `--regions` label: without
    // `--regions` the label was `None`, so every single-region fix was
    // audited as `region=default` — a region that does not exist.
    let region_label = aws.context.region.clone();
    // Rebuild the (cheap, borrowing) context for the
    // fix pass — `run_rules_for_env` consumed its own.
    let ctx = build_lint_context(env, inputs, &safety_cfg.required_tags);
    let mut to_set: Vec<(String, String, String)> = Vec::new();
    let mut planned: Vec<(String, lint::FixAction)> = Vec::new();
    let mut planned_set_indices: Vec<usize> = Vec::new();
    for issue in issues {
        if fix_disabled.contains(&issue.rule_id) {
            if !quiet && !json {
                println!("skip {} ({}): in lint.fix_disable", issue.rule_id, env.name);
            }
            continue;
        }
        let Some(rule) = rules.iter().find(|r| r.id() == issue.rule_id) else {
            continue;
        };
        let Some(action) = rule.fix(&ctx) else {
            if !quiet && !json {
                println!(
                    "no-fix {} ({}): rule has no auto-remediation",
                    issue.rule_id, env.name
                );
            }
            continue;
        };
        if let lint::FixAction::SetOption {
            namespace,
            name,
            value,
            ..
        } = &action
        {
            planned_set_indices.push(planned.len());
            to_set.push((namespace.clone(), name.clone(), value.clone()));
        }
        planned.push((issue.rule_id.clone(), action));
    }
    // Plan lines respect --quiet and stay off stdout
    // under --json (prose interleaved with the JSON
    // document broke every piped consumer).
    if !quiet && !json {
        for (rule_id, action) in &planned {
            match action {
                lint::FixAction::SetOption { description, .. } => {
                    println!("fix {rule_id} ({}): {description}", env.name);
                }
                lint::FixAction::Manual { instructions } => {
                    println!(
                        "fix {rule_id} ({}) MANUAL — operator action required:\n  {instructions}",
                        env.name
                    );
                }
            }
        }
    }
    if fix_may_dispatch(yes, to_set.len()) {
        match aws
            .update_env_option_settings(&env.name, &to_set, &[])
            .await
        {
            Ok(()) => {
                for &idx in &planned_set_indices {
                    let (rule_id, action) = &planned[idx];
                    if let lint::FixAction::SetOption {
                        namespace,
                        name,
                        value,
                        ..
                    } = action
                    {
                        audit::append_lint_fix(
                            &region_label,
                            &env.name,
                            rule_id,
                            namespace,
                            name,
                            value,
                            None,
                        );
                    }
                }
                if !quiet && !json {
                    println!(
                        "ok ({}): applied {} fix(es)",
                        env.name,
                        planned_set_indices.len()
                    );
                }
            }
            Err(e) => {
                eprintln!(
                    "ebman lint --fix: dispatch failed for {} in {region_label}: {e}",
                    env.name
                );
                let err_str = e.to_string();
                for &idx in &planned_set_indices {
                    let (rule_id, action) = &planned[idx];
                    if let lint::FixAction::SetOption {
                        namespace,
                        name,
                        value,
                        ..
                    } = action
                    {
                        audit::append_lint_fix(
                            &region_label,
                            &env.name,
                            rule_id,
                            namespace,
                            name,
                            value,
                            Some(&err_str),
                        );
                    }
                }
                dispatch_failed = true;
            }
        }
    }
    dispatch_failed
}

#[cfg(test)]
mod cycle_wiring {
    use super::*;

    /// Which failure the mock fleet injects. Default: none — a clean
    /// fleet the cycle reads end to end, which is what lets a
    /// `degraded()` assertion discriminate at all.
    #[derive(Default, Clone, Copy)]
    struct MockFaults {
        /// `UpdateEnvironment` is rejected — the shape a `--fix` run
        /// hits when the role can read the fleet and not change it.
        update_rejected: bool,
        /// One custom platform exists and its `DescribePlatformVersion`
        /// is rejected: EBL015 coverage that PARTLY failed.
        platform_date_rejected: bool,
        /// `ListTagsForResource` is rejected: EBL010's input is lost.
        tags_rejected: bool,
        /// `DescribeEnvironmentHealth` is rejected: EBL012's input is lost.
        health_rejected: bool,
        /// `ListAvailableSolutionStacks` is rejected: EBL008's input is lost.
        stacks_rejected: bool,
        /// `DescribeEnvironments` is rejected: the region does not answer.
        listing_rejected: bool,
    }

    /// The branch whose platform dates the mock refuses to report.
    const FAULTED_BRANCH: &str = "Node.js 20 running on 64bit Amazon Linux 2023";

    /// Like `mock_client`, but `UpdateEnvironment` is rejected — the
    /// shape a `--fix` run hits when the role can read the fleet and
    /// not change it.
    fn client_with_failing_update(envs: Vec<String>) -> aws::AwsClient {
        mock_client_inner(
            envs,
            MockFaults {
                update_rejected: true,
                ..MockFaults::default()
            },
        )
    }

    /// A fleet with one custom platform whose `DescribePlatformVersion`
    /// fails. Everything else answers, so a degraded cycle here can
    /// only have come from the EBL015 probe.
    fn client_with_failing_platform_date(envs: Vec<String>) -> aws::AwsClient {
        mock_client_inner(
            envs,
            MockFaults {
                platform_date_rejected: true,
                ..MockFaults::default()
            },
        )
    }

    fn mock_client(envs: Vec<String>) -> aws::AwsClient {
        mock_client_inner(envs, MockFaults::default())
    }

    fn mock_client_inner(envs: Vec<String>, faults: MockFaults) -> aws::AwsClient {
        let failing_update = faults.update_rejected;
        use aws_sdk_elasticbeanstalk::operation::describe_environments::DescribeEnvironmentsOutput;
        use aws_sdk_elasticbeanstalk::types::EnvironmentDescription;
        let listing_rejected = faults.listing_rejected;
        let listing =
            aws_smithy_mocks::mock!(aws_sdk_elasticbeanstalk::Client::describe_environments)
                .match_requests(move |_| !listing_rejected)
                .then_output(move || {
                    let mut b = DescribeEnvironmentsOutput::builder();
                    for e in &envs {
                        b = b.environments(
                            EnvironmentDescription::builder()
                                .environment_name(e)
                                .environment_arn(format!(
                            "arn:aws:elasticbeanstalk:us-west-1:123456789012:environment/poly/{e}"
                        ))
                                .application_name("poly")
                                // A versioned platform, so EBL008 applies
                                // and a failed stack listing costs it.
                                .solution_stack_name(
                                    "64bit Amazon Linux 2023 v4.1.0 running Corretto 17",
                                )
                                .status("Ready".into())
                                .health("Green".into())
                                .build(),
                        );
                    }
                    b.build()
                });
        // The per-region solution-stack fetch is allowed to fail: the
        // cycle skips EBL008 for the region rather than aborting, and
        // that tolerance is part of what this test pins.
        let stacks = if faults.stacks_rejected {
            aws_smithy_mocks::mock!(
                aws_sdk_elasticbeanstalk::Client::list_available_solution_stacks
            )
            .then_error(|| {
                aws_sdk_elasticbeanstalk::operation::list_available_solution_stacks::ListAvailableSolutionStacksError::generic(
                    aws_smithy_types::error::ErrorMetadata::builder()
                        .code("AccessDeniedException")
                        .message("not authorized")
                        .build(),
                )
            })
        } else {
            aws_smithy_mocks::mock!(
                aws_sdk_elasticbeanstalk::Client::list_available_solution_stacks
            )
            .then_output(|| {
                aws_sdk_elasticbeanstalk::operation::list_available_solution_stacks::ListAvailableSolutionStacksOutput::builder().build()
            })
        };
        // With `failing_update`, hand back the option settings EBL001
        // fires on — `AllAtOnce` on a multi-instance env — so the fix
        // pass has something to PLAN and therefore something to
        // dispatch. An empty settings response yields issues with no
        // `SetOption` fix, which reaches the planner and stops there.
        let cfgsettings = aws_smithy_mocks::mock!(
            aws_sdk_elasticbeanstalk::Client::describe_configuration_settings
        )
        .then_output(move || {
            use aws_sdk_elasticbeanstalk::types::{
                ConfigurationOptionSetting, ConfigurationSettingsDescription,
            };
            let mut out = aws_sdk_elasticbeanstalk::operation::describe_configuration_settings::DescribeConfigurationSettingsOutput::builder();
            if failing_update {
                let opt = |ns: &str, name: &str, value: &str| {
                    ConfigurationOptionSetting::builder()
                        .namespace(ns)
                        .option_name(name)
                        .value(value)
                        .build()
                };
                out = out.configuration_settings(
                    ConfigurationSettingsDescription::builder()
                        .option_settings(opt(
                            "aws:elasticbeanstalk:command",
                            "DeploymentPolicy",
                            "AllAtOnce",
                        ))
                        .option_settings(opt("aws:autoscaling:asg", "MaxSize", "4"))
                        .build(),
                );
            }
            out.build()
        });
        let denied = |what: &str| {
            aws_smithy_types::error::ErrorMetadata::builder()
                .code("AccessDeniedException")
                .message(format!("User is not authorized to perform {what}"))
                .build()
        };
        let tags = if faults.tags_rejected {
            aws_smithy_mocks::mock!(aws_sdk_elasticbeanstalk::Client::list_tags_for_resource)
                .then_error(move || {
                    aws_sdk_elasticbeanstalk::operation::list_tags_for_resource::ListTagsForResourceError::generic(
                        denied("elasticbeanstalk:ListTagsForResource"),
                    )
                })
        } else {
            aws_smithy_mocks::mock!(aws_sdk_elasticbeanstalk::Client::list_tags_for_resource)
                .then_output(|| {
                    aws_sdk_elasticbeanstalk::operation::list_tags_for_resource::ListTagsForResourceOutput::builder().build()
                })
        };
        let health = if faults.health_rejected {
            aws_smithy_mocks::mock!(aws_sdk_elasticbeanstalk::Client::describe_environment_health)
                .then_error(move || {
                    aws_sdk_elasticbeanstalk::operation::describe_environment_health::DescribeEnvironmentHealthError::generic(
                        denied("elasticbeanstalk:DescribeEnvironmentHealth"),
                    )
                })
        } else {
            aws_smithy_mocks::mock!(aws_sdk_elasticbeanstalk::Client::describe_environment_health)
                .then_output(|| {
                    aws_sdk_elasticbeanstalk::operation::describe_environment_health::DescribeEnvironmentHealthOutput::builder().build()
                })
        };
        let resources = aws_smithy_mocks::mock!(
            aws_sdk_elasticbeanstalk::Client::describe_environment_resources
        )
        .then_output(|| {
            aws_sdk_elasticbeanstalk::operation::describe_environment_resources::DescribeEnvironmentResourcesOutput::builder().build()
        });
        // The EBL015 account-level pass. An EMPTY list by default, not
        // an error: the error path is the one 0.44 fixed, and a test
        // that always degrades could not tell a degraded cycle from a
        // clean one. Under `platform_date_rejected` it lists one
        // custom platform, so the per-branch date probe below is
        // reached.
        let platform_date_rejected = faults.platform_date_rejected;
        let platforms = aws_smithy_mocks::mock!(
            aws_sdk_elasticbeanstalk::Client::list_platform_versions
        )
        .then_output(move || {
            use aws_sdk_elasticbeanstalk::types::PlatformSummary;
            let mut b = aws_sdk_elasticbeanstalk::operation::list_platform_versions::ListPlatformVersionsOutput::builder();
            if platform_date_rejected {
                b = b.platform_summary_list(
                    PlatformSummary::builder()
                        .platform_arn("arn:aws:elasticbeanstalk:us-west-1:123456789012:platform/custom-node/1.0.0")
                        .platform_branch_name(FAULTED_BRANCH)
                        .platform_version("1.0.0")
                        .build(),
                );
            }
            b.build()
        });
        // EBL015's only source of dates. Rejected, it yields a WARNING
        // rather than an error: the branch is skipped and the rest of
        // the pass continues — which is exactly the partial-coverage
        // case that must still degrade the cycle.
        let platform_date = aws_smithy_mocks::mock!(
            aws_sdk_elasticbeanstalk::Client::describe_platform_version
        )
        .then_error(|| {
            aws_sdk_elasticbeanstalk::operation::describe_platform_version::DescribePlatformVersionError::generic(
                aws_smithy_types::error::ErrorMetadata::builder()
                    .code("AccessDeniedException")
                    .message(
                        "User is not authorized to perform \
                         elasticbeanstalk:DescribePlatformVersion",
                    )
                    .build(),
            )
        });
        let update = aws_smithy_mocks::mock!(
            aws_sdk_elasticbeanstalk::Client::update_environment
        )
        .then_error(|| {
            aws_sdk_elasticbeanstalk::operation::update_environment::UpdateEnvironmentError::generic(
                aws_smithy_types::error::ErrorMetadata::builder()
                    .code("AccessDeniedException")
                    .message("User is not authorized to perform elasticbeanstalk:UpdateEnvironment")
                    .build(),
            )
        });
        let listing_denied =
            aws_smithy_mocks::mock!(aws_sdk_elasticbeanstalk::Client::describe_environments)
                .then_error(|| {
                    aws_sdk_elasticbeanstalk::operation::describe_environments::DescribeEnvironmentsError::generic(
                        aws_smithy_types::error::ErrorMetadata::builder()
                            .code("AccessDeniedException")
                            .message("not authorized")
                            .build(),
                    )
                });
        let mut rules: Vec<&aws_smithy_mocks::Rule> = vec![
            &listing,
            &stacks,
            &cfgsettings,
            &tags,
            &health,
            &resources,
            &platforms,
        ];
        if failing_update {
            rules.push(&update);
        }
        if faults.platform_date_rejected {
            rules.push(&platform_date);
        }
        if faults.listing_rejected {
            rules.push(&listing_denied);
        }
        let eb = aws_smithy_mocks::mock_client!(
            aws_sdk_elasticbeanstalk,
            aws_smithy_mocks::RuleMode::MatchAny,
            rules
        );
        let cfg = aws_config::SdkConfig::builder()
            .region(aws_config::Region::new("us-west-1"))
            .behavior_version(aws_config::BehaviorVersion::latest())
            .build();
        aws::AwsClient::for_tests(
            eb,
            aws_sdk_sqs::Client::new(&cfg),
            aws_sdk_cloudwatch::Client::new(&cfg),
            aws_sdk_cloudwatchlogs::Client::new(&cfg),
            aws_sdk_s3::Client::new(&cfg),
            aws_sdk_ec2::Client::new(&cfg),
        )
    }

    /// The knobs `run_cycle` takes, so a test can set the one it
    /// cares about and leave the rest.
    ///
    /// `run_with` used to hardcode all fourteen arguments — `fix`
    /// false, `env_name` none, default safety config — which meant the
    /// seam's tests drove the region loop and nothing else. The
    /// ~165-line `--fix` block, holding the refusal accounting and the
    /// dispatch-failure flag, was exactly as unreachable as it had
    /// been before the extraction. Named by the pre-0.44 architecture
    /// review.
    #[derive(Default)]
    struct CycleOpts {
        env_name: Option<String>,
        fix: bool,
        yes: bool,
        safety_cfg: config::Config,
        fix_disabled: Vec<String>,
        /// `lint.disable` / `--rules` exclusions.
        disabled: Vec<String>,
    }

    /// A fixed clock, so EBL015's date-dependent staleness threshold
    /// is deterministic.
    fn test_clock() -> chrono::DateTime<chrono::Utc> {
        "2026-09-22T12:00:00Z".parse().expect("a valid instant")
    }

    async fn run_with<F, Fut>(regions: Vec<Option<String>>, client_for: F) -> CycleReport
    where
        F: Fn(Option<String>) -> Fut,
        Fut: std::future::Future<Output = color_eyre::eyre::Result<aws::AwsClient>>,
    {
        run_with_opts(regions, CycleOpts::default(), client_for).await
    }

    async fn run_with_opts<F, Fut>(
        regions: Vec<Option<String>>,
        opts: CycleOpts,
        client_for: F,
    ) -> CycleReport
    where
        F: Fn(Option<String>) -> Fut,
        Fut: std::future::Future<Output = color_eyre::eyre::Result<aws::AwsClient>>,
    {
        run_cycle(
            &regions,
            &opts.env_name,
            &opts.disabled,
            false,
            opts.fix,
            opts.yes,
            true,
            false,
            None,
            &[],
            &opts.safety_cfg,
            &opts.fix_disabled,
            &None,
            client_for,
            test_clock(),
        )
        .await
    }

    /// A `--fix` dispatch that AWS rejects sets `fix_dispatch_failed`,
    /// which is what makes `lint --fix` exit 1.
    ///
    /// The flag existed before 0.45 and was asserted exactly once, as
    /// `false`. `run_with` hardcoded `fix = false`, so the ~170 lines
    /// holding the refusal accounting and this flag were as unreachable
    /// after the extraction meant to expose them as before it. Named by
    /// the pre-0.44 architecture review; this is the test it asked for.
    #[tokio::test]
    async fn a_rejected_fix_dispatch_fails_the_cycle() {
        let report = run_with_opts(
            vec![None],
            CycleOpts {
                fix: true,
                yes: true,
                ..CycleOpts::default()
            },
            |_| async { Ok(client_with_failing_update(vec!["poly-prod-web".into()])) },
        )
        .await;

        assert!(
            report.fix_dispatch_failed,
            "a rejected UpdateEnvironment must fail the cycle, or `lint --fix` \
             exits 0 having changed nothing ({} issues seen)",
            report.issues.len()
        );
        assert!(
            !report.degraded(),
            "the fleet WAS seen — a rejected write is not incomplete coverage: {:?}",
            report.degrade_reasons
        );
    }

    fn with_required_tag() -> config::Config {
        config::Config {
            required_tags: vec!["owner".into()],
            ..config::Config::default()
        }
    }

    /// A rejected tag fetch DEGRADES the cycle when EBL010 could have
    /// fired. `.ok()` used to turn it into a silent skip: exit 0, and
    /// `--baseline` adopted a run whose tag check never happened.
    #[tokio::test]
    async fn a_rejected_tag_fetch_degrades_the_cycle() {
        let report = run_with_opts(
            vec![None],
            CycleOpts {
                safety_cfg: with_required_tag(),
                ..CycleOpts::default()
            },
            |_| async {
                Ok(mock_client_inner(
                    vec!["poly-prod-web".into()],
                    MockFaults {
                        tags_rejected: true,
                        ..MockFaults::default()
                    },
                ))
            },
        )
        .await;
        assert!(
            report
                .degrade_reasons
                .iter()
                .any(|r| r.contains("EBL010") && r.contains("ListTagsForResource")),
            "{:?}",
            report.degrade_reasons
        );
    }

    /// The same for EBL012 and the health fetch, on a Ready/Green env.
    #[tokio::test]
    async fn a_rejected_health_fetch_degrades_the_cycle() {
        let report = run_with(vec![None], |_| async {
            Ok(mock_client_inner(
                vec!["poly-prod-web".into()],
                MockFaults {
                    health_rejected: true,
                    ..MockFaults::default()
                },
            ))
        })
        .await;
        assert!(
            report
                .degrade_reasons
                .iter()
                .any(|r| r.contains("EBL012") && r.contains("DescribeEnvironmentHealth")),
            "{:?}",
            report.degrade_reasons
        );
    }

    fn stacks_rejected() -> aws::AwsClient {
        mock_client_inner(
            // Two envs: one failed listing must still be one line.
            vec!["poly-prod-web".into(), "poly-prod-api".into()],
            MockFaults {
                stacks_rejected: true,
                ..MockFaults::default()
            },
        )
    }

    /// A failed stack listing degrades the cycle — EBL008 did not run.
    #[tokio::test]
    async fn a_failed_stack_listing_degrades_the_cycle() {
        let report = run_with(vec![None], |_| async { Ok(stacks_rejected()) }).await;
        let ebl008: Vec<_> = report
            .degrade_reasons
            .iter()
            .filter(|r| r.contains("EBL008"))
            .collect();
        // Once for the region, naming it — not once per env over the
        // same cause.
        assert_eq!(ebl008.len(), 1, "{:?}", report.degrade_reasons);
        assert!(
            ebl008[0].contains("ListAvailableSolutionStacks") && ebl008[0].contains("region '"),
            "{}",
            ebl008[0]
        );
    }

    /// ...unless EBL008 is disabled, when nothing was lost. A disabled
    /// rule must never redden a run: the operator's documented escape
    /// hatch has to be one.
    #[tokio::test]
    async fn a_failed_stack_listing_does_not_degrade_when_ebl008_is_disabled() {
        let report = run_with_opts(
            vec![None],
            CycleOpts {
                disabled: vec!["EBL008".into()],
                ..CycleOpts::default()
            },
            |_| async { Ok(stacks_rejected()) },
        )
        .await;
        assert!(!report.degraded(), "{:?}", report.degrade_reasons);
    }

    /// EBL015 coverage that PARTLY failed degrades the cycle.
    ///
    /// `fetch_stale_platform_issues` returns per-branch warnings when
    /// `DescribePlatformVersion` fails for a branch: the branch is
    /// skipped, the rest of the pass continues, and the issue set is
    /// therefore not a full picture. Until 0.45 those warnings were
    /// `eprintln!`ed behind `!quiet` and dropped — so a partial EBL015
    /// failure exited 0, the webhook did not page, and `--baseline`
    /// adopted a snapshot whose stale-platform check never ran for
    /// that branch.
    ///
    /// The whole-pass version of this was 0.44's silent-green fix, 20
    /// lines below. The per-branch one beside it was left, with a
    /// comment on the Err arm naming `--quiet` erasing the evidence as
    /// a lesson already learned. Nothing in the suite could see it:
    /// `run_with_opts` passes `quiet: true`, so the print this
    /// replaced never even ran under test.
    ///
    /// The discriminating case is
    /// `a_cycle_where_every_region_answers_is_not_degraded`: the same
    /// `mock_client` with no fault injected, asserting NOT degraded.
    /// Without it this assertion would be satisfied by a `degrade`
    /// that fired unconditionally.
    #[tokio::test]
    async fn a_partly_failed_platform_pass_degrades_the_cycle() {
        let report = run_with(vec![None], |_| async {
            Ok(client_with_failing_platform_date(vec![
                "poly-prod-web".into()
            ]))
        })
        .await;

        assert!(
            report.degraded(),
            "a branch whose DescribePlatformVersion failed is EBL015 coverage that \
             did not happen — a clean exit here lets `--baseline` snapshot it as good"
        );
        assert!(
            report.degrade_reasons.iter().any(|r| {
                r.contains("EBL015 skipped for")
                    && r.contains(FAULTED_BRANCH)
                    && r.contains("DescribePlatformVersion")
            }),
            "the reason must NAME the branch and the call that failed, or the \
             operator cannot tell which coverage is missing: {:?}",
            report.degrade_reasons
        );
    }

    /// A single-region `--fix` is audited under the region it ran in.
    ///
    /// The audit took the `--regions` label, which is `None` without
    /// `--regions`, so every ordinary fix was recorded as
    /// `region=default` — a region that does not exist, on the line an
    /// operator filters by afterwards.
    #[tokio::test]
    async fn a_fix_is_audited_under_the_region_it_ran_in() {
        let env = "lint-fix-region-probe-env";
        let path = crate::util::cache_dir().join("audit.log");
        let before = std::fs::read_to_string(&path).unwrap_or_default();
        run_with_opts(
            vec![None],
            CycleOpts {
                fix: true,
                yes: true,
                ..CycleOpts::default()
            },
            |_| async { Ok(client_with_failing_update(vec![env.into()])) },
        )
        .await;
        let after = std::fs::read_to_string(&path).unwrap_or_default();
        let lines: Vec<&str> = after
            .strip_prefix(&before)
            .expect("the audit log is append-only")
            .lines()
            .filter(|l| l.contains(env))
            .collect();
        assert!(!lines.is_empty(), "the fix attempt is audited");
        // The client's own resolved region, whatever the fixture sets.
        let region = client_with_failing_update(vec![]).context.region.clone();
        for l in &lines {
            assert!(l.contains(&format!("region={region}")), "{l}");
            assert!(!l.contains("region=default"), "{l}");
        }
    }

    /// The same rejection under a preview (no `--yes`) must NOT fail
    /// the cycle: nothing was dispatched.
    #[tokio::test]
    async fn a_preview_never_fails_the_cycle() {
        let report = run_with_opts(
            vec![None],
            CycleOpts {
                fix: true,
                yes: false,
                ..CycleOpts::default()
            },
            |_| async { Ok(client_with_failing_update(vec!["poly-prod-web".into()])) },
        )
        .await;
        assert!(
            !report.fix_dispatch_failed,
            "a preview dispatched nothing and must not exit 1"
        );
    }

    fn read_only_cfg(env: &str) -> config::Config {
        let mut cfg = config::Config::default();
        cfg.safety_envs.insert(env.to_string(), true);
        cfg
    }

    /// A safety-pinned env REFUSES the fix, and the refusal counts as
    /// a dispatch failure only on a real run.
    ///
    /// The pair matters, and one arm alone would not have caught the
    /// bug that prompted it: extracting the fix block turned
    /// `if yes { failed = true }` into an unconditional `return true`,
    /// which would have made a refused PREVIEW exit 1. Clippy noticed
    /// the assignment it made dead; nothing in the suite did, because
    /// no test reached the refusal branch at all.
    #[tokio::test]
    async fn a_refused_fix_fails_the_cycle_only_on_a_real_run() {
        let env = "poly-prod-web";
        for (yes, expect_failed) in [(true, true), (false, false)] {
            let report = run_with_opts(
                vec![None],
                CycleOpts {
                    fix: true,
                    yes,
                    safety_cfg: read_only_cfg(env),
                    ..CycleOpts::default()
                },
                |_| async { Ok(client_with_failing_update(vec![env.to_string()])) },
            )
            .await;
            assert_eq!(
                report.fix_dispatch_failed,
                expect_failed,
                "a refusal with --yes={yes} must {} the cycle",
                if expect_failed { "fail" } else { "not fail" }
            );
        }
    }

    /// `--env NAME` where NAME is not in the only context being
    /// linted is a USAGE error, reported rather than exited.
    ///
    /// Unreachable from a test until 0.45: `run_cycle` called
    /// `exit_after_drain(2)` here, inside the function extracted to
    /// make the cycle testable, so the single most likely
    /// `ebman lint --env X` mistake was the one branch the seam could
    /// not reach. A test that covers a `process::exit` kills the test
    /// binary; there is no version of this assertion that works
    /// without moving the exit out.
    #[tokio::test]
    async fn an_unknown_env_is_a_usage_error_not_an_exit() {
        let report = run_with_opts(
            vec![None],
            CycleOpts {
                env_name: Some("no-such-env".into()),
                ..CycleOpts::default()
            },
            |_| async { Ok(mock_client(vec!["real-env".into()])) },
        )
        .await;

        let msg = report
            .usage_error
            .as_deref()
            .expect("an unknown env must be reported as a usage error");
        assert!(msg.contains("no-such-env"), "{msg}");
        assert!(
            !report.degraded(),
            "a typo is not a degraded cycle — degraded means the fleet was not \
             seen, and it was: {:?}",
            report.degrade_reasons
        );
        assert!(report.issues.is_empty(), "{:?}", report.issues);
    }

    /// Under multi-region, NAME missing from one region is not a usage
    /// error when it lives in another — the sweep keeps looking. This is
    /// what the test it replaces meant to protect; its fixture put the
    /// env in NO region, and so pinned the typo-passes-CI defect instead.
    #[tokio::test]
    async fn an_env_in_another_region_is_not_a_usage_error() {
        let report = run_with_opts(
            vec![Some("eu-west-1".into()), Some("eu-west-2".into())],
            CycleOpts {
                env_name: Some("target-env".into()),
                ..CycleOpts::default()
            },
            |region| async move {
                Ok(match region.as_deref() {
                    Some("eu-west-2") => mock_client(vec!["target-env".into()]),
                    _ => mock_client(vec!["other-env".into()]),
                })
            },
        )
        .await;
        assert!(report.usage_error.is_none(), "{:?}", report.usage_error);
    }

    /// NAME in NO region, with every region answering, is a usage error
    /// — exactly as it is for one region. It used to exit 0 with "No
    /// issues found", so a typo'd env passed a multi-region CI gate.
    #[tokio::test]
    async fn an_env_in_no_region_is_a_usage_error() {
        let report = run_with_opts(
            vec![Some("eu-west-1".into()), Some("eu-west-2".into())],
            CycleOpts {
                env_name: Some("no-such-env".into()),
                ..CycleOpts::default()
            },
            |_| async { Ok(mock_client(vec!["real-env".into()])) },
        )
        .await;
        let msg = report.usage_error.expect("a typo is a usage error");
        assert!(
            msg.contains("no-such-env") && msg.contains("2 regions"),
            "{msg}"
        );
    }

    /// The other way a region fails to answer: its client builds, but
    /// listing its environments is refused. Same verdict.
    #[tokio::test]
    async fn an_env_missing_where_a_region_would_not_list_is_not_a_usage_error() {
        let report = run_with_opts(
            vec![Some("eu-west-1".into()), Some("eu-west-2".into())],
            CycleOpts {
                env_name: Some("maybe-env".into()),
                ..CycleOpts::default()
            },
            |region| async move {
                Ok(match region.as_deref() {
                    Some("eu-west-2") => mock_client_inner(
                        vec![],
                        MockFaults {
                            listing_rejected: true,
                            ..MockFaults::default()
                        },
                    ),
                    _ => mock_client(vec!["other-env".into()]),
                })
            },
        )
        .await;
        assert!(report.usage_error.is_none(), "{:?}", report.usage_error);
        assert!(
            report.degraded(),
            "the region that would not list degrades the run"
        );
    }

    /// ...but not when a region could not be listed: NAME may be there.
    /// The cycle is degraded instead, which already fails the run —
    /// calling it a typo would claim more than was seen.
    #[tokio::test]
    async fn an_env_missing_where_a_region_did_not_answer_is_not_a_usage_error() {
        let report = run_with_opts(
            vec![Some("eu-west-1".into()), Some("eu-west-2".into())],
            CycleOpts {
                env_name: Some("maybe-env".into()),
                ..CycleOpts::default()
            },
            |region| async move {
                match region.as_deref() {
                    Some("eu-west-2") => Err(color_eyre::eyre::eyre!("no credentials")),
                    _ => Ok(mock_client(vec!["other-env".into()])),
                }
            },
        )
        .await;
        assert!(report.usage_error.is_none(), "{:?}", report.usage_error);
        assert!(report.degraded(), "the unanswered region degrades the run");
    }

    /// A region whose client cannot be built degrades the cycle, and
    /// says which region and why.
    ///
    /// This is the wiring the refactor exists to expose. Before it,
    /// the only way to reach this path was to run the binary against
    /// real AWS with broken credentials and read an exit code.
    #[tokio::test]
    async fn a_region_that_will_not_connect_degrades_the_cycle() {
        let report = run_with(vec![Some("eu-west-2".into())], |_| async {
            Err(color_eyre::eyre::eyre!("no credentials"))
        })
        .await;

        assert!(
            report.degraded(),
            "a region that never answered means the issue set is not a full picture"
        );
        assert_eq!(
            report.degrade_reasons.len(),
            1,
            "{:?}",
            report.degrade_reasons
        );
        let reason = &report.degrade_reasons[0];
        assert!(
            reason.contains("eu-west-2"),
            "the reason must name WHICH region: {reason}"
        );
        assert!(
            reason.contains("no credentials"),
            "and carry the cause, or an operator cannot act on it: {reason}"
        );
        assert!(report.issues.is_empty());
        assert!(!report.fix_dispatch_failed, "nothing was dispatched");
    }

    /// One region failing does not abandon the others, and the report
    /// carries both halves.
    #[tokio::test]
    async fn a_partial_outage_reports_both_what_worked_and_what_did_not() {
        let report = run_with(
            vec![Some("eu-west-2".into()), Some("us-east-1".into())],
            |region| async move {
                if region.as_deref() == Some("eu-west-2") {
                    Err(color_eyre::eyre::eyre!("no credentials"))
                } else {
                    Ok(mock_client(vec!["poly-prod".to_string()]))
                }
            },
        )
        .await;

        assert!(
            report.degraded(),
            "a cycle that skipped a region is incomplete even though the other \
             region answered — this is the distinction the whole type exists for"
        );
        assert_eq!(
            report.degrade_reasons.len(),
            1,
            "{:?}",
            report.degrade_reasons
        );
        assert!(report.degrade_reasons[0].contains("eu-west-2"));
        assert!(
            !report.degrade_reasons[0].contains("us-east-1"),
            "the region that worked must not appear as a failure"
        );
    }

    /// A clean cycle is not degraded — or `degraded()` is satisfied by
    /// returning true always.
    #[tokio::test]
    async fn a_cycle_where_every_region_answers_is_not_degraded() {
        let report = run_with(vec![Some("us-east-1".into())], |_| async {
            Ok(mock_client(vec!["poly-prod".to_string()]))
        })
        .await;
        assert!(
            !report.degraded(),
            "every region answered: {:?}",
            report.degrade_reasons
        );
    }
}