autumn-cli 0.10.0

CLI tool for the Autumn web framework
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
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
//! `autumn deploy` — push-button, zero-downtime deploys to a VPS (issue #1607).
//!
//! This slice implements the locally-verifiable spine of the command:
//!
//! - **`check`** runs a preflight (SSH reachability, signing secret, database
//!   URL, and a `migrate check`) and reports pass/fail, exiting non-zero if any
//!   grader fails.
//! - **`plan`** renders the systemd service unit and the ordered zero-downtime
//!   rollout plan as a pure dry-run — it touches nothing remote.
//! - **`up`** performs a REAL deploy: it runs the same preflight as `check`
//!   (aborting before touching the server if anything fails), then drives the
//!   ordered host-prep + first-deploy or zero-downtime cutover sequence against
//!   an injectable executor (the real one shells out to system `ssh`/`scp`), with
//!   auto-rollback of the candidate on a pre-cutover failure. See [`exec`].
//! - **`rollback`** performs a REAL on-demand rollback (Slice 3, AC-4): it
//!   resolves the previous release on the target, flips the proxy back to it,
//!   repoints `current`, and re-probes `/ready` — failing loudly when there is no
//!   previous release to roll back to.
//!
//! Only the CI end-to-end harness that exercises rollback over real ssh against a
//! container remains (Slice 4). The plan/unit generators here are pure functions
//! so they can be unit-tested without a server, and the preflight graders are
//! shared with `autumn doctor`.

mod bake;
pub mod exec;
// #1621: the fleet planning layer is crate-internal — every item is `pub(crate)`
// and only `deploy` (and, later, its rollout driver) consumes it, so the module
// itself stays private rather than joining the `pub mod` siblings above.
mod fleet;
pub mod media;
pub mod proxy;

use std::net::{TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use autumn_web::alerts::{Alert, AlertChannel, AlertCondition};
use autumn_web::config::{AutumnConfig, DeployConfig, Env};
use proxy::ProxyController;
use serde::Deserialize;

/// Bounded timeout for the SSH-reachability preflight probe. Kept short so the
/// check fails fast on an unreachable host instead of hanging on a dropped SYN.
const SSH_PROBE_TIMEOUT: Duration = Duration::from_secs(5);

/// Default migrations directory scanned by the `migrate check` preflight grader.
const MIGRATIONS_DIR: &str = "migrations";

/// Detail shown when no deploy target host is configured. Shared by the offline
/// host-present grader and the online SSH-reachability probe so `autumn deploy
/// check` and `autumn doctor` report the missing-host case identically.
const DEPLOY_HOST_MISSING_DETAIL: &str = "no target host configured";

/// Remediation hint for a missing/blank `[deploy] host`. Shared so every surface
/// (offline `doctor`, online `deploy check`) points at the same fix.
///
/// #1621 EXTENDED this text with the fleet spelling rather than replacing it: the
/// literal substring `` `[deploy] host` `` is asserted by
/// `deploy_check_fails_fast_without_host` and quoted in operator runbooks, so it
/// must survive verbatim.
const DEPLOY_HOST_MISSING_HINT: &str = "Set `[deploy] host` in autumn.toml to your server's SSH-reachable address \
     (or `[deploy] hosts = [\"<address>\", …]` to deploy a fleet)";

/// [`DeployError::BakeFailed`]: the host was rolled back.
pub const BAKE_ROLLED_BACK: &str = "The host was rolled back to the previous release.";

/// [`DeployError::BakeFailed`]: the automatic rollback did not finish.
pub const BAKE_ROLLBACK_FAILED: &str = "The automatic rollback did not finish, so the host can \
     still run the new release. Run `autumn deploy rollback`.";

/// [`DeployError::BakeFailed`]: the rollback target was not safe to use.
pub const BAKE_ROLLBACK_REFUSED: &str = "The automatic rollback was not safe, so the host still \
     runs the new release. Follow the recovery steps above.";

/// [`DeployError::BakeFailed`]: `--no-rollback` left the new release live.
pub const BAKE_FROZEN: &str = "--no-rollback is set, so the new release still serves. Run \
     `autumn deploy rollback` to roll back.";

/// Errors surfaced by `autumn deploy`.
#[derive(Debug, thiserror::Error)]
pub enum DeployError {
    /// The project configuration could not be loaded.
    #[error("failed to load configuration: {0}")]
    Config(String),

    /// `deploy` was invoked on a platform where it is not supported natively
    /// (issue #1616). Its own variant rather than [`Self::Config`]: nothing is
    /// wrong with the configuration, and prefixing this message with "failed to
    /// load configuration" would send the operator to the wrong file.
    #[error("{0}")]
    UnsupportedPlatform(String),

    /// One or more preflight graders failed.
    #[error(
        "preflight failed: {0} check(s) did not pass — resolve the issues above and re-run \
         `autumn deploy check`"
    )]
    PreflightFailed(usize),

    /// The release binary to upload was not found on disk.
    #[error("release binary not found at {0} — run `autumn build --embed` first")]
    BinaryMissing(String),

    /// Remote execution of the first deploy failed.
    #[error("deploy execution failed: {0}")]
    Exec(String),

    /// The post-cutover bake found a breach on a one-host deploy (issue #3069).
    ///
    /// A fleet reports a bake breach as [`Self::FleetHalted`] with the step
    /// `bake`. `result` is one of [`BAKE_ROLLED_BACK`], [`BAKE_ROLLBACK_FAILED`],
    /// [`BAKE_ROLLBACK_REFUSED`] or [`BAKE_FROZEN`].
    #[error(
        "the bake failed on {host}: {reason}. {result}{}",
        .schema_note.map_or_else(String::new, |note| format!(" Note: {note}"))
    )]
    BakeFailed {
        /// The host.
        host: String,
        /// The breach.
        reason: String,
        /// What the deploy did about it.
        result: &'static str,
        /// Set when a migration ran: the rollback restored binaries only.
        schema_note: Option<&'static str>,
    },

    /// A multi-host rollout stopped mid-fleet (issue #1621, AC-3).
    ///
    /// **Boxed deliberately.** The payload is seven fields (160 bytes) and
    /// `DeployError` is the `Err` type of essentially every function in this
    /// module, so inlining it would make each of ~30 `Result`s carry the halt
    /// report on its happy path — which `clippy::result_large_err` (armed by the
    /// workspace's `-D warnings` gate) refuses, correctly. One allocation on the
    /// rarest path is the right trade.
    #[error("{0}")]
    FleetHalted(Box<FleetHalt>),

    /// A fleet-wide `deploy rollback` did not restore every host (issue #1621).
    ///
    /// Unlike [`Self::FleetHalted`] this is not a partial-state report: a fleet
    /// rollback is **best-effort-continue**, so every host was attempted and the
    /// per-host table printed above it is the detail. Two counts are all this
    /// carries — never a host-specific string built from a driver error.
    ///
    /// Returned when ANY host was left un-rolled-back — its rollback failed, or it
    /// had no previous release to return to. Partial success is failure here: the
    /// contract is that the FLEET returns to its previous release, and a fleet where
    /// one host could not follow the others is mixed.
    #[error(
        "fleet rollback incomplete: {not_rolled_back} of {total} host(s) were not rolled back \
         — see the per-host table above. A host with no previous release recorded cannot be \
         rolled back; deploy the intended release to it explicitly, or retry one host with \
         `autumn deploy rollback --only <host>`"
    )]
    FleetRollbackFailed {
        /// Hosts left un-rolled-back (failed, or nothing to roll back to).
        not_rolled_back: usize,
        /// Hosts attempted.
        total: usize,
    },

    /// `deploy status --strict` found drift (issue #1621, AC-6).
    ///
    /// Carries no payload: the status table printed above IS the report, and this
    /// error exists so drift is alertable from cron — the default (non-`--strict`)
    /// status never fails on drift.
    #[error(
        "fleet drift detected — the status table above names each host and reason \
         (`--strict` exits non-zero on drift so it can be alerted on)"
    )]
    DriftDetected,

    /// A fleet `deploy maintenance on|off` did not reach every host (issue #1621,
    /// AC-5).
    ///
    /// Best-effort-and-aggregate: every host was attempted, the per-host table
    /// above names the ones that DID change (they are deliberately NOT reversed —
    /// that would reopen the window the operator is closing), and this carries
    /// only counts — never a host-derived string.
    #[error(
        "fleet maintenance {verb} incomplete: {failed} of {total} host(s) failed — the \
         table above names the hosts that DID change, so they can be reversed by hand \
         if the fleet must stay consistent"
    )]
    FleetMaintenanceFailed {
        /// Which verb was fanned out (`"on"` / `"off"`).
        verb: &'static str,
        /// Hosts whose change failed.
        failed: usize,
        /// Hosts attempted.
        total: usize,
    },
}

/// The partial-fleet state a halted rollout leaves behind (issue #1621, AC-3).
///
/// Every field is a host name or a `&'static str` op label — never a shell line, a
/// remote path, or a formatted driver error (a failed migration's source can embed
/// the database URL). The lists describe the FINAL state, after any automatic
/// compensation: a host whose rollback failed stays in `still_on_new`, which is the
/// whole point of reporting them.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
    "fleet rollout halted at {failed_host} during `{failed_step}` — the remaining hosts were \
     not touched, and any migration that already ran was NOT rolled back (automatic \
     compensation restores binaries only)"
)]
pub struct FleetHalt {
    /// Host the rollout stopped on.
    pub failed_host: String,
    /// Label of the step that failed on it.
    pub failed_step: &'static str,
    /// Hosts whose previous release is serving again — either their own
    /// pre-boundary teardown or the fleet's compensating rollback.
    pub rolled_back: Vec<String>,
    /// Hosts left with nothing installed — either a torn-down first-deploy
    /// candidate or a first deploy the fleet compensated away.
    pub torn_down: Vec<String>,
    /// Hosts left running the NEW release, in rollout order.
    pub still_on_new: Vec<String>,
    /// Hosts that cut over but whose post-cutover housekeeping failed, with the
    /// step label. Recorded even when the host was later compensated, because the
    /// debris (an unwritten `shared/proxy-options` marker in particular) outlives
    /// the rollback and fails the NEXT deploy closed.
    pub degraded: Vec<(String, &'static str)>,
    /// Hosts whose first deploy was torn down, but whose proxy route removal
    /// failed (issue #2270), with the step label. Also present in `torn_down`
    /// (the app really is gone), but named here TOO so an API caller or an
    /// alert built from this struct — not just the console table — can tell a
    /// clean compensation apart from one whose public port may still answer
    /// 502 until it is redeployed or the route is removed by hand.
    pub route_removal_failed: Vec<(String, &'static str)>,
    /// Hosts the fleet deliberately did NOT roll back, with the reason.
    pub manual: Vec<(String, &'static str)>,
}

impl FleetHalt {
    /// The risk that the failed step leaves, when the step label alone does not
    /// name it (issue #2279). A `drain-old` halt has a risk only while the host
    /// is still on the new release. A rollback leaves one slot running.
    #[must_use]
    pub fn risk(&self) -> Option<&'static str> {
        (self.failed_step == fleet::DRAIN_OLD_LABEL
            && self.still_on_new.contains(&self.failed_host))
        .then_some(fleet::OLD_SLOT_MAY_RUN_NOTE)
    }
}

/// Which `autumn deploy` subcommand to run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeployAction {
    /// Run the preflight and report pass/fail.
    Check,
    /// Print the systemd unit and the ordered deploy plan (dry-run).
    Plan,
    /// Run the preflight, then perform a REAL on-demand rollback over SSH.
    Rollback,
    /// Run the preflight, then perform a REAL first deploy over SSH.
    Up,
    /// Report every configured host's state, read-only (issue #1621, AC-6).
    Status,
    /// Turn maintenance mode ON across every configured host (issue #1621, AC-5).
    ///
    /// The flags travel in [`DeployOptions::maintenance`] so this enum stays
    /// fieldless and `Copy`.
    MaintenanceOn,
    /// Turn maintenance mode OFF across every configured host (issue #1621, AC-5).
    MaintenanceOff,
}

/// The `autumn deploy maintenance on` flags (issue #1621, AC-5).
///
/// Exactly the flag set of the existing local `autumn maintenance on`, because the
/// two write the SAME wire format — `autumn_web::maintenance::MaintenanceConfig` —
/// and an operator who knows one must not have to learn the other. This is a plain
/// owned mirror of `MaintenanceOnOptions` (which borrows, and carries a test-only
/// path override that has no meaning for a remote host).
///
/// Carried in [`DeployOptions`] rather than as a [`DeployAction`] payload so the
/// action enum stays fieldless and `Copy`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MaintenanceOnArgs {
    /// Human-readable message shown in the 503 body.
    pub message: Option<String>,
    /// CIDR blocks / IPs whose requests bypass the gate.
    pub allow_ips: Vec<String>,
    /// Let GET/HEAD/OPTIONS through while blocking writes.
    pub readonly: bool,
    /// `(header name, expected value)` that bypasses the gate.
    pub bypass_header: Option<(String, String)>,
}

/// Flags that modify a [`DeployAction`] (issue #1621, plan §3.1).
///
/// Carried **beside** the action rather than inside it: [`DeployAction`] is a
/// fieldless `Copy` enum matched 1:1 by `run_deploy_command`, and giving its
/// variants payloads would ripple into every call site and test for no gain. This
/// struct is also the natural home for the later fleet flags (`--json`,
/// `--strict`, the maintenance verb) and, in Phase 2, `--role` — so it derives
/// [`Default`] and every construction site outside the CLI uses
/// `..DeployOptions::default()`, making each addition a non-event.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DeployOptions {
    /// Restrict the command to these hosts, a subset of `[deploy] hosts` (the
    /// repeatable `--only`). Empty means the whole configured fleet.
    ///
    /// A **repair lever, not a convenience**: narrowing a rollout is how an
    /// operator ends up with a mixed fleet on purpose, so the CLI says so out
    /// loud whenever this excludes a configured host.
    pub only: Vec<String>,
    /// Halt and FREEZE a failed rollout instead of compensating it (`--no-rollback`).
    ///
    /// The hosts that already cut over are left exactly as they are for
    /// inspection, and named in the state table. See [`FleetUpInput::auto_rollback`].
    pub no_rollback: bool,
    /// `deploy status --json`: emit the stable machine-readable report (the repo's
    /// skills are a first-class consumer) instead of the table.
    pub json: bool,
    /// `deploy status --strict`: exit non-zero when ANY drift is detected, so
    /// drift is alertable from cron. The default status always exits 0 (it is a
    /// report, not a judgement).
    pub strict: bool,
    /// The `deploy maintenance on` flags. `Some` only for
    /// [`DeployAction::MaintenanceOn`]; `None` everywhere else (including
    /// `MaintenanceOff`, which takes no flags).
    pub maintenance: Option<MaintenanceOnArgs>,
    /// `deploy up --bake-secs`: the bake time, over `[deploy.bake]
    /// duration_secs`. `Some(0)` turns the bake off (issue #3069).
    pub bake_secs: Option<u64>,
}

/// A `[deploy]` section with all defaults resolved to concrete values.
///
/// `app_name`, `app_dir`, and `service_name` are resolved here (from the
/// project's package name) rather than during deserialization, matching the
/// documented "resolved at deploy time" behavior of [`DeployConfig`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedDeployConfig {
    /// SSH-reachable target host, if configured.
    pub host: Option<String>,
    /// SSH user.
    pub user: String,
    /// SSH port.
    pub ssh_port: u16,
    /// Resolved application name.
    pub app_name: String,
    /// Resolved remote install directory.
    pub app_dir: String,
    /// Resolved systemd unit name.
    pub service_name: String,
    /// Readiness window (seconds) before rollback.
    pub readiness_timeout_secs: u64,
    /// Prior releases retained on the host.
    pub keep_releases: u32,
    /// Profile the deployed app runs under (written to the host env file as
    /// `AUTUMN_ENV`). Defaults to the production profile (`"prod"`).
    pub profile: String,
    /// Whether the deploy-managed proxy terminates TLS on 443 (`[deploy.tls]
    /// enabled`). `false` (unchanged HTTP-only behavior) unless opted in.
    pub tls_enabled: bool,
    /// Public hostname the proxy's TLS certificate is issued for. `Some` ONLY
    /// when TLS is enabled and a non-blank host was configured; `None` when TLS
    /// is disabled.
    pub tls_host: Option<String>,
    /// Whether this deploy may install the reverse-proxy binary on a host that has
    /// none (`[deploy] install_proxy`, default `true`; issue #1607, AC-1).
    pub install_proxy: bool,
    /// Release-relative path of the `SQLite` data file, when the app is on the
    /// `SQLite` tier and its `[database]` URL names a RELATIVE file (issue
    /// #1909).
    ///
    /// A slot unit's `WorkingDirectory` is the release dir, so a relative
    /// `sqlite://./app.db` resolves INSIDE the release — a new release would
    /// start against an empty database and the old release's file would be
    /// pruned away with its directory. When this is `Some`, the deploy keeps the
    /// real file in [`Self::shared_data_dir`] and links each release at this
    /// path (see [`crate::deploy::exec::sqlite_data_link_op`]).
    ///
    /// [`SqliteDataPlacement::None`] for a Postgres app;
    /// [`SqliteDataPlacement::Persistent`] for a `SQLite` app whose URL is
    /// already an absolute path outside the releases dir, which is verified on
    /// the host but never relocated. Set by
    /// [`Self::with_sqlite_data_placement`]; [`Self::resolve`] leaves it
    /// `None`, since it grades `[deploy]` and never reads `[database]`.
    pub sqlite_data: SqliteDataPlacement,
    /// Basenames this deploy writes into the release dir (the app binary and the
    /// uploaded config manifests). A relative `SQLite` data file may not collide
    /// with one: the data link is created first, so `scp` would follow it and
    /// truncate the database (#2589 item 11).
    ///
    /// Empty on [`Self::resolve`], which grades `[deploy]` alone. The real deploy
    /// path fills it via [`Self::with_release_payloads`]; the refusal in
    /// [`classify_sqlite_data_file`] also applies a filesystem-independent rule,
    /// so an empty list never leaves the common names unguarded.
    pub release_payloads: Vec<String>,
}

/// What a deploy must do to keep the app's `SQLite` data file (issue #1909).
///
/// ONE value rather than two `Option` fields, so the two managed states cannot
/// both be set: they are decided by a single [`classify_sqlite_data_file`] call.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum SqliteDataPlacement {
    /// Nothing for the deploy to manage: a Postgres app, or a refused config
    /// that preflight already failed.
    #[default]
    None,
    /// A release-relative file. The real file is kept in `shared/data` and each
    /// release is linked at the path the app resolves.
    Relative(String),
    /// An absolute, operator-managed file. There is nothing to relocate, but the
    /// deploy still VERIFIES on the host that it is not inside the releases
    /// directory: a symlinked `app_dir` is invisible to the local lexical check,
    /// which would grade a file under `releases/` durable while retention
    /// deletes it (#2589 item 13).
    Persistent(String),
}

/// Canonicalize a deploy profile string to the value the app's runtime resolver
/// would produce, so the preflight grade and the `AUTUMN_ENV` written to the
/// host env file agree on a single spelling.
///
/// Mirrors `autumn_web::config::normalize_profile_name` (the source of truth) so
/// non-canonical spellings can't slip past preflight and then be rejected at
/// host boot: trims whitespace; case-insensitively folds `production`/`prod` →
/// `"prod"` and `development`/`dev` → `"dev"`; preserves any other non-empty
/// value verbatim (custom profiles like `staging`/`QA`); and for a blank/empty
/// value falls back to the deploy default `"prod"` (matching
/// `autumn_web::config::default_deploy_profile`). Keep this in sync if the
/// runtime rules ever change.
// `pub(crate)` (not `pub`): reachable from `doctor` so it grades the deploy
// signing secret against the same normalized deploy profile, but kept
// crate-internal. In this bin-only crate `deploy` is a private module, so clippy
// flags the `pub(crate)` as redundant; we keep it to document the intended
// visibility rather than widening to `pub`.
#[allow(clippy::redundant_pub_crate)]
pub(crate) fn canonicalize_deploy_profile(raw: &str) -> String {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return "prod".to_owned();
    }

    if trimmed.eq_ignore_ascii_case("production") {
        return "prod".to_owned();
    }
    if trimmed.eq_ignore_ascii_case("development") {
        return "dev".to_owned();
    }
    if trimmed.eq_ignore_ascii_case("prod") {
        return "prod".to_owned();
    }
    if trimmed.eq_ignore_ascii_case("dev") {
        return "dev".to_owned();
    }

    // Preserve user-specified case for custom profile names.
    trimmed.to_owned()
}

/// Trim a deploy profile string, preserving the operator's raw spelling.
///
/// This is what gets stored on [`ResolvedDeployConfig::profile`] and written to
/// `AUTUMN_ENV`, so the host's runtime override-file lookup
/// (`autumn_web::config::profile_override_file_lookup_names`) sees the exact
/// selector the operator wrote — e.g. `autumn-production.toml` is preferred over
/// `autumn-prod.toml` when the raw input was `production`. Alias folding here
/// would flip that precedence, so we deliberately do NOT fold: trims whitespace;
/// for a blank/empty value falls back to the deploy default `"prod"` (matching
/// `autumn_web::config::default_deploy_profile`); otherwise returns the trimmed
/// string verbatim (no alias folding, no case change). Grading normalizes
/// separately via [`canonicalize_deploy_profile`] at the grade site.
// `pub(crate)` (not `pub`): reachable from `doctor` so its deploy secret/DB
// value graders derive the RAW deploy-profile spelling exactly like
// [`ResolvedDeployConfig::resolve`] stores it (trimmed, empty → `prod`), rather
// than re-deriving (and drifting from) that rule. Kept crate-internal. In this
// bin-only crate `deploy` is a private module, so clippy flags the `pub(crate)`
// as redundant; we keep it to document the intended visibility.
#[allow(clippy::redundant_pub_crate)]
pub(crate) fn trimmed_deploy_profile(raw: &str) -> String {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return "prod".to_owned();
    }
    trimmed.to_owned()
}

impl ResolvedDeployConfig {
    /// Resolve a [`DeployConfig`] against the project name, filling in the
    /// `app_name` → `app_dir` → `service_name` default chain.
    ///
    /// # Errors
    ///
    /// Returns a message when `[deploy.tls] enabled = true` but no non-blank
    /// `host` is configured — TLS cannot be provisioned without a hostname for
    /// the certificate, so the misconfiguration is rejected before any remote
    /// command runs.
    pub fn resolve(cfg: &DeployConfig, project_name: &str) -> Result<Self, String> {
        let non_blank = |s: &Option<String>| {
            s.as_ref()
                .map(|v| v.trim().to_owned())
                .filter(|v| !v.is_empty())
        };

        let app_name = non_blank(&cfg.app_name).unwrap_or_else(|| project_name.to_owned());
        let app_dir = non_blank(&cfg.app_dir).unwrap_or_else(|| format!("/srv/autumn/{app_name}"));
        let service_name = non_blank(&cfg.service_name).unwrap_or_else(|| app_name.clone());

        // TLS is opt-in: when disabled, `tls_host` stays `None` and nothing about
        // the render/deploy commands changes. When enabled, a non-blank `host` is
        // mandatory (the certificate is issued for it).
        let tls_host = if cfg.tls.enabled {
            let host = non_blank(&cfg.tls.host).ok_or_else(|| {
                "[deploy.tls] requires a non-empty `host` when enabled: set \
                 `[deploy.tls] host = \"<public-hostname>\"` in autumn.toml to the DNS \
                 name the TLS certificate should be issued for"
                    .to_owned()
            })?;
            Some(host)
        } else {
            None
        };

        Ok(Self {
            host: non_blank(&cfg.host),
            user: cfg.user.clone(),
            ssh_port: cfg.ssh_port,
            app_name,
            app_dir,
            service_name,
            readiness_timeout_secs: cfg.readiness_timeout_secs,
            keep_releases: cfg.keep_releases,
            profile: trimmed_deploy_profile(&cfg.profile),
            tls_enabled: cfg.tls.enabled,
            tls_host,
            install_proxy: cfg.install_proxy,
            sqlite_data: SqliteDataPlacement::None,
            release_payloads: Vec::new(),
        })
    }

    /// Attach the `SQLite` data-file placement this deploy must honor (issue
    /// #1909). See [`SqliteDataPlacement`].
    #[must_use]
    pub fn with_sqlite_data_placement(mut self, placement: SqliteDataPlacement) -> Self {
        self.sqlite_data = placement;
        self
    }

    /// Attach the basenames this deploy uploads into the release dir. See
    /// [`Self::release_payloads`].
    #[must_use]
    pub fn with_release_payloads(mut self, payloads: Vec<String>) -> Self {
        self.release_payloads = payloads;
        self
    }

    /// The release-relative data file, when the deploy manages one.
    #[must_use]
    pub fn relative_sqlite_data_file(&self) -> Option<&str> {
        match &self.sqlite_data {
            SqliteDataPlacement::Relative(rel) => Some(rel),
            SqliteDataPlacement::None | SqliteDataPlacement::Persistent(_) => None,
        }
    }

    /// The absolute operator-managed data file, when there is one to verify.
    #[must_use]
    pub fn persistent_sqlite_data_file(&self) -> Option<&str> {
        match &self.sqlite_data {
            SqliteDataPlacement::Persistent(path) => Some(path),
            SqliteDataPlacement::None | SqliteDataPlacement::Relative(_) => None,
        }
    }

    /// Persistent per-app dir shared across releases (holds the secret env
    /// file). The config manifest(s) uploaded for #1952 are NOT here — they are
    /// uploaded into each release's own dir ([`Self::releases_dir`]) so a
    /// rollback reads the manifest that shipped with the release it rolls back
    /// to; the deployed systemd unit points `AUTUMN_MANIFEST_DIR` at that
    /// release dir, not at this one.
    #[must_use]
    pub fn shared_dir(&self) -> String {
        format!("{}/shared", self.app_dir)
    }

    /// Remote path to the `EnvironmentFile` holding secrets (mode `0600`), kept
    /// out of the world-readable systemd unit.
    #[must_use]
    pub fn env_file(&self) -> String {
        format!("{}/autumn.env", self.shared_dir())
    }

    /// Directory holding timestamped release dirs.
    #[must_use]
    pub fn releases_dir(&self) -> String {
        format!("{}/releases", self.app_dir)
    }

    /// Symlink pointing at the currently-serving release.
    #[must_use]
    pub fn current_symlink(&self) -> String {
        format!("{}/current", self.app_dir)
    }

    /// The maintenance flag file this host's slot units read (issue #1621, R1).
    ///
    /// It lives in the SHARED dir, not a release dir: the runtime's default flag
    /// path is cwd-relative and a slot unit's `WorkingDirectory` is the release dir,
    /// so a cutover would orphan the flag and silently un-maintain the host.
    /// `shared/` is created by `prepare-dirs`, survives cutovers, rollbacks and
    /// pruning, and is seen by BOTH slots — so a flag written here means the same
    /// thing before and after a deploy. [`render_app_unit`] stamps this path into
    /// every slot unit via `AUTUMN_MAINTENANCE_FLAG_FILE`, and the fleet
    /// `deploy maintenance` fan-out writes exactly here.
    ///
    /// The file NAME comes from `autumn_web` — the CLI never re-declares a wire
    /// path the framework owns.
    #[must_use]
    pub fn maintenance_flag_file(&self) -> String {
        format!(
            "{}/{}",
            self.shared_dir(),
            autumn_web::maintenance::MAINTENANCE_FLAG_BASENAME
        )
    }

    /// Persistent directory holding the `SQLite` data file across releases
    /// (issue #1909).
    ///
    /// It sits under `shared/` for the reason the maintenance flag does: `shared/`
    /// survives cutovers, rollbacks and pruning, and both slots see it. A release
    /// dir is the opposite — replaced on every deploy, deleted by retention. The
    /// directory itself is created by the data-link op, not by `prepare-dirs`.
    #[must_use]
    pub fn shared_data_dir(&self) -> String {
        format!("{}/data", self.shared_dir())
    }

    /// Absolute path of the persistent `SQLite` data file, or `None` when this
    /// app has none to keep (Postgres, or an already-absolute `SQLite` path).
    #[must_use]
    pub fn shared_sqlite_data_file(&self) -> Option<String> {
        self.relative_sqlite_data_file()
            .map(|rel| format!("{}/{rel}", self.shared_data_dir()))
    }

    /// Marker recording that the shared `SQLite` database has been seen to exist
    /// (issue #1909, #2589 item 17).
    ///
    /// It lives in `shared/`, **never** in `shared/data`: the state it exists to
    /// detect is `shared/data` being an unavailable mount, and a marker inside
    /// that mount would disappear with it and report the very "never created"
    /// answer it is there to refute.
    ///
    /// Absent means the database has never been established, so a missing file is
    /// a genuine first deploy. Present means it must be there, so a missing file
    /// is a fault — an unmounted volume — and the deploy stops rather than
    /// creating a fresh database and orphaning the original.
    #[must_use]
    pub fn sqlite_data_marker_file(&self) -> String {
        format!("{}/sqlite-data-adopted", self.shared_dir())
    }
}

/// Validate the `[deploy]` host spelling(s) and return the ordered target list
/// (issue #1621, AC-1).
///
/// Accepts either the historical scalar `[deploy] host` or the fleet list
/// `[deploy] hosts`, never both, and returns the trimmed addresses **in
/// declaration order** — the order of `hosts` IS the rollout order, so nothing
/// here may sort or regroup it. An empty result means neither spelling configured
/// a target; that is a valid state at rest (`deploy plan` renders without one and
/// the `ssh_reachability` grader reports it), so it is NOT an error here.
///
/// Every rule fails closed BEFORE any remote command runs and names the offending
/// key/index/value, matching the house style of the other deploy refusals.
///
/// # Errors
///
/// Returns a message when `host` and `hosts` are both configured, when a `hosts`
/// entry is blank, or when a `hosts` entry repeats (compared after trimming).
// `pub(crate)` (not private): `doctor` enumerates the deploy target list through
// THIS function so its deploy branch grades the same fleet `deploy check` does —
// re-deriving the rules there is exactly the drift the parity invariant forbids.
// In this bin-only crate `deploy` is a private module, so clippy flags the
// `pub(crate)` as redundant; it is kept to document the intended visibility.
#[allow(clippy::redundant_pub_crate)]
pub(crate) fn deploy_host_list(cfg: &DeployConfig) -> Result<Vec<String>, String> {
    let host = cfg
        .host
        .as_deref()
        .map(str::trim)
        .filter(|host| !host.is_empty());

    // 1. Mutual exclusion. With both set the rollout order is ambiguous, so name
    //    BOTH keys and let the operator delete one.
    if host.is_some() && !cfg.hosts.is_empty() {
        return Err(
            "`[deploy] host` and `[deploy] hosts` are mutually exclusive: keep the \
             single-server `[deploy] host = \"<address>\"` or the fleet list \
             `[deploy] hosts = [\"<address>\", …]` in autumn.toml, not both (#1621)"
                .to_owned(),
        );
    }

    if cfg.hosts.is_empty() {
        return Ok(host.map(str::to_owned).into_iter().collect());
    }

    // 2. A blank entry would resolve to a hostless SSH target and blow up
    //    mid-rollout, with earlier hosts already cut over. The index is 0-based so
    //    the operator can find the line in a long list.
    let mut hosts: Vec<String> = Vec::with_capacity(cfg.hosts.len());
    for (index, entry) in cfg.hosts.iter().enumerate() {
        let trimmed = entry.trim();
        if trimmed.is_empty() {
            return Err(format!(
                "`[deploy] hosts` entry {index} is blank: every fleet entry must be an \
                 SSH-reachable hostname or IP (#1621)"
            ));
        }

        // 3. A duplicate deploys the same machine twice: the second pass sees its
        //    OWN new release as live, ping-pongs the blue/green slots and corrupts
        //    the previous-release chain a fleet rollback depends on. Compared after
        //    trimming; DNS aliases are a documented limitation (same as
        //    `migrate`'s `reject_duplicate_target_urls`).
        if hosts.iter().any(|seen| seen == trimmed) {
            return Err(format!(
                "`[deploy] hosts` lists `{trimmed}` more than once: each fleet host must \
                 appear exactly once — deploying the same server twice corrupts its \
                 previous-release chain (#1621)"
            ));
        }
        hosts.push(trimmed.to_owned());
    }

    Ok(hosts)
}

/// Narrow the configured host list to the `--only` selection (issue #1621, §3.2)
/// — **pure**, so the refusal lands before any config is even resolved.
///
/// Rules:
///
/// - An empty selection is the whole fleet (the default, and the only shape a
///   single-host config ever sees).
/// - The result keeps **declaration order**, not the order the flags were typed:
///   `[deploy] hosts` order IS the rollout order, and letting `--only c --only a`
///   reverse it would silently invert a rolling deploy.
/// - An unknown name is a hard error that quotes the name and lists the configured
///   hosts. Guessing (prefix match, DNS resolution) would let a typo deploy the
///   wrong machine, and silently deploying nothing would be worse still.
/// - A repeated name selects that host once.
///
/// # Errors
///
/// Returns a message naming the unmatched entry and listing the configured hosts.
fn select_hosts(configured: &[String], only: &[String]) -> Result<Vec<String>, String> {
    if only.is_empty() {
        return Ok(configured.to_vec());
    }

    for wanted in only {
        let wanted = wanted.trim();
        if !configured.iter().any(|host| host == wanted) {
            let known = if configured.is_empty() {
                "none — set `[deploy] hosts` in autumn.toml first".to_owned()
            } else {
                configured.join(", ")
            };
            return Err(format!(
                "`--only {wanted}` names a host that is not in this project's deploy \
                 configuration. Configured hosts: {known}. `--only` selects from that list \
                 verbatim — it never resolves or guesses a name, so a typo can't deploy the \
                 wrong machine (#1621)"
            ));
        }
    }

    // Filter the CONFIGURED list rather than mapping over `only`: `[deploy] hosts`
    // order is the rollout order, so `--only c --only a` must not reverse it. This
    // also de-duplicates a repeated flag for free.
    Ok(configured
        .iter()
        .filter(|host| only.iter().any(|wanted| wanted.trim() == host.as_str()))
        .cloned()
        .collect())
}

/// An ordered fleet of deploy targets, each a fully-resolved
/// [`ResolvedDeployConfig`] (issue #1621, AC-1).
///
/// The elements differ **only** in `host`: the shared shape (the `app_name` →
/// `app_dir` → `service_name` chain, the TLS-requires-host rejection, profile
/// trimming) is resolved ONCE through [`ResolvedDeployConfig::resolve`] and then
/// cloned per host. That is what makes a one-entry `hosts` list byte-for-byte the
/// historical single-server deploy *by construction* rather than by review —
/// everything below `exec::SshTarget::from_resolved` keeps working unchanged.
///
/// The list is never empty and is always in declaration (rollout) order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedFleet {
    /// The resolved targets, in rollout order. Guaranteed non-empty.
    pub hosts: Vec<ResolvedDeployConfig>,
}

impl ResolvedFleet {
    /// Resolve a [`DeployConfig`] into an ordered fleet against the project name.
    ///
    /// Validation runs first, in the documented order (mutual exclusion → blank
    /// entry → duplicate entry → no target at all), so a malformed fleet is
    /// refused before any host is touched.
    ///
    /// # Errors
    ///
    /// Returns a message when [`deploy_host_list`] rejects the host spelling(s),
    /// when neither `host` nor `hosts` configures a target, or when
    /// [`ResolvedDeployConfig::resolve`] rejects the shared shape (e.g.
    /// `[deploy.tls] enabled = true` with no `host`).
    // `deploy up` deliberately does NOT come through here: it resolves the shared
    // shape itself and builds the fleet with [`Self::from_targets`], so a config
    // with no target at all still reaches — and fails at — the PREFLIGHT report
    // (`ssh_reachability`), byte-identically to pre-#1621, instead of being
    // rejected earlier here with a different message and no report. This is the
    // seam the read-only fleet surfaces (`status`, `maintenance`) use.
    pub fn resolve(cfg: &DeployConfig, project_name: &str) -> Result<Self, String> {
        let addresses = deploy_host_list(cfg)?;
        if addresses.is_empty() {
            // 4. Neither spelling configured a target. Reuse the shared
            //    missing-host strings so `deploy check`, `doctor` and this seam
            //    report the case identically.
            return Err(format!(
                "{DEPLOY_HOST_MISSING_DETAIL}: {DEPLOY_HOST_MISSING_HINT}"
            ));
        }

        // Resolve the shared shape ONCE, then vary only `host`.
        let shared = ResolvedDeployConfig::resolve(cfg, project_name)?;
        Ok(Self::from_targets(&shared, &addresses))
    }

    /// Build a fleet from an ALREADY-resolved shared config plus the ordered
    /// address list from [`deploy_host_list`].
    ///
    /// The elements differ only in `host`, so a one-entry list is byte-for-byte
    /// today's single-server deploy **by construction**. An empty or single-entry
    /// list keeps `shared` verbatim — including a `None` host — so a config with no
    /// target still flows into the normal preflight report rather than being
    /// special-cased here.
    #[must_use]
    pub fn from_targets(shared: &ResolvedDeployConfig, addresses: &[String]) -> Self {
        if addresses.len() <= 1 {
            return Self {
                hosts: vec![ResolvedDeployConfig {
                    host: addresses.first().cloned().or_else(|| shared.host.clone()),
                    ..shared.clone()
                }],
            };
        }
        Self {
            hosts: addresses
                .iter()
                .map(|host| ResolvedDeployConfig {
                    host: Some(host.clone()),
                    ..shared.clone()
                })
                .collect(),
        }
    }

    /// Whether this fleet is a single server — the shape every pre-#1621 config
    /// resolves to, and the one that must behave identically to today.
    ///
    /// This answers "how many hosts is this RUN targeting?", which is **not** the
    /// same question as "is this the byte-identical pre-#1621 single-host deploy?" —
    /// a three-host config narrowed by `--only` to one host is a one-host fleet but
    /// not a single-host deploy. Use [`is_single_host_deploy`] for the latter.
    #[must_use]
    pub const fn is_single(&self) -> bool {
        self.hosts.len() == 1
    }
}

/// Whether this run is the genuine pre-#1621 **single-host deploy**: the config
/// declares ONE host and `--only` has not narrowed anything (issue #1621, AC-1).
///
/// This is the one predicate every "does this run keep the pre-#1621 shape?"
/// decision asks, so those decisions can never drift apart. It is deliberately
/// stricter than [`ResolvedFleet::is_single`]: a three-host fleet narrowed to one
/// host resolves to a one-host `ResolvedFleet`, but it is NOT a single-host deploy —
/// the other two hosts exist and are on another release, so the run keeps the fleet
/// vocabulary, the state table, the compensation semantics, and — the reason this
/// was extracted — **host attribution on every message**. An unattributed refusal
/// during a `--only` repair is exactly the wrong output at exactly the wrong moment.
/// See [`FleetUpInput::configured_host_count`].
///
/// Asked at three sites: the rollout driver ([`run_up_with`]), the per-host probe
/// refusals ([`probe_host_for_up`]), and the preflight report
/// ([`collect_fleet_preflight`]). [`run_rollback`] deliberately still branches on
/// `is_single()` alone — that is a choice of which CODE PATH runs, not of how a
/// message is worded, and narrowing a rollback to one host genuinely is a
/// single-host rollback; it is tracked separately.
const fn is_single_host_deploy(fleet: &ResolvedFleet, configured_host_count: usize) -> bool {
    fleet.is_single() && configured_host_count <= 1
}

/// A single ordered step in a deploy or rollback plan. Purely descriptive — a
/// plan is rendered, never executed, in this slice.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeployStep {
    /// Short label (a few words) naming the step.
    pub label: &'static str,
    /// One-line description of what the step does.
    pub description: String,
}

impl DeployStep {
    fn new(label: &'static str, description: impl Into<String>) -> Self {
        Self {
            label,
            description: description.into(),
        }
    }
}

/// Result of a single preflight grader. Shared by `autumn deploy check` and
/// `autumn doctor` so both surfaces grade identically.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreflightCheck {
    /// Short stable identifier for the check.
    ///
    /// **Deliberately still `&'static str`.** It is the operator-visible key in
    /// `autumn doctor --json`, so it must not become host-specific; a fleet names
    /// the host in [`Self::scope`] instead. (Making it dynamic would need a
    /// `Cow`/`Box::leak` — an unbounded per-host-per-run leak clippy will not flag
    /// — and would change a published contract for no gain.)
    pub name: &'static str,
    /// Which fleet host this grader graded, when that is a meaningful question
    /// (issue #1621, plan §5.2).
    ///
    /// `Some(host)` only for a per-host grader in a fleet of MORE THAN ONE host;
    /// `None` for every project-wide grader and for every check in a single-host
    /// deploy — which is what keeps single-host output byte-identical to pre-#1621
    /// (AC-1). [`preflight_label`] is the single place it is rendered.
    pub scope: Option<String>,
    /// Whether the check passed.
    pub passed: bool,
    /// Whether the check could not be verified here and is deliberately
    /// **deferred to the service's own runtime** (e.g. an env/interpolation
    /// indirected `[media.ffmpeg] bin` the deploy side must not guess). A
    /// deferred check is non-passing but **non-blocking** — it is surfaced as a
    /// warning and never aborts a deploy, distinct from an honest failure. See
    /// [`PreflightCheck::blocking`].
    pub deferred: bool,
    /// Human-readable detail (what was found).
    pub detail: String,
    /// One-line remediation hint shown on failure.
    pub hint: Option<&'static str>,
}

impl PreflightCheck {
    fn pass(name: &'static str, detail: impl Into<String>) -> Self {
        Self {
            name,
            scope: None,
            passed: true,
            deferred: false,
            detail: detail.into(),
            hint: None,
        }
    }

    fn fail(name: &'static str, detail: impl Into<String>, hint: &'static str) -> Self {
        Self {
            name,
            scope: None,
            passed: false,
            deferred: false,
            detail: detail.into(),
            hint: Some(hint),
        }
    }

    /// Attach the fleet host this check graded (issue #1621).
    ///
    /// Always called with `None` for a single-host fleet, so the rendered line is
    /// byte-identical to pre-#1621.
    #[must_use]
    fn scoped(mut self, scope: Option<String>) -> Self {
        self.scope = scope;
        self
    }

    /// Whether this check must abort the deploy. A check blocks only when it
    /// genuinely failed — a **deferred** check (non-passing, but resolved in the
    /// service's own runtime environment) is surfaced as a warning and never
    /// blocks. This is the single predicate every preflight gate keys on so a
    /// deferred outcome can never silently pass *or* hard-fail a deploy.
    #[must_use]
    pub const fn blocking(&self) -> bool {
        !self.passed && !self.deferred
    }
}

// ── Preflight graders (AC-6) ─────────────────────────────────────────────────

/// The preflight graders BOTH `autumn deploy check` and `autumn doctor` run, in
/// the order `deploy check` reports them (issue #1621, plan §5.5).
///
/// This is the **single shared source** for the parity invariant that the two
/// surfaces grade the same things. Doctor's own operator-visible check names are
/// mechanically this list with a `deploy_` prefix — see
/// [`DOCTOR_PREFLIGHT_GRADERS`] and the test that pins the derivation.
///
/// `ssh_reachability` is the only PER-HOST grader: a fleet emits one row per host
/// (distinguished by [`PreflightCheck::scope`]) and the other three once, because
/// they grade the project, not the target.
#[allow(clippy::redundant_pub_crate)]
// Consumed by the parity tests (deploy-side and doctor-side). Kept in production
// code rather than `#[cfg(test)]` because it IS the documented shared source the
// two surfaces derive from — hiding it in a test module would invite a third,
// unchecked hand-written list.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) const PREFLIGHT_GRADERS: [&str; 4] = [
    "ssh_reachability",
    "signing_secret",
    "database_url",
    "migrate_check",
];

/// `autumn doctor`'s names for [`PREFLIGHT_GRADERS`], in the same order.
///
/// These strings are an operator-visible `doctor --json` contract, so they are
/// spelled out literally (a `const fn` concat is not available for `&'static str`)
/// and pinned against [`PREFLIGHT_GRADERS`] by
/// `doctor_deploy_check_names_are_the_shared_grader_names_prefixed`. The doctor
/// branch indexes THIS array rather than repeating the literals, so a rename can
/// only happen in one place.
///
/// Two doctor deploy checks are deliberately NOT here: `deploy_config` (a
/// doctor-only config-load guard) and `deploy_host` (the OFFLINE host-presence
/// grader, which exists because doctor grades a deploy target without `--online`;
/// `deploy check` subsumes it into `ssh_reachability`, which reports the identical
/// missing-host detail and hint).
#[allow(clippy::redundant_pub_crate)]
pub(crate) const DOCTOR_PREFLIGHT_GRADERS: [&str; 4] = [
    "deploy_ssh_reachability",
    "deploy_signing_secret",
    "deploy_database_url",
    "deploy_migrate_check",
];

/// Grade that a deploy target host is configured — a pure, OFFLINE check with no
/// network I/O. This is deliberately split out from [`grade_ssh_reachability`]
/// (which performs a TCP probe) so `autumn doctor` can validate host presence
/// unconditionally — even without `--online` — while keeping the actual TCP
/// connect behind `--online`. A `[deploy]` table with a missing/blank `host`
/// makes `autumn deploy check` fail immediately, so `doctor` must fail on it too
/// rather than green-lighting a config the deploy path rejects.
#[must_use]
pub fn grade_deploy_host_present(host: Option<&str>) -> PreflightCheck {
    match host.map(str::trim).filter(|h| !h.is_empty()) {
        Some(_) => PreflightCheck::pass("deploy_host", "deploy target host is configured"),
        None => PreflightCheck::fail(
            "deploy_host",
            DEPLOY_HOST_MISSING_DETAIL,
            DEPLOY_HOST_MISSING_HINT,
        ),
    }
}

/// Grade that at least one deploy target is configured, across BOTH host
/// spellings (issue #1621) — the fleet sibling of [`grade_deploy_host_present`].
///
/// `hosts` is the validated, ordered list from [`deploy_host_list`]. Used by
/// `autumn doctor`, whose `deploy_host` check must grade a `[deploy] hosts` fleet
/// rather than reporting "no target host configured" because the scalar `host` is
/// unset.
///
/// The empty and single-host cases produce **byte-identical** detail/hint to
/// [`grade_deploy_host_present`], so single-server doctor output is unchanged; only
/// a real fleet gets the extra host enumeration. That enumeration lives in the
/// DETAIL text rather than in per-host check names because `CheckResult.name` is an
/// operator-visible `doctor --json` key (plan §5.2).
#[must_use]
pub fn grade_deploy_hosts_present(hosts: &[String]) -> PreflightCheck {
    match hosts {
        // Delegate the historical shapes to the historical grader, so their
        // detail/hint are identical BY CONSTRUCTION rather than by copy.
        [] => grade_deploy_host_present(None),
        [only] => grade_deploy_host_present(Some(only)),
        many => PreflightCheck::pass(
            "deploy_host",
            format!(
                "{} deploy target hosts configured, in rollout order: {}",
                many.len(),
                many.join(", ")
            ),
        ),
    }
}

/// Probe SSH reachability for EVERY configured host and aggregate the result into
/// ONE check (issue #1621) — the shape `autumn doctor` needs.
///
/// `deploy check` reports one `ssh_reachability` row per host (distinguished by
/// [`PreflightCheck::scope`]); doctor cannot, because its `CheckResult.name` is a
/// `&'static str` `--json` key that must stay stable and unique. So doctor grades
/// the same hosts with the same grader and folds the per-host outcomes into the
/// detail text: the NAME set stays identical between the two surfaces (the parity
/// invariant, plan §5.5) while the fleet detail is not lost.
///
/// A single-host list delegates straight through, so its detail/hint are
/// byte-identical to pre-#1621. The check fails when ANY host is unreachable — a
/// rollout touches all of them.
#[must_use]
pub fn grade_fleet_ssh_reachability(
    hosts: &[String],
    ssh_port: u16,
    timeout: Duration,
) -> PreflightCheck {
    match hosts {
        [] => grade_ssh_reachability(None, ssh_port, timeout),
        [only] => grade_ssh_reachability(Some(only.as_str()), ssh_port, timeout),
        many => {
            let graded: Vec<(&str, PreflightCheck)> = many
                .iter()
                .map(|host| {
                    (
                        host.as_str(),
                        grade_ssh_reachability(Some(host.as_str()), ssh_port, timeout),
                    )
                })
                .collect();
            let unreachable: Vec<&str> = graded
                .iter()
                .filter(|(_, check)| !check.passed)
                .map(|(host, _)| *host)
                .collect();
            if unreachable.is_empty() {
                PreflightCheck::pass(
                    "ssh_reachability",
                    format!(
                        "SSH port reachable on all {} fleet hosts: {}",
                        many.len(),
                        many.join(", ")
                    ),
                )
            } else {
                PreflightCheck::fail(
                    "ssh_reachability",
                    format!(
                        "cannot reach {} of {} fleet hosts on port {ssh_port}: {}",
                        unreachable.len(),
                        many.len(),
                        unreachable.join(", ")
                    ),
                    "Confirm the server is up, the SSH port is open, and any firewall allows your IP",
                )
            }
        }
    }
}

/// Grade SSH reachability: a bounded, non-interactive TCP connect to the SSH
/// port. This slice does not shell out to `ssh` (that lands with real remote
/// execution) — an honest "the port is reachable" probe is sufficient here.
///
/// The missing-host case reuses the same detail/hint as the offline
/// [`grade_deploy_host_present`] grader so the two surfaces stay consistent.
#[must_use]
pub fn grade_ssh_reachability(
    host: Option<&str>,
    ssh_port: u16,
    timeout: Duration,
) -> PreflightCheck {
    let Some(host) = host.map(str::trim).filter(|h| !h.is_empty()) else {
        return PreflightCheck::fail(
            "ssh_reachability",
            DEPLOY_HOST_MISSING_DETAIL,
            DEPLOY_HOST_MISSING_HINT,
        );
    };

    let addrs = match (host, ssh_port).to_socket_addrs() {
        Ok(addrs) => addrs.collect::<Vec<_>>(),
        Err(e) => {
            return PreflightCheck::fail(
                "ssh_reachability",
                format!("could not resolve {host}:{ssh_port}: {e}"),
                "Check that `[deploy] host` is a resolvable hostname or a valid IP address",
            );
        }
    };

    if addrs.is_empty() {
        return PreflightCheck::fail(
            "ssh_reachability",
            format!("{host}:{ssh_port} resolved to no addresses"),
            "Check that `[deploy] host` is a resolvable hostname or a valid IP address",
        );
    }

    // Probe every resolved address, not just the first. A dual-stack host may
    // resolve to an IPv6 address first that an IPv4-only client cannot reach
    // (or vice versa); the port is reachable as long as ANY address connects.
    // Fail only when all of them fail, reporting the last error.
    let mut last_err = None;
    for addr in &addrs {
        match TcpStream::connect_timeout(addr, timeout) {
            Ok(_) => {
                return PreflightCheck::pass(
                    "ssh_reachability",
                    format!("SSH port reachable at {host}:{ssh_port}"),
                );
            }
            Err(e) => last_err = Some(e),
        }
    }

    let detail = last_err.map_or_else(
        || format!("cannot reach {host}:{ssh_port}"),
        |e| format!("cannot reach {host}:{ssh_port}: {e}"),
    );
    PreflightCheck::fail(
        "ssh_reachability",
        detail,
        "Confirm the server is up, the SSH port is open, and any firewall allows your IP",
    )
}

/// Grade signing-secret presence and, in production, strength. Never prints the
/// secret value.
///
/// In a non-production profile a present, non-empty secret is enough. In a
/// production profile the app boot path runs
/// [`autumn_web::security::validate_signing_secret`] and *exits* on a
/// missing/too-short/known-demo secret, so preflight reuses that exact validator
/// to reject the same values here — otherwise `deploy check` would greenlight a
/// release that immediately fails to boot (or ships a known demo secret).
///
/// The app boot path (`fail_fast_on_invalid_signing_secret`) also validates every
/// `previous_secrets` rotation entry with the same validator and exits if any is
/// weak, so preflight validates them too: a strong current secret paired with a
/// `previous_secrets = ["changeme"]` entry would otherwise pass `deploy check`
/// and then fail to boot. The rejection message names the offending rotation
/// entry by position without printing its value.
#[must_use]
pub fn grade_signing_secret(
    secret: Option<&str>,
    previous_secrets: &[String],
    is_production: bool,
) -> PreflightCheck {
    let Some(value) = secret.map(str::trim).filter(|s| !s.is_empty()) else {
        return PreflightCheck::fail(
            "signing_secret",
            "no signing secret configured",
            "Set AUTUMN_SECURITY__SIGNING_SECRET (generate with `openssl rand -hex 32`)",
        );
    };

    if is_production {
        // Reuse the exact runtime validator so preflight and app boot agree on
        // what counts as a valid production secret. The error's `Display`
        // embeds the (demo) secret value for `KnownWeakValue`, so we translate
        // each variant into a value-free message rather than formatting it.
        use autumn_web::security::{SigningSecretError, validate_signing_secret};
        if let Err(error) = validate_signing_secret(Some(value), true) {
            let detail = match error {
                SigningSecretError::MissingInProduction => {
                    "signing secret is required in production".to_owned()
                }
                SigningSecretError::TooShort { actual, required } => format!(
                    "signing secret is too short ({actual} bytes, minimum {required}) for production"
                ),
                SigningSecretError::KnownWeakValue(_) => {
                    "signing secret is a known demo/template value not allowed in production"
                        .to_owned()
                }
            };
            return PreflightCheck::fail(
                "signing_secret",
                detail,
                "Set a strong AUTUMN_SECURITY__SIGNING_SECRET (generate with `openssl rand -hex 32`)",
            );
        }

        // Rotation secrets accepted during a grace window must clear the same
        // bar as the current secret; the app boot path validates each
        // `previous_secrets` entry with the same validator and exits on the
        // first weak one. Report by 1-based position without printing the value.
        for (index, previous) in previous_secrets.iter().enumerate() {
            if let Err(error) = validate_signing_secret(Some(previous.as_str()), true) {
                let position = index + 1;
                let detail = match error {
                    SigningSecretError::MissingInProduction => format!(
                        "previous (rotation) signing secret #{position} is empty and not allowed in production"
                    ),
                    SigningSecretError::TooShort { actual, required } => format!(
                        "previous (rotation) signing secret #{position} is too short ({actual} bytes, minimum {required}) for production"
                    ),
                    SigningSecretError::KnownWeakValue(_) => format!(
                        "previous (rotation) signing secret #{position} is a known demo/template value not allowed in production"
                    ),
                };
                return PreflightCheck::fail(
                    "signing_secret",
                    detail,
                    "Remove or rotate out the weak entry in security.signing_secret.previous_secrets (each must be as strong as the current secret)",
                );
            }
        }
    }

    PreflightCheck::pass("signing_secret", "signing secret is configured")
}

/// Grade database-URL presence. Never prints the URL (it may embed credentials).
///
/// The URL is only *required* when the app is database-backed — any of:
/// - a migrations directory exists (the same presence check [`grade_migrate_check`]
///   uses, so the two graders agree), or
/// - a `[database]` section is configured, or
/// - a DB-backed runtime feature is enabled (`db_backed_runtime`) — e.g.
///   `jobs.backend = "postgres"` or `scheduler.backend = "postgres"`, whose
///   startup paths (`job::start_postgres_runtime` /
///   `scheduler::coordinator_from_config`) require a configured pool.
///
/// A zero-dependency, daemon-style app with none of these has nothing to connect
/// to, so the grader passes with a "no database configured" note instead of
/// failing preflight unconditionally.
#[must_use]
pub fn grade_database_url(
    url: Option<&str>,
    migrations_dir: &Path,
    database_configured: bool,
    db_backed_runtime: bool,
) -> PreflightCheck {
    match url.map(str::trim).filter(|u| !u.is_empty()) {
        Some(_) => PreflightCheck::pass("database_url", "database URL is configured"),
        None if !migrations_dir.exists() && !database_configured && !db_backed_runtime => {
            PreflightCheck::pass(
                "database_url",
                "no database configured (nothing to connect to)",
            )
        }
        None => PreflightCheck::fail(
            "database_url",
            "no writable database URL: this app is database-backed (migrations, a \
             `[database]` section, or a Postgres-backed runtime feature such as \
             `jobs.backend`/`scheduler.backend`) and needs a primary/control \
             (`database.primary_url`) or shard-primary URL; `database.replica_url` \
             alone is not a writable target",
            "Set database.primary_url (or database.url) in autumn.toml, or AUTUMN_DATABASE__URL",
        ),
    }
}

/// Grade `migrate check`: reuse the migration safety classifier and fail when a
/// pending migration is unsafe for a live rolling deploy. A project with no
/// migrations directory passes (there is nothing to check).
///
/// Detects the backend from the ambient profile. `autumn deploy` calls
/// [`grade_migrate_check_for`] with the DEPLOY TARGET profile's backend instead
/// (issue #1906 review); this form is for `autumn doctor`, which reports on the
/// project as it stands locally.
#[must_use]
pub fn grade_migrate_check(migrations_dir: &Path) -> PreflightCheck {
    // Grade against the app's own backend (issue #1906): a SQLite app's
    // migrations must be judged by SQLite's dialect, not Postgres's. The
    // offline detector never reads `.env` and never exits — `autumn doctor
    // --json` calls this while assembling its report.
    grade_migrate_check_for(
        crate::generate::detect_backend_offline(Path::new("."), None),
        migrations_dir,
    )
}

/// [`grade_migrate_check`] against an explicit `backend`, so the grader is
/// testable without a project on disk.
#[must_use]
pub fn grade_migrate_check_for(
    backend: autumn_web::config::DatabaseBackend,
    migrations_dir: &Path,
) -> PreflightCheck {
    if !migrations_dir.exists() {
        return PreflightCheck::pass(
            "migrate_check",
            "no migrations directory (nothing to check)",
        );
    }

    match crate::migrate::check_migrations_in_dir_for(backend, migrations_dir) {
        Ok(reports) => {
            let unsafe_names: Vec<&str> = reports
                .iter()
                .filter(|r| crate::migrate::safety::has_unsafe_findings(&r.up))
                .map(|r| r.name.as_str())
                .collect();
            if unsafe_names.is_empty() {
                PreflightCheck::pass(
                    "migrate_check",
                    format!("{} migration(s) safe for a rolling deploy", reports.len()),
                )
            } else {
                PreflightCheck::fail(
                    "migrate_check",
                    format!(
                        "migration(s) unsafe for a rolling deploy: {}",
                        unsafe_names.join(", ")
                    ),
                    "Run `autumn migrate check` and apply the expand/contract pattern before deploying",
                )
            }
        }
        Err(e) => PreflightCheck::fail(
            "migrate_check",
            format!("could not scan migrations: {e}"),
            "Run `autumn migrate check` to see the full report",
        ),
    }
}

// ── Artifact / plan generators (pure) ────────────────────────────────────────

/// Render the systemd service unit that supervises the deployed app.
///
/// An autumn app compiled with `autumn build --embed` is a standalone server
/// binary (the generated Dockerfile launches it directly as
/// `CMD ["/usr/local/bin/<app>"]`, with no `serve` subcommand). The deploy flow
/// uploads that pre-built binary into a timestamped release dir fronted by the
/// `current` symlink, so the unit execs the deployed binary at
/// `{app_dir}/current/{app_name}` directly — it must NOT run
/// `autumn serve --release`, which would rebuild the project from source.
///
/// The unit restarts on failure, comes back after reboot
/// (`WantedBy=multi-user.target`), and sources secrets from an `EnvironmentFile`
/// so they are never inlined into the world-readable unit (AC-5).
#[must_use]
pub fn render_systemd_unit(cfg: &ResolvedDeployConfig) -> String {
    format!(
        "[Unit]\n\
         Description=Autumn application: {app}\n\
         After=network-online.target\n\
         Wants=network-online.target\n\
         \n\
         [Service]\n\
         Type=simple\n\
         User={user}\n\
         WorkingDirectory={current}\n\
         EnvironmentFile={env_file}\n\
         Environment=AUTUMN_MANIFEST_DIR={manifest_dir}\n\
         ExecStart={current}/{app}\n\
         Restart=on-failure\n\
         RestartSec=2\n\
         \n\
         [Install]\n\
         WantedBy=multi-user.target\n",
        app = cfg.app_name,
        user = cfg.user,
        current = cfg.current_symlink(),
        env_file = cfg.env_file(),
        // Point the app's config loader at `current` (this unit's
        // WorkingDirectory), where the active release's uploaded autumn.toml
        // lives, so the deployed app loads the intended config instead of
        // built-in defaults (#1952). The manifest is coupled to the release, not
        // the shared dir. Non-secret, so it lives in the unit's Environment= (not
        // the 0600 env file).
        manifest_dir = cfg.current_symlink(),
    )
}

/// Render the systemd unit for a specific blue/green *slot* release (issue #1607,
/// Slice 2).
///
/// Unlike [`render_systemd_unit`] (which execs the `current` symlink), a slot unit
/// pins its own `release_dir` and binds a PRIVATE loopback `app_port`, so the blue
/// and green slots can run different releases side by side across a cutover while
/// the reverse proxy owns the public port. The unit is named
/// `{service}-{slot}.service` (see [`exec::slot_unit_name`]).
#[must_use]
pub fn render_app_unit(
    cfg: &ResolvedDeployConfig,
    release_dir: &str,
    app_port: u16,
    slot: &str,
) -> String {
    format!(
        "[Unit]\n\
         Description=Autumn application: {app} ({slot})\n\
         After=network-online.target\n\
         Wants=network-online.target\n\
         \n\
         [Service]\n\
         Type=simple\n\
         User={user}\n\
         WorkingDirectory={release_dir}\n\
         EnvironmentFile={env_file}\n\
         Environment=AUTUMN_MANIFEST_DIR={manifest_dir}\n\
         Environment={maintenance_env}={maintenance_flag}\n\
         Environment=AUTUMN_SERVER__HOST=127.0.0.1\n\
         Environment=AUTUMN_SERVER__PORT={app_port}\n\
         ExecStart={release_dir}/{app}\n\
         Restart=on-failure\n\
         RestartSec=2\n\
         \n\
         [Install]\n\
         WantedBy=multi-user.target\n",
        app = cfg.app_name,
        user = cfg.user,
        env_file = cfg.env_file(),
        // Point the app's config loader at this release dir (this unit's
        // WorkingDirectory), where the uploaded autumn.toml lives, so the deployed
        // app loads the intended config instead of built-in defaults (#1952). The
        // manifest is coupled to the binary in the retained per-release dir, so a
        // rollback re-rendering this unit from the target release dir reads that
        // release's OWN manifest. Non-secret → unit Environment=, not the 0600 env
        // file.
        manifest_dir = release_dir,
        // #1621 R1: point the runtime's maintenance flag at the per-app SHARED dir
        // instead of leaving it cwd-relative (i.e. release-relative, because
        // `WorkingDirectory` above is the release dir). Without this a cutover
        // orphans an active maintenance flag and silently un-maintains the host —
        // and the blue and green slots cannot see each other's flag at all. The
        // variable name and file name are the framework's, imported (never
        // re-declared here). Non-secret → unit `Environment=`.
        maintenance_env = autumn_web::maintenance::MAINTENANCE_FLAG_FILE_ENV,
        maintenance_flag = cfg.maintenance_flag_file(),
    )
}

/// Build the ordered, zero-downtime deploy plan (AC-2/3/4).
///
/// The sequence encodes the framework's `/live`-`/ready`-drain contract:
/// migrations run *before* cutover (a failed migration leaves the old version
/// serving), the candidate must report `/ready` within the bounded window (else
/// roll back), traffic is handed over only after readiness, and the old release
/// is drained and pruned last.
///
/// **The candidate never binds the live `server.port`.** For the default TCP
/// serving config the running app binds `server.host:server.port`, so starting
/// the candidate on that same port while the old release is still serving would
/// fail with "address already in use" *before* the readiness gate could ever
/// run — the plan would not be executable. The candidate is therefore started on
/// a SEPARATE listener (a distinct port/socket from the live service), and a
/// later explicit handoff step switches live traffic to it.
///
/// **The concrete handoff mechanism is an open design decision for the execution
/// follow-up.** This slice emits a mechanism-neutral PLAN: the cutover is
/// described as a "reverse-proxy upstream swap or systemd socket-activation
/// handoff" without committing to either in code. Whatever is chosen, the plan
/// must never imply the candidate binds the live `server.port`.
#[must_use]
pub fn build_deploy_plan(cfg: &ResolvedDeployConfig) -> Vec<DeployStep> {
    let mut steps = vec![
        DeployStep::new(
            "build",
            "Build the embedded single-binary release locally (`autumn build --embed`)",
        ),
        // FIRST, because it is the first thing that mutates the server: the install
        // ops are spliced at the head of the host's op vector, ahead of the upload.
        DeployStep::new(
            "prepare-host",
            "Ensure the target has a working kamal-proxy — the FIRST thing that touches the \
             server. A host that already has one is untouched; a host that has none gets the \
             pinned build installed, which also installs (and leaves behind) any of `curl` \
             and a container runtime it is missing, and pulls the pinned proxy image from \
             Docker Hub. Decline with `[deploy] install_proxy = false`",
        ),
        DeployStep::new(
            "upload",
            format!(
                "Upload the binary to a new timestamped release dir under {}",
                cfg.releases_dir()
            ),
        ),
        DeployStep::new(
            "migrate",
            "Run pending migrations BEFORE the new release takes traffic — on a redeploy an \
             abort here leaves the current version serving; on a first deploy the release is \
             never started",
        ),
        DeployStep::new(
            "start-candidate",
            "Start the new release as a candidate on a SEPARATE listener (a distinct \
             port/socket from the live service) — it does NOT bind the live \
             `server.port`, so the old release keeps serving traffic uninterrupted",
        ),
        DeployStep::new(
            "readiness-gate",
            format!(
                "Poll the candidate's /ready on its separate listener within {}s — roll back on \
                 timeout",
                cfg.readiness_timeout_secs
            ),
        ),
        DeployStep::new(
            "cutover",
            format!(
                "Hand live traffic over to the candidate — reverse-proxy upstream swap or systemd \
                 socket-activation handoff (mechanism finalized in the execution slice) — then \
                 promote it by pointing the {} symlink at the new release",
                cfg.current_symlink(),
            ),
        ),
        DeployStep::new(
            "drain",
            "Drain and stop the previous release once traffic has moved to the candidate",
        ),
        DeployStep::new(
            "prune",
            format!(
                "Prune old releases, retaining the most recent {} — always keeping the releases \
                 the current symlink and previous-release marker point at (rollback targets)",
                cfg.keep_releases
            ),
        ),
    ];
    insert_sqlite_data_steps(cfg, &mut steps);
    steps
}

/// Add the `SQLite` data-file steps where the deploy runs them (#2589 item 5):
/// the data step before `upload`, and the marker after `migrate`.
fn insert_sqlite_data_steps(cfg: &ResolvedDeployConfig, steps: &mut Vec<DeployStep>) {
    let data = if let Some(shared) = cfg.shared_sqlite_data_file() {
        let rel = cfg.relative_sqlite_data_file().unwrap_or_default();
        DeployStep::new(
            "link-data",
            format!(
                "Link the release's {rel} at the persistent {shared}. Refuses when {current}/{rel} \
                 is a real file or links elsewhere (a one-time adoption the refusal explains), or \
                 when {shared} is gone but {marker} records that it existed",
                current = cfg.current_symlink(),
                marker = cfg.sqlite_data_marker_file(),
            ),
        )
    } else if let Some(path) = cfg.persistent_sqlite_data_file() {
        DeployStep::new(
            "check-data-dir",
            format!(
                "Check on the host that {path} resolves outside {releases}, and create its \
                 directory when it is in {data}",
                releases = cfg.releases_dir(),
                data = cfg.shared_data_dir(),
            ),
        )
    } else {
        return;
    };
    let at = |label: &str, steps: &[DeployStep]| steps.iter().position(|s| s.label == label);
    if let Some(upload) = at("upload", steps) {
        steps.insert(upload, data);
    }
    if let Some(migrate) = at("migrate", steps) {
        steps.insert(
            migrate.saturating_add(1),
            DeployStep::new(
                "record-data-adopted",
                format!(
                    "Record {} once the database exists in {}, so a later missing volume is \
                     refused, not replaced with an empty database",
                    cfg.sqlite_data_marker_file(),
                    cfg.shared_data_dir()
                ),
            ),
        );
    }
}

/// Build the rollback plan, mirroring [`exec::rollback_ops`]'s actual sequence:
/// re-render the target slot's unit and `daemon-reload`, restart the previous
/// slot's unit, flip the proxy upstream back to it, record the release being
/// rolled back FROM as the new previous-release marker, repoint `current`, record
/// the live slot, re-probe `/ready`, and finally drain the slot the rollback
/// flipped traffic away from.
///
/// The order matters: the target unit is re-rendered from the persisted marker
/// (its dir + port) and `daemon-reload`ed FIRST so the restart never relaunches a
/// slot unit an earlier failed redeploy clobbered. The proxy flip is health-gated,
/// so the previous release's unit must be restarted and up *before* the flip can
/// pass, and the flip therefore precedes the `current` repoint. The former-live
/// slot is drained last, after the re-probe confirms the rolled-back release is
/// healthy.
#[must_use]
pub fn build_rollback_plan(cfg: &ResolvedDeployConfig) -> Vec<DeployStep> {
    vec![
        DeployStep::new(
            "write-target-unit",
            format!(
                "Re-render the previous release's {} slot unit from the persisted \
                 marker (its dir + port) so the restart never relaunches a slot unit \
                 an earlier failed redeploy left pointing at a removed candidate",
                cfg.service_name
            ),
        ),
        DeployStep::new(
            "daemon-reload",
            "Reload systemd so the restart below loads the freshly re-rendered unit",
        ),
        DeployStep::new(
            "restart-previous",
            format!(
                "Restart the previous release's {} slot unit so it is healthy \
                 before the proxy flips traffic back to it",
                cfg.service_name
            ),
        ),
        DeployStep::new(
            "proxy-flip",
            "Flip the reverse-proxy upstream back to the previous release \
             (health-gated on /ready before traffic moves)",
        ),
        DeployStep::new(
            "record-previous",
            "Record the release being rolled back FROM (its dir + former-live slot) \
             as the new previous-release marker so a subsequent rollback returns to it",
        ),
        DeployStep::new(
            "repoint",
            format!(
                "Point the {} symlink back at the previous release",
                cfg.current_symlink()
            ),
        ),
        DeployStep::new(
            "record-live-slot",
            "Record the previous slot as the live slot so the next deploy's mode \
             detection sees it serving",
        ),
        DeployStep::new(
            "readiness-gate",
            format!(
                "Re-probe /ready within {}s to confirm the rollback is healthy",
                cfg.readiness_timeout_secs
            ),
        ),
        DeployStep::new(
            "drain-rolled-back-slot",
            "Disable the slot that was live before the rollback (the one traffic \
             moved away from) so the next deploy sees it genuinely idle and starts \
             the new binary fresh",
        ),
    ]
}

// ── Command entrypoint ───────────────────────────────────────────────────────

/// The policy row `autumn deploy`'s remote actions are refused under, quoted
/// verbatim from [`crate::platform::POLICY`] — `tier_two_windows_error` panics
/// on a name the policy does not carry, so this is checked by every test that
/// builds a refusal.
const DEPLOY_TIER_TWO_POLICY_COMMAND: &str = "autumn deploy up / rollback / status / maintenance";

/// Whether an action opens an SSH session to a remote host.
///
/// This is the line the platform policy is drawn on (#1616). The remote actions
/// shell out to `ssh`/`sh`, and `up`/`rollback`/`maintenance` additionally stage
/// the environment file — carrying the app's signing secret and database
/// password — through `exec::stage_temp_file`, whose `chmod 0600` is
/// `#[cfg(unix)]`. On native Windows that file would be written with whatever
/// the containing directory's ACLs happen to be, which is the silent
/// degradation the policy forbids.
///
/// `check` and `plan` are on the other side of that line: `plan` renders the
/// systemd unit and step list from `resolved` alone, and `check` grades the
/// project config plus an `ssh_reachability` probe that is a portable
/// [`TcpStream::connect_timeout`] — no `ssh` binary, no staged file, nothing
/// written anywhere. They are Tier 1 on Windows, and they are precisely how a
/// Windows developer validates a deploy config *before* switching to WSL2 to
/// run it.
///
/// The match is deliberately exhaustive with no wildcard arm: a new
/// [`DeployAction`] must be classified here or the crate does not compile, so a
/// remote action can never default into "runs natively on Windows".
const fn reaches_a_remote_host(action: DeployAction) -> bool {
    match action {
        DeployAction::Check | DeployAction::Plan => false,
        DeployAction::Up
        | DeployAction::Rollback
        | DeployAction::Status
        | DeployAction::MaintenanceOn
        | DeployAction::MaintenanceOff => true,
    }
}

/// The refusal for a native-Windows `autumn deploy` action that reaches a remote
/// host, or `None` when the action is local-only or the host is supported.
///
/// Refusing up front — before any config load, SSH probe or temp file — is what
/// keeps Tier 2 from being a silent degradation (#1616).
///
/// Takes the OS family as a string so the Windows branch is covered by tests on
/// every host.
fn windows_deploy_refusal(os: &str, action: DeployAction) -> Option<String> {
    (os == "windows" && reaches_a_remote_host(action))
        .then(|| crate::platform::tier_two_windows_error(DEPLOY_TIER_TWO_POLICY_COMMAND))
}

/// Run the requested `autumn deploy` subcommand.
///
/// # Errors
///
/// Returns [`DeployError::UnsupportedPlatform`] when a remote-host action is
/// invoked on native Windows (those paths are Tier 2 / WSL2, see #1616;
/// `check` and `plan` are local-only and run natively),
/// [`DeployError::Config`] when the project config cannot be loaded, and
/// [`DeployError::PreflightFailed`] when `check` finds a failing grader.
pub fn run(action: DeployAction, options: &DeployOptions) -> Result<(), DeployError> {
    // Refuse before anything else: no config load, no SSH probe, no temp file.
    if let Some(refusal) = windows_deploy_refusal(std::env::consts::OS, action) {
        return Err(DeployError::UnsupportedPlatform(refusal));
    }
    // Ambient load (the operator's shell profile, `dev` by default), used only to read
    // `[deploy]` and compute `resolved` — in particular `resolved.profile`, the profile
    // the deployed service boots under (default `prod`). It is a lenient-unknown-roots
    // load (#2063): the deploy CLI structurally cannot know an app's plugin set, with no
    // AppBuilder and no plugin-crate dependency, so it must not fail closed on a
    // plugin-owned top-level table such as `[media]` under `strict_config`. Every core
    // section it does own stays strictly validated, and app boot — which knows the
    // plugin set through the `config_section` seam — remains the strict gate.
    let ambient_config = AutumnConfig::load_lenient_unknown_roots()
        .map_err(|e| DeployError::Config(e.to_string()))?;
    let deploy_cfg = ambient_config.deploy.unwrap_or_default();
    // #1621: refuse a malformed host spelling — `host` AND `hosts` together, a
    // blank entry, a duplicate entry — before ANY other work, so the operator sees
    // one actionable message instead of a preflight report graded against a target
    // list we could not make sense of. The ordered list is the rollout order and
    // is rendered by `plan`; the rollout DRIVER that consumes it via
    // `ResolvedFleet` lands in a later slice, so the single-host paths below are
    // deliberately untouched.
    let host_list = deploy_host_list(&deploy_cfg).map_err(DeployError::Config)?;
    // #1621: `--only` narrows the rollout to a subset of that list, in DECLARATION
    // order. Resolved here — before the config is even resolved and long before any
    // preflight probe — so a typo'd host name costs nothing and names itself.
    let targets = select_hosts(&host_list, &options.only).map_err(DeployError::Config)?;
    // A narrowed rollout is a deliberate repair lever that leaves the fleet on two
    // versions, so it is never silent.
    for line in fleet::only_selection_warning_lines(&host_list, &targets) {
        eprintln!("{line}");
    }
    let resolved = ResolvedDeployConfig::resolve(&deploy_cfg, &resolve_project_name())
        .map_err(DeployError::Config)?;

    // MediaMTX host-provisioning config (issue #1974, Slice 7) is loaded ONLY in
    // the actions that plan/provision media (`plan` and `up`). `check`/`rollback`
    // neither read nor provision `MediaMTX`, so parsing `[media]` there would let a
    // typo in `[media.mediamtx]`/`[media.ffmpeg]` fail-close a rollback that does
    // not touch media at all — a regression the round-2 fail-closed fix must not
    // introduce. The load stays fail-closed where it IS relevant (`plan`/`up`): a
    // present-but-invalid `[media]` table still aborts those two.
    match action {
        // `plan` is a dry-run: it never grades or uploads runtime VALUES. It loads
        // the target profile only to classify `[database]`, so it shows the SQLite
        // data steps the deploy runs (#2589 item 5). A config that does not load
        // costs only those steps, and the plan says so.
        DeployAction::Plan => {
            let (media_cfg, _ffmpeg_bin) = load_media_host_config(&resolved)?;
            let (planned, note) = match load_runtime_config(&resolved.profile) {
                Ok(config) => (
                    with_sqlite_data_contract(&resolved, &config),
                    sqlite_plan_note(&config, &resolved),
                ),
                Err(e) => (
                    resolved.clone(),
                    Some(format!(
                        "the `{}` profile config did not load, so SQLite data steps are not \
                         shown: {e}",
                        resolved.profile
                    )),
                ),
            };
            print_plan(&planned, &host_list, &media_cfg, note.as_deref());
            Ok(())
        }
        // `check`/`rollback`/`up` grade and (for `up`) upload the signing secret
        // and DB URL, so they must see those VALUES resolved under the TARGET
        // deploy profile — not the operator's ambient/dev config. Reload here.
        // `check`/`rollback` deliberately do NOT load the media config.
        DeployAction::Check => run_check(
            &load_runtime_config(&resolved.profile)?,
            &resolved,
            &targets,
            host_list.len(),
        ),
        DeployAction::Rollback => run_rollback(
            &load_runtime_config(&resolved.profile)?,
            &resolved,
            &targets,
            host_list.len(),
        ),
        // The read-only fleet surfaces (#1621). Both resolve through
        // `ResolvedFleet::resolve` — the seam that rejects a malformed/absent target
        // with one actionable message — and neither loads the media config (they
        // provision nothing).
        DeployAction::Status => {
            let fleet = ResolvedFleet::resolve(&deploy_cfg, &resolve_project_name())
                .map_err(DeployError::Config)?;
            // Review round 1: `status` is READ-ONLY and needs exactly one value
            // from the app config (`server.port`), so an unrelated invalid
            // production setting must not take it offline mid-incident. See
            // `status_public_port`.
            let port = status_public_port(&resolved)?;
            run_status(
                &port,
                &resolved.app_name,
                &resolved.profile,
                &fleet,
                options,
            )
        }
        DeployAction::MaintenanceOn | DeployAction::MaintenanceOff => {
            let fleet = ResolvedFleet::resolve(&deploy_cfg, &resolve_project_name())
                .map_err(DeployError::Config)?;
            // Review round 3: the fan-out writes the flag file each host's LIVE slot
            // unit actually polls, and deciding WHICH slot that is maps the proxy's
            // routed target port through the public port. Resolved exactly as
            // `status` resolves it — same degraded fallback — because maintenance is
            // switched mid-incident too.
            let port = status_public_port(&resolved)?;
            run_fleet_maintenance_with(
                &fleet,
                &port,
                &resolved.profile,
                action,
                options.maintenance.as_ref(),
                |cfg| {
                    exec::SshTarget::from_resolved(cfg)
                        .map(exec::SshExecutor::new)
                        .ok_or_else(|| DeployError::Config(DEPLOY_HOST_MISSING_DETAIL.to_owned()))
                },
            )
        }
        DeployAction::Up => {
            let (media_cfg, ffmpeg_bin) = load_media_host_config(&resolved)?;
            run_up(
                &load_runtime_config(&resolved.profile)?,
                &resolved,
                &targets,
                host_list.len(),
                &media_cfg,
                &ffmpeg_bin,
                options,
            )
        }
    }
}

/// Load the `[media.mediamtx]` host-provisioning config and the `[media.ffmpeg]
/// bin` path from the project config, resolved **under the target deploy profile**
/// (issue #1974, Slice 7; issue #2051, Finding O).
///
/// Reads the raw project TOML and deserializes only the `[media]` subtree
/// (mirroring how `autumn-media-plugin` reads its own config), so it bypasses
/// `autumn-web`'s strict `AutumnConfig` schema and adds no dependency on the
/// plugin. Crucially it applies the **same base+profile TOML layering
/// `AutumnConfig::load()` applies to the app config** — base `autumn.toml`, then
/// the inline `[profile.<name>]` sections, then `autumn-<profile>.toml` — so a
/// profiled deploy (`prod`/`staging`) provisions `MediaMTX` from the profile's
/// `[media.mediamtx]` / `[media.ffmpeg]` (`[profile.<name>.media.*]` or
/// `autumn-<profile>.toml`) instead of the base default. Without this a
/// prod-enabled `[profile.prod.media.mediamtx]` (or `autumn-prod.toml`) would be
/// ignored and `plan`/`up` would see the disabled base config, so the release
/// boots under the target profile with no media daemon provisioned. The env-var
/// override layer (`AUTUMN_MEDIA__*`) is deliberately NOT applied here — an
/// env/interpolation-indirected value is resolved from the SERVICE'S OWN
/// environment at runtime (see [`media::ffmpeg_preflight`]'s fail-closed-honest
/// deferral), which the CLI neither has nor may guess.
///
/// A missing file (or one that cannot be read) yields the disabled default plus
/// the default `FFmpeg` path, so a project that does not use autumn-media is
/// unaffected.
///
/// **Fails closed on invalid media config.** A `[media.mediamtx]` /
/// `[media.ffmpeg]` table that is *present but does not deserialize* (a
/// wrong-typed value) **in any contributing layer** is an error, not a silent
/// fallback: the merged value carries the bad type and
/// [`media::media_host_config_from_value`] returns [`DeployError::Config`] so
/// `deploy plan`/`deploy up` abort with a clear message instead of proceeding
/// WITHOUT provisioning a media-enabled app's `MediaMTX` daemon. The disabled
/// default is reserved for the genuinely *absent* case.
fn load_media_host_config(
    resolved: &ResolvedDeployConfig,
) -> Result<(media::MediaMtxHostConfig, String), DeployError> {
    load_media_host_config_in(&manifest_project_dirs(), &resolved.profile)
}

/// Pure core of [`load_media_host_config`] over an explicit ordered search path
/// and RAW deploy-profile spelling, so the base+profile media layering is
/// unit-testable against temp dirs (mirrors [`manifest_uploads_in`]).
///
/// Builds a merged `[media]` subtree exactly as `AutumnConfig::load_with_env`
/// builds the app config (minus the env-override layer, see the caller docs):
/// base `autumn.toml` ← inline `[profile.<name>]` sections ←
/// `autumn-<profile>.toml`. The base `autumn.toml` is **optional** — an
/// absent/unreadable base skips only that layer, exactly like `load_with_env`,
/// so a deploy that keeps `[media.mediamtx] enabled = true` ONLY in
/// `autumn-<profile>.toml` (with `[deploy] host` supplied via env and no base
/// file) still resolves the profile override and provisions `MediaMTX` (Finding
/// R). When no layer contributes a `[media]` subtree the `#[serde(default)]`
/// `MediaTomlRoot` deserializes to the disabled default; a base or profile file
/// that does not parse, or a merged `[media]` subtree with a wrong-typed value,
/// is a fail-closed [`DeployError::Config`].
fn load_media_host_config_in(
    dirs: &[PathBuf],
    profile_raw: &str,
) -> Result<(media::MediaMtxHostConfig, String), DeployError> {
    // Start from an empty root and deep-merge each contributing layer in the same
    // order `AutumnConfig::load_with_env` does, so the deploy-side `[media]`
    // resolution matches the app/runtime resolution for every base/profile
    // combination. The runtime seeds `merged` with `profile_defaults_as_toml`, but
    // those smart defaults carry NO `[media]` keys, so an empty root is faithful
    // for the media subtree — an absent `[media]` deserializes to the disabled
    // default via the `#[serde(default)]` `MediaTomlRoot`. The env-override layer
    // is deliberately excluded (see the caller docs).
    let mut merged = toml::Value::Table(toml::map::Map::new());

    // Layer 3: base `autumn.toml` — OPTIONAL, exactly like `load_with_env`. A
    // missing or unreadable base skips only this layer (a project without
    // autumn-media is unaffected) but does NOT skip the profile override file
    // below; a base present-but-malformed is fail-closed.
    let base_toml: Option<toml::Value> = match first_dir_with_file(dirs, "autumn.toml") {
        Some(base_path) => match std::fs::read_to_string(&base_path) {
            Ok(base_str) => {
                let base: toml::Value = toml::from_str(&base_str).map_err(|e| {
                    DeployError::Config(format!("invalid config in {}: {e}", base_path.display()))
                })?;
                deep_merge_toml(&mut merged, base.clone());
                Some(base)
            }
            Err(_) => None,
        },
        None => None,
    };

    // Layer 4: inline `[profile.<name>]` sections in the base autumn.toml (only
    // present when the base parsed), in the runtime's alias-then-canonical merge
    // order (`production` then `prod`), so a `[profile.prod.media.mediamtx]` wins
    // over the base — matching `AutumnConfig::load_with_env`.
    let canonical = canonicalize_deploy_profile(profile_raw);
    if let Some(base) = &base_toml {
        for name in profile_inline_lookup_names(&canonical) {
            if let Some(section) = profile_section_from_base_toml(base, name) {
                deep_merge_toml(&mut merged, section);
            }
        }
    }

    // Layer 5: `autumn-<profile>.toml` (first existing in the ordered lookup wins,
    // reusing the runtime's own pure override-file name resolver so the deploy
    // reads the SAME profile file the host runtime loads).
    for name in autumn_web::config::profile_override_file_lookup_names(&canonical, profile_raw) {
        let basename = format!("autumn-{name}.toml");
        if let Some(path) = first_dir_with_file(dirs, &basename) {
            let overlay_str = std::fs::read_to_string(&path).map_err(|e| {
                DeployError::Config(format!("could not read {}: {e}", path.display()))
            })?;
            let overlay: toml::Value = toml::from_str(&overlay_str).map_err(|e| {
                DeployError::Config(format!("invalid config in {}: {e}", path.display()))
            })?;
            deep_merge_toml(&mut merged, overlay);
            break;
        }
    }

    // Deserialize the merged `[media]` subtree — fail-closed on an ill-typed value
    // in any contributing layer.
    media::media_host_config_from_value(merged).map_err(|e| {
        DeployError::Config(format!(
            "invalid [media] config for deploy profile `{profile_raw}`: {e}"
        ))
    })
}

/// Inline `[profile.<name>]` lookup names for the canonical profile, mirroring
/// `autumn-web`'s private `profile_lookup_names`: canonical profiles also pull
/// their legacy alias (`prod`→`production`,`prod`; `dev`→`development`,`dev`) so
/// a `[profile.production.media.mediamtx]` is honored for a `prod` deploy, while a
/// custom profile is looked up verbatim. Merged in list order (alias first) so the
/// canonical spelling wins — identical to the runtime. Kept a local mirror (like
/// [`canonicalize_deploy_profile`] mirrors `normalize_profile_name`) because the
/// runtime helper is private.
fn profile_inline_lookup_names(canonical: &str) -> Vec<&str> {
    match canonical {
        "prod" => vec!["production", "prod"],
        "dev" => vec!["development", "dev"],
        other => vec![other],
    }
}

/// Extract a `[profile.<name>]` table from a parsed `autumn.toml` value as a
/// standalone TOML value (mirrors `autumn-web`'s private
/// `profile_section_from_base_toml`). `None` when the section is absent.
fn profile_section_from_base_toml(base: &toml::Value, profile: &str) -> Option<toml::Value> {
    base.get("profile")
        .and_then(toml::Value::as_table)
        .and_then(|profiles| profiles.get(profile))
        .and_then(toml::Value::as_table)
        .map(|table| toml::Value::Table(table.clone()))
}

/// Deep-merge two TOML values — tables merged recursively, non-table `overlay`
/// values replace `base` (a faithful copy of `autumn-web`'s private `deep_merge`,
/// so the deploy-side media layering matches the runtime's app-config layering
/// exactly). Bounded recursion mirrors the runtime's `MAX_MERGE_DEPTH`.
fn deep_merge_toml(base: &mut toml::Value, overlay: toml::Value) {
    deep_merge_toml_depth(base, overlay, 0);
}

fn deep_merge_toml_depth(base: &mut toml::Value, overlay: toml::Value, depth: usize) {
    /// Matches `autumn-web`'s `MAX_MERGE_DEPTH`.
    const MAX_MERGE_DEPTH: usize = 16;
    if depth > MAX_MERGE_DEPTH {
        return;
    }
    let toml::Value::Table(overlay_table) = overlay else {
        return;
    };
    let Some(base_table) = base.as_table_mut() else {
        return;
    };
    for (key, overlay_val) in overlay_table {
        let is_recursive_merge =
            overlay_val.is_table() && base_table.get(&key).is_some_and(toml::Value::is_table);
        if is_recursive_merge {
            if let Some(base_val) = base_table.get_mut(&key) {
                deep_merge_toml_depth(base_val, overlay_val, depth + 1);
            }
        } else {
            base_table.insert(key, overlay_val);
        }
    }
}

/// An [`Env`] that forces `AUTUMN_ENV` to a specific deploy profile while
/// delegating every other lookup to an inner env.
///
/// [`AutumnConfig::load_with_env`] re-derives the active profile from
/// `resolve_profile_input`, which reads `AUTUMN_ENV`.
/// [`autumn_web::dotenv::os_env_with_dotenv_for_profile`] only selects the
/// `.env.<profile>` overlay — it does NOT set `AUTUMN_ENV` — so on a dev box the
/// loader would still resolve `dev` and never layer `[profile.prod]` /
/// `autumn-prod.toml`. Reporting `AUTUMN_ENV=<profile>` here makes the reload
/// resolve the target deploy profile, so profile-scoped prod values (the signing
/// secret, the DB URL) are loaded, graded, and uploaded.
struct ForcedProfileEnv<E: Env> {
    /// The deploy profile forced onto `AUTUMN_ENV`.
    profile: String,
    /// Inner env every other key delegates to (the profile-aware dotenv overlay).
    inner: E,
}

impl<E: Env> Env for ForcedProfileEnv<E> {
    fn var(&self, key: &str) -> Result<String, std::env::VarError> {
        if key == "AUTUMN_ENV" {
            return Ok(self.profile.clone());
        }
        // Report `AUTUMN_DOTENV=1` so `should_load` opts the non-dev deploy profile into
        // `.env.<profile>` loading. The operator explicitly ran `autumn deploy` to gather
        // and upload the target profile's config, and `.env.<profile>` is a documented
        // place for profile-only values, so the deploy-time reload reads it without the
        // operator exporting `AUTUMN_DOTENV` by hand. This mutates neither the global env
        // nor the deployed service's runtime, and the profile-selector-key exclusion in
        // the overlay still strips `AUTUMN_ENV`/`AUTUMN_PROFILE`/`AUTUMN_IS_DEBUG` from
        // any `.env` file.
        //
        // Synthesize `1` only when the inner env has no explicit value: an operator
        // running `AUTUMN_DOTENV=0 autumn deploy ...` is deliberately opting out, and
        // `should_load` honors `0`/`false` as the documented off switch (see dotenv.rs).
        // So delegate to the inner env when it provides `AUTUMN_DOTENV`, preserving an
        // explicit value, and fall back to `1` only when it is unset.
        if key == "AUTUMN_DOTENV" {
            return self
                .inner
                .var("AUTUMN_DOTENV")
                .or_else(|_| Ok("1".to_owned()));
        }
        self.inner.var(key)
    }
}

/// Reload the deploy config under the TARGET deploy profile.
///
/// The chicken-and-egg here: the ambient load in [`run`] learns the deploy
/// profile (`resolved.profile`), and this reload then resolves the full config
/// under it. Takes the RAW profile string rather than the whole
/// [`ResolvedDeployConfig`] — that field is all this needs, and issue #2267's
/// alert path reloads by profile alone, with no `ResolvedDeployConfig` at
/// hand. The `.env.<profile>` overlay is selected via
/// [`autumn_web::dotenv::os_env_with_dotenv_for_profile_using`], fed a
/// [`ForcedProfileEnv`] gating base that reports `AUTUMN_DOTENV=1` so a non-dev
/// deploy profile still loads `.env.<profile>` (dotenv auto-load is otherwise
/// gated off outside `dev`/`test`). The overlay is selected by the CANONICAL
/// profile ([`canonicalize_deploy_profile`]) so a `[deploy] profile` alias like
/// `production` still reads `.env.prod` (matching `AutumnConfig::load()`), not
/// `.env.production`. A second [`ForcedProfileEnv`] wrapper forces `AUTUMN_ENV`
/// to the RAW profile so the loader layers `[profile.<profile>]` /
/// `autumn-<profile>.toml` on top with the operator's exact spelling. Real OS
/// env vars still win over `.env` (the
/// overlay only fills gaps), and the dotenv profile-selector-key exclusion still
/// strips `AUTUMN_ENV`/`AUTUMN_PROFILE`/`AUTUMN_IS_DEBUG` from any `.env` file,
/// matching `AutumnConfig::load()`.
fn load_runtime_config(profile: &str) -> Result<AutumnConfig, DeployError> {
    let forced = deploy_profile_env_overlay(profile)?;
    // Lenient unknown top-level roots (#2063): keep strict validation of the
    // core sections the CLI knows while accepting plugin-owned roots (e.g.
    // `[media]`) as opaque — app boot stays the authoritative strict gate.
    AutumnConfig::load_with_env_lenient_unknown_roots(&forced)
        .map_err(|e| DeployError::Config(e.to_string()))
}

/// The public port `autumn deploy status` probes each host against, plus the
/// reason it had to be resolved the hard way (issue #1621, review round 1).
#[derive(Debug, Clone, PartialEq, Eq)]
struct StatusPort {
    /// The port `[server] port` resolves to under the TARGET deploy profile.
    port: u16,
    /// `None` on the normal path (the whole runtime config validated). `Some` when
    /// the config did NOT validate under the deploy profile and the port was read
    /// from the layered TOML/env without validation — the caller must say so out
    /// loud rather than report against a silently-chosen port.
    degraded: Option<String>,
}

/// Resolve the probe port for `deploy status` WITHOUT making an unrelated
/// application-config error take the fleet's only read-only incident command
/// offline (issue #1621, review round 1).
///
/// `status` needs exactly one value from the application config: `server.port`,
/// the public port kamal-proxy binds — the number every per-host slot port is
/// derived from and the one the proxy-port-mismatch drift rule compares against.
/// Routing that through [`load_runtime_config`] validated the ENTIRE config under
/// the deploy profile, so an invalid `[scheduler]`, `[mail]`, `[database]` or
/// `[security]` setting aborted the command **before a single host was probed** —
/// exactly when an operator needs to see the fleet.
///
/// The strict load stays the primary path, so a project whose config is fine gets
/// byte-identical behaviour and the identical port. Only when it fails does this
/// fall back to reading the DECLARED port out of the same base+profile TOML layers
/// (plus the same `.env.<profile>`/OS env layer) the loader itself resolves it
/// from, and it reports the degradation. It never guesses: the fallback value is
/// the operator's own declared port, or the framework default when nothing
/// declares one.
///
/// `check`, `rollback` and `up` deliberately keep the strict load: they grade and
/// upload runtime VALUES (the signing secret, the DB URL), so an invalid config
/// must stop them. `plan` never loads the runtime config at all.
fn status_public_port(resolved: &ResolvedDeployConfig) -> Result<StatusPort, DeployError> {
    let loaded = load_runtime_config(&resolved.profile);
    status_public_port_with(&manifest_project_dirs(), &resolved.profile, loaded)
}

/// Pure core of [`status_public_port`] over an explicit search path and an
/// already-attempted load, so both branches are unit-testable against temp dirs.
fn status_public_port_with(
    dirs: &[PathBuf],
    profile_raw: &str,
    loaded: Result<AutumnConfig, DeployError>,
) -> Result<StatusPort, DeployError> {
    match loaded {
        Ok(config) => Ok(StatusPort {
            port: config.server.port,
            degraded: None,
        }),
        Err(err) => {
            // The `.env.<profile>` + OS env layer, selected exactly as the strict
            // load selects it — so an `AUTUMN_SERVER__PORT` that only exists in
            // `.env.prod` still wins here, as it would at runtime. A `.env` that
            // cannot be read is still fatal: that is not an unrelated app setting.
            let overlay = deploy_profile_env_overlay(profile_raw)?;
            Ok(StatusPort {
                port: declared_server_port_in(dirs, profile_raw, &overlay)
                    .unwrap_or_else(|| AutumnConfig::default().server.port),
                degraded: Some(err.to_string()),
            })
        }
    }
}

/// Read the DECLARED `[server] port` for a deploy profile without validating (or
/// even fully deserializing) the application config (issue #1621, review round 1).
///
/// Layers exactly as [`load_media_host_config_in`] does — base `autumn.toml` ←
/// inline `[profile.<name>]` ← `autumn-<profile>.toml` — because that is the same
/// order `AutumnConfig::load_with_env` merges them in, and then applies the env
/// layer ON TOP, because `AUTUMN_SERVER__PORT` is the highest-priority layer in the
/// loader too. So the number returned here is the number the strict load would
/// have produced, minus the validation.
///
/// `None` means no layer declares a port; the caller substitutes the framework
/// default rather than inventing one. A malformed/unreadable layer is skipped
/// rather than fatal: this function runs only on the already-degraded path, where
/// refusing again would leave `deploy status` just as unavailable as before.
fn declared_server_port_in(dirs: &[PathBuf], profile_raw: &str, env: &dyn Env) -> Option<u16> {
    // Highest layer first: `apply_env_overrides` applies `AUTUMN_SERVER__PORT`
    // last, so it wins over every TOML layer. An unparseable value is ignored for
    // the same reason the loader ignores it (it warns and keeps the layered value).
    if let Ok(raw) = env.var("AUTUMN_SERVER__PORT")
        && let Ok(port) = raw.trim().parse::<u16>()
    {
        return Some(port);
    }

    let mut merged = toml::Value::Table(toml::map::Map::new());
    let base_toml: Option<toml::Value> = first_dir_with_file(dirs, "autumn.toml")
        .and_then(|path| std::fs::read_to_string(path).ok())
        .and_then(|text| toml::from_str::<toml::Value>(&text).ok());
    let canonical = canonicalize_deploy_profile(profile_raw);
    if let Some(base) = &base_toml {
        deep_merge_toml(&mut merged, base.clone());
        for name in profile_inline_lookup_names(&canonical) {
            if let Some(section) = profile_section_from_base_toml(base, name) {
                deep_merge_toml(&mut merged, section);
            }
        }
    }
    for name in autumn_web::config::profile_override_file_lookup_names(&canonical, profile_raw) {
        let Some(path) = first_dir_with_file(dirs, &format!("autumn-{name}.toml")) else {
            continue;
        };
        if let Ok(text) = std::fs::read_to_string(&path)
            && let Ok(overlay) = toml::from_str::<toml::Value>(&text)
        {
            deep_merge_toml(&mut merged, overlay);
        }
        break;
    }

    merged
        .get("server")
        .and_then(|server| server.get("port"))
        .and_then(toml::Value::as_integer)
        .and_then(|port| u16::try_from(port).ok())
}

/// Build the profile-aware env overlay that [`load_runtime_config`] resolves the
/// deploy config under — the `.env.<profile>` overlay plus a forced
/// `AUTUMN_ENV` — WITHOUT loading [`AutumnConfig`].
///
/// `profile_raw` is the operator's trimmed RAW `[deploy] profile` spelling (as
/// stored on [`ResolvedDeployConfig::profile`] by [`trimmed_deploy_profile`]).
/// The `.env.<profile>` overlay is selected by the CANONICAL profile
/// ([`canonicalize_deploy_profile`]) so a `[deploy] profile` alias like
/// `production`/`PROD` still reads `.env.prod` (matching `AutumnConfig::load()`),
/// while the returned [`ForcedProfileEnv`] forces `AUTUMN_ENV` to the RAW
/// spelling so the loader layers `[profile.<profile>]` / `autumn-<profile>.toml`
/// under the operator's exact profile name, and reports `AUTUMN_DOTENV=1` so a
/// non-dev deploy profile still loads `.env.<profile>`.
///
/// `doctor` reuses this so its deploy secret/DB value graders resolve under the
/// `[deploy] profile` EXACTLY like `autumn deploy check` — same overlay
/// selection and same forced profile — rather than replicating (and risking
/// drift from) the layering.
///
/// # Errors
/// Returns [`DeployError::Config`] when a project-root `.env` file exists but
/// cannot be read or parsed.
// `pub(crate)`: reachable from `doctor`, kept crate-internal. In this bin-only
// crate `deploy` is a private module, so clippy flags the `pub(crate)` as
// redundant; we keep it to document the intended visibility.
#[allow(clippy::redundant_pub_crate)]
pub(crate) fn deploy_profile_env_overlay(profile_raw: &str) -> Result<impl Env, DeployError> {
    use autumn_web::config::OsEnv;
    // Gating base: the real OS env, but reports `AUTUMN_DOTENV=1` so
    // `should_load` loads `.env.<profile>` for a non-dev deploy profile —
    // without mutating the global process environment.
    let gating = ForcedProfileEnv {
        profile: profile_raw.to_owned(),
        inner: OsEnv,
    };
    // Select the `.env.<profile>` overlay by the CANONICAL profile, so a
    // `[deploy] profile` alias like `production`/`PROD` still picks the same
    // `.env.prod` file that `AutumnConfig::load()` reads after profile
    // normalization — not `.env.production`/`.env.PROD`. Only the dotenv-overlay
    // SELECTION is canonicalized; `AUTUMN_ENV` and the TOML override-file
    // precedence (handled by `load_with_env`) still see the RAW spelling below.
    let dotenv_profile = canonicalize_deploy_profile(profile_raw);
    let inner = autumn_web::dotenv::os_env_with_dotenv_for_profile_using(&gating, &dotenv_profile)
        .map_err(|e| DeployError::Config(e.to_string()))?;
    Ok(ForcedProfileEnv {
        profile: profile_raw.to_owned(),
        inner,
    })
}

/// Resolve the project's package name (for the `app_name` default), falling back
/// to the current directory name and finally to `"app"`.
fn resolve_project_name() -> String {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    crate::release::read_project_name(&cwd)
        .ok()
        .or_else(|| {
            cwd.file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .filter(|n| !n.is_empty())
        })
        .unwrap_or_else(|| "app".to_owned())
}

/// Resolve the first *writable* database URL a deploy/migration would actually
/// act on, honoring shard-only deployments.
///
/// `autumn migrate` only ever targets a writable primary: the control
/// `primary_url`/`url`, or — for a shard-only app (one or more
/// `[[database.shards]]` with no control primary) — each shard's `primary_url`
/// (see `migrate::build_targets`). It never migrates against
/// `database.replica_url`. The DB-URL preflight must agree, so it returns the
/// first writable URL that resolves (control primary → first shard primary);
/// replicas are excluded because `autumn migrate` cannot migrate against a
/// replica. The grader never prints the value, so surfacing a shard URL here is
/// safe.
fn resolve_writable_db_url(db: &autumn_web::config::DatabaseConfig) -> Option<&str> {
    db.effective_primary_url()
        .or_else(|| db.shards.first().map(|shard| shard.primary_url.as_str()))
}

/// The release-relative `SQLite` data-file path this deploy must keep persistent,
/// or `None` when there is none (issue #1909).
///
/// Only the [`SqliteDataFile::Relative`] case needs relocating. An absolute path
/// already survives a release swap, but is still carried through as
/// [`SqliteDataPlacement::Persistent`] so the deploy can verify on the HOST that
/// it is outside the releases dir — a symlinked `app_dir` defeats the local
/// lexical check (#2589 item 13). A refused configuration is caught by
/// [`grade_sqlite_data_persistence`] before any remote command runs.
fn sqlite_data_placement(
    config: &AutumnConfig,
    resolved: &ResolvedDeployConfig,
) -> SqliteDataPlacement {
    match classify_sqlite_data_file(resolve_writable_db_url(&config.database), resolved) {
        SqliteDataFile::Relative(rel) => SqliteDataPlacement::Relative(rel),
        SqliteDataFile::Persistent(path) => SqliteDataPlacement::Persistent(path),
        // A refused config never reaches the op builders: preflight fails first.
        SqliteDataFile::NotSqlite | SqliteDataFile::Refused(_) => SqliteDataPlacement::None,
    }
}

/// Attach the `SQLite` data-file contract to `resolved` (issue #1909).
///
/// `up`, `rollback` and `plan` all call this, so the plan shows the same data
/// steps the deploy runs (#2589 item 5). A Postgres app gets no change.
fn with_sqlite_data_contract(
    resolved: &ResolvedDeployConfig,
    config: &AutumnConfig,
) -> ResolvedDeployConfig {
    resolved
        .clone()
        .with_release_payloads(release_payload_basenames(config, resolved))
        .with_sqlite_data_placement(sqlite_data_placement(config, resolved))
}

/// The reason preflight refuses the `SQLite` database, for `deploy plan`.
/// `None` when it is not refused.
fn sqlite_plan_note(config: &AutumnConfig, resolved: &ResolvedDeployConfig) -> Option<String> {
    match classify_sqlite_data_file(resolve_writable_db_url(&config.database), resolved) {
        SqliteDataFile::Refused(reason) => Some(reason),
        SqliteDataFile::NotSqlite | SqliteDataFile::Relative(_) | SqliteDataFile::Persistent(_) => {
            None
        }
    }
}

/// How a `SQLite` app's configured data file relates to the deploy layout
/// (issue #1909).
///
/// See [`classify_sqlite_data_file`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SqliteDataFile {
    /// Not a `SQLite` app — nothing to persist.
    NotSqlite,
    /// A relative path, which resolves inside the release dir. The deploy keeps
    /// the real file under `shared/data` and links each release at this path.
    Relative(String),
    /// An absolute path the deploy does not manage — outside the app dir, or in
    /// its persistent `shared/`. Already release-independent, so the deploy
    /// leaves it exactly where the operator put it.
    Persistent(String),
    /// A configuration a deploy cannot make durable. Carries the operator-facing
    /// reason.
    Refused(String),
}

/// Classify the writable database URL a deploy would ship (issue #1909).
///
/// Each refusal names a configuration whose data cannot survive a deploy.
/// Preflight catches it before any remote command runs, not after the first
/// cutover.
#[must_use]
pub fn classify_sqlite_data_file(url: Option<&str>, cfg: &ResolvedDeployConfig) -> SqliteDataFile {
    let Some(url) = url.map(str::trim).filter(|u| !u.is_empty()) else {
        return SqliteDataFile::NotSqlite;
    };
    if autumn_web::config::DatabaseBackend::detect(url)
        != Some(autumn_web::config::DatabaseBackend::Sqlite)
    {
        return SqliteDataFile::NotSqlite;
    }
    let Some(path) = autumn_web::replication::database_file(url) else {
        return SqliteDataFile::Refused(
            "the configured SQLite database is IN-MEMORY, so it cannot survive a deploy \
             (or a restart). Point `[database] url` at a file, e.g. \
             sqlite:///srv/autumn/<app>/shared/data/app.db"
                .to_owned(),
        );
    };
    // A deploy addresses paths as text — in a systemd unit, in a shell line — so
    // one it cannot render is one it cannot ship. `file:app%FF.db` decodes to such
    // a name.
    let Some(raw) = path.to_str().map(str::to_owned) else {
        return SqliteDataFile::Refused(format!(
            "the configured SQLite database path ({}) is not valid UTF-8, so a deploy \
             cannot address it. Rename the file.",
            path.display()
        ));
    };
    // Normalize BEFORE any containment check: a lexical prefix compare on
    // `/srv/app/shared/../releases/r1/app.db` would call it durable, while the
    // kernel resolves it into `releases/`, where retention deletes it.
    let text = lexically_normalized(&raw);
    let app_dir = lexically_normalized(&cfg.app_dir);
    // FAIL CLOSED on the one input that makes every rule below undecidable: a
    // non-absolute app dir. It gates BOTH branches, not just the absolute one.
    //
    // For an absolute database it decided containment, and falling through
    // graded a file under `releases/` durable while retention deletes it. For a
    // RELATIVE database it decides the link TARGET: `sqlite_data_link_op` points
    // the release at `{app_dir}/shared/data/<file>`, so a relative `app_dir`
    // makes that target resolve beneath the release dir instead of the SSH
    // working directory, and the migration opens a dangling link (#2589 item
    // 16). One guard, above the split, because the answer is the same on both
    // sides — placing it on one branch only is what left the other open.
    if !app_dir.starts_with('/') {
        return SqliteDataFile::Refused(format!(
            "the deploy's app directory ({}) is not an absolute path, so where the \
             SQLite database {text} would live cannot be decided. Set `[deploy] \
             app_dir` to an absolute path.",
            cfg.app_dir
        ));
    }
    if text.starts_with('/') {
        // Anything the deploy itself manages is transient — `releases/` is
        // replaced every deploy and pruned by retention, and `current` is just a
        // symlink into it. Only `shared/` survives, so only `shared/` is a
        // durable place inside the app dir. A path outside the app dir is the
        // operator's own and is left alone.
        //
        // `app_dir` is normalized too, not just the database path: `[deploy]
        // app_dir = "/srv/autumn/tmp/../myapp"` names the same directory as
        // `/srv/autumn/myapp`, and comparing the raw spelling would miss a
        // database sitting in the releases dir it resolves to.
        // `shared/data`, not all of `shared/`. `shared/` survives a release swap,
        // but the deploy OWNS it: `autumn.env`, `live-slot`, `previous-release`,
        // `proxy-options`, `last-deploy`, the maintenance flag and the adoption
        // marker are all written there, and a database configured at one of those
        // paths is truncated by the deploy that writes it —
        // `sqlite:///…/shared/autumn.env` passed every containment check and was
        // then overwritten by `write-env` before the migration.
        //
        // A closed namespace rather than a list of reserved names: enumerating
        // the control files would have to be revisited every time one is added,
        // which is the failure mode this whole grader keeps hitting.
        let shared_data = lexically_normalized(&cfg.shared_data_dir());
        if within(&text, &app_dir) && !within(&text, &shared_data) {
            return SqliteDataFile::Refused(format!(
                "the configured SQLite database {text} lives inside the deploy's own app \
                 directory ({app_dir}), where only {} is yours: `releases/` is replaced on \
                 every deploy and deleted by release retention, `current` is a symlink into \
                 it, and the rest of `shared/` holds deploy state files that would \
                 overwrite the database. Move the file to {}, or outside {app_dir} \
                 altogether.",
                cfg.shared_data_dir(),
                cfg.shared_data_dir()
            ));
        }
        return SqliteDataFile::Persistent(text);
    }
    // A relative path is resolved against the slot unit's `WorkingDirectory`,
    // which is the release dir. Normalization above already removed `.` and
    // resolved `..`; what is left must still name a file INSIDE the release dir,
    // so a leading `..` (which normalization keeps, having nothing to cancel it
    // against) and an empty path are both refused.
    //
    // This lexical normalization matches `SQLite`, not the kernel. The unix VFS
    // normalizes the name before `open(2)`, so `data/nested/../app.db` opens
    // `data/app.db` even when `data/nested` does not exist. `link-data` creates
    // only `release/data` because of that. Check this again for a platform or a
    // VFS that does not normalize lexically (#2589).
    if text.is_empty() || text == ".." || text.starts_with("../") {
        return SqliteDataFile::Refused(format!(
            "the configured SQLite database path {text:?} does not name a file inside the \
             release directory it is resolved against, so a deploy cannot keep it durable. \
             Use a plain relative name (sqlite://app.db) or an absolute path."
        ));
    }
    // The data link is created BEFORE the release payloads are uploaded, and
    // `scp` writes THROUGH a symlink. So a relative database whose path is also a
    // payload path has its link made first and is then truncated by the upload —
    // the migration finds an ELF or a TOML file where the database was, after the
    // data is already gone (#2589 item 11). Refused here, before any remote
    // command runs, rather than detected on the host after the loss.
    if let Some(payload) = collides_with_release_payload(&text, cfg) {
        return SqliteDataFile::Refused(format!(
            "the configured SQLite database {text} is also a file this deploy uploads \
             into the release directory ({payload}), which would overwrite the database \
             on the first deploy. Rename the database, or move it under a \
             subdirectory (sqlite://data/app.db)."
        ));
    }
    SqliteDataFile::Relative(text)
}

/// The release payload a relative `SQLite` data file collides with, if any.
///
/// Two sources, deliberately: the names this particular deploy would upload
/// ([`ResolvedDeployConfig::release_payloads`]), plus a filesystem-independent
/// rule for the app binary and the `autumn*.toml` manifest family. The second is
/// not redundant — the payload list is empty for a bare
/// [`ResolvedDeployConfig::resolve`], and a database named `autumn.toml` must be
/// refused even on a project that has no `autumn.toml` YET, since adding one
/// later would start truncating it.
fn collides_with_release_payload(text: &str, cfg: &ResolvedDeployConfig) -> Option<String> {
    // The FIRST path component, not the whole path. Every payload is written flat
    // in the release root, but `scp <local> <release>/myapp` with a DIRECTORY at
    // `<release>/myapp` writes *into* it — so `sqlite://myapp/myapp` has
    // `link-data` create `myapp/` and put the database link at `myapp/myapp`,
    // which is exactly where the upload then lands, following the link and
    // replacing the database with the binary. Requiring the whole path to equal a
    // payload missed that entirely (a single component is just the one-segment
    // case of this rule).
    let text = text.split('/').next().filter(|c| !c.is_empty())?;
    if text == cfg.app_name {
        return Some(format!("the {} binary", cfg.app_name));
    }
    // `rsplit_once`, not `ends_with(".toml")`: the latter trips clippy's
    // case-insensitive-extension lint, and folding case would be wrong anyway —
    // the uploader always writes the lowercase spelling, and the target is POSIX.
    let is_manifest = text == "autumn.toml"
        || (text.starts_with("autumn-")
            && text.len() > "autumn-.toml".len()
            && text.rsplit_once('.').is_some_and(|(_, ext)| ext == "toml"));
    if is_manifest {
        return Some(format!("the config manifest {text}"));
    }
    cfg.release_payloads
        .iter()
        .find(|payload| payload.as_str() == text)
        .map(|payload| format!("the uploaded file {payload}"))
}

/// Collapse `.` and `..` lexically, and normalize separators.
///
/// Deliberately a STRING walk, not `std::path`: the path names a file on the
/// deploy TARGET, which is always a POSIX host, while `std::path` follows the
/// host this CLI runs on. On Windows `Path::new("/var/lib/app.db").is_absolute()`
/// is false, so every containment rule below would grade a Linux absolute path as
/// a relative one — `autumn deploy check` from a Windows workstation would
/// misjudge the target it is about to deploy to.
///
/// Lexical, not `canonicalize`: this process cannot stat the target. That is
/// enough for the containment rules — it closes the `shared/../releases` hole —
/// and a symlink on the host that defeats it would defeat any check made here.
///
/// Collapsing `..` is safe here because `SQLite` collapses it too, in its own
/// VFS, BEFORE calling `open(2)`. The deploy therefore links only the collapsed
/// path — `data/nested/../app.db` creates `data`, not `data/nested` — and the app
/// still opens the file the deploy linked. Raw `open(2)` would NOT: POSIX
/// resolution needs `data/nested` to exist. So this is load-bearing on `SQLite`'s
/// behaviour, not the kernel's. Re-check it before supporting a VFS that does not
/// normalize lexically.
///
/// Total: every path normalizes. An absolute path cannot climb out (POSIX
/// defines `/..` as `/`), and a relative one keeps a leading `..` for the caller
/// to refuse. The old `Option` implied a failure mode that does not exist, and
/// the caller's `unwrap_or_default()` on it graded a database durable.
fn lexically_normalized(path: &str) -> String {
    let absolute = path.starts_with('/');
    let mut names: Vec<&str> = Vec::new();
    for segment in path.split('/') {
        match segment {
            // An empty segment is a repeated or trailing `/`.
            "" | "." => {}
            ".." => {
                // A leading `..` on a RELATIVE path has nothing to cancel and is
                // kept, so the caller can refuse it.
                //
                // On an ABSOLUTE path it is simply dropped: POSIX defines `/..`
                // as `/`, so `/../srv/app` names `/srv/app` and cannot escape.
                // Returning `None` here instead made a real `app_dir` spelling
                // ungradable, and the caller then graded a database in the
                // releases dir as durable while retention deletes it.
                if names.last().is_some_and(|name| *name != "..") {
                    names.pop();
                } else if !absolute {
                    names.push("..");
                }
            }
            name => names.push(name),
        }
    }
    let joined = names.join("/");
    if absolute {
        format!("/{joined}")
    } else {
        joined
    }
}

/// Whether `path` is `root` itself or sits under it. Compares whole path
/// components, so `/srv/app/releases-archive` is not "under" `/srv/app/releases`.
fn within(path: &str, root: &str) -> bool {
    let root = root.trim_end_matches('/');
    path == root || path.starts_with(&format!("{root}/"))
}

/// Preflight grader for `SQLite` data-file durability (issue #1909).
///
/// Only emitted for a `SQLite` app, so a Postgres deploy's preflight report is
/// unchanged.
#[must_use]
pub fn grade_sqlite_data_persistence(
    url: Option<&str>,
    cfg: &ResolvedDeployConfig,
) -> Option<PreflightCheck> {
    match classify_sqlite_data_file(url, cfg) {
        SqliteDataFile::NotSqlite => None,
        SqliteDataFile::Relative(rel) => Some(PreflightCheck::pass(
            "sqlite_data_file",
            format!(
                "SQLite data file kept in {}/{rel} across releases",
                cfg.shared_data_dir()
            ),
        )),
        SqliteDataFile::Persistent(path) => Some(PreflightCheck::pass(
            "sqlite_data_file",
            format!("SQLite data file {path} is outside the releases directory"),
        )),
        SqliteDataFile::Refused(detail) => Some(PreflightCheck::fail(
            "sqlite_data_file",
            detail,
            "Set `[database] url` to a path a deploy can keep: a plain relative name \
             (sqlite://app.db, kept under the app's shared/data dir) or an absolute path \
             outside the releases directory",
        )),
    }
}

/// Collect all preflight graders for the resolved config against the loaded
/// runtime configuration.
///
/// Exactly ONE of the four graders is host-specific (`ssh_reachability`); the
/// other three grade the project, not the target. The split is made explicit by
/// [`collect_project_preflight`] so a fleet can run the host grader per host and
/// the project graders once ([`collect_fleet_preflight`]) without re-deriving —
/// and so a single-host run keeps this exact order and text.
fn collect_preflight(
    config: &AutumnConfig,
    resolved: &ResolvedDeployConfig,
) -> Vec<PreflightCheck> {
    let mut checks = vec![grade_ssh_reachability(
        resolved.host.as_deref(),
        resolved.ssh_port,
        SSH_PROBE_TIMEOUT,
    )];
    checks.extend(collect_project_preflight(config, resolved));
    checks
}

/// The preflight graders that are fleet-wide by nature: they grade the project's
/// signing secret, database URL and pending migrations, none of which vary per
/// host. A fleet runs these ONCE (issue #1621, AC-7).
fn collect_project_preflight(
    config: &AutumnConfig,
    resolved: &ResolvedDeployConfig,
) -> Vec<PreflightCheck> {
    // A `[database]` is considered configured when any connection URL is set on
    // the loaded config (primary/compat `url`, a replica-only role, or any
    // `[[database.shards]]` entry). Combined with the migrations-dir presence
    // check inside `grade_database_url`, this marks the app as database-backed
    // so a missing URL fails preflight — while a DB-free app (no URLs, no
    // shards, no migrations) passes.
    let database_configured = config.database.url.is_some()
        || config.database.primary_url.is_some()
        || config.database.replica_url.is_some()
        || config.database.has_shards();
    let mut checks = vec![
        // Grade the signing secret against the SAME profile that will be written
        // to the host env file (`AUTUMN_ENV=<resolved.profile>`, default `prod`),
        // not the local CLI runtime profile (`config.profile`, dev/None on a dev
        // box). Otherwise a weak/demo secret passes preflight locally but the
        // uploaded unit boots under `prod` and exits in
        // `fail_fast_on_invalid_signing_secret` — failing the deploy only AFTER
        // touching the host. Keeping the grader and env-file profile coherent
        // catches the weak secret locally, before any remote call.
        grade_signing_secret(
            config.security.signing_secret.secret.as_deref(),
            &config.security.signing_secret.previous_secrets,
            // `resolved.profile` holds the operator's trimmed RAW spelling (so the
            // AUTUMN_ENV value preserves override-file precedence). Normalize it to
            // the canonical profile only here, for grading, so `PROD`/`Production`/
            // ` production ` are still held to the production strength rules.
            is_production_profile(Some(&canonicalize_deploy_profile(&resolved.profile))),
        ),
        grade_database_url(
            resolve_writable_db_url(&config.database),
            Path::new(MIGRATIONS_DIR),
            database_configured,
            requires_database_pool(config),
        ),
        // Grade migrations against the backend of the SAME profile that will run
        // them on the host, for the reason spelled out for the signing secret
        // above: a project whose prod profile is SQLite and whose dev profile is
        // Postgres would otherwise have its production migrations graded by
        // Postgres rules. `config` is already the reloaded TARGET-profile config
        // (see `reload_config_for_deploy_profile`), so it is the one source that
        // sees `.env.<profile>` — where a production URL often lives — and no
        // separate detection can match it. Same URL the `database_url` grader
        // below reads.
        grade_migrate_check_for(
            resolve_writable_db_url(&config.database)
                .and_then(autumn_web::config::DatabaseBackend::detect)
                .unwrap_or(autumn_web::config::DatabaseBackend::Postgres),
            Path::new(MIGRATIONS_DIR),
        ),
    ];
    // Only a SQLite app gets this row, so a Postgres deploy's report is
    // byte-identical to pre-#1909.
    checks.extend(grade_sqlite_data_persistence(
        resolve_writable_db_url(&config.database),
        resolved,
    ));
    checks
}

/// Preflight for a whole fleet: `ssh_reachability` **per host**, then the three
/// project-wide graders **once** (issue #1621, AC-7).
///
/// A single-host fleet returns exactly [`collect_preflight`]'s vector, so its
/// report is byte-identical to pre-#1621 (AC-1). For a real fleet each per-host row
/// additionally carries [`PreflightCheck::scope`], so `report_preflight` can render
/// `✅ ssh_reachability (web-2): …` without the grader NAME — a `doctor --json`
/// contract — ever becoming host-specific.
///
/// **No fleet grader ever returns `deferred`** (plan §5.3, pinned by
/// `no_fleet_preflight_grader_returns_deferred`): `report_preflight` treats deferred
/// as a non-blocking warning while doctor maps it to a hard `Fail`, so a deferring
/// fleet grader would make `doctor --strict` reject a config `deploy check` accepts.
/// These graders pass or they fail.
///
/// The probes run SERIALLY here: they are a bounded TCP connect each, the report
/// must come out in declaration order, and threading them would put a `Sync` bound
/// on machinery the `RefCell`-based recording fake cannot satisfy. Parallelising
/// the pure TCP graders is a later, isolated change.
fn collect_fleet_preflight(
    config: &AutumnConfig,
    fleet: &ResolvedFleet,
    configured_host_count: usize,
) -> Vec<PreflightCheck> {
    let Some(shared) = fleet.hosts.first() else {
        // A fleet with no entries at all (#2274). `ResolvedFleet::from_targets` keeps a
        // `None`-host entry rather than dropping it, so an unconfigured `[deploy]`
        // reaches the arm below and reports `ssh_reachability` normally, leaving this
        // arm unreachable today. It still must not return no checks: this function is
        // the fail-fast boundary — `run_up`, `run_check`, and `run_rollback` all abort
        // on the count it produces — and zero checks reads as "0 failed", walks the run
        // past that boundary, and leaves the `fleet.hosts[0]` sites downstream to panic
        // on an empty vec. `hosts` is a `pub` field, so the non-empty promise in its doc
        // comment is not a type: the gate fails closed, in the same words the
        // single-host path uses.
        return vec![grade_ssh_reachability(None, 0, SSH_PROBE_TIMEOUT)];
    };
    if is_single_host_deploy(fleet, configured_host_count) {
        return collect_preflight(config, shared);
    }
    let mut checks: Vec<PreflightCheck> = fleet
        .hosts
        .iter()
        .map(|cfg| {
            grade_ssh_reachability(cfg.host.as_deref(), cfg.ssh_port, SSH_PROBE_TIMEOUT)
                // Scope only ever names a host in a REAL fleet — the single-host
                // branch above returns before this point.
                .scoped(cfg.host.clone())
        })
        .collect();
    checks.extend(collect_project_preflight(config, shared));
    checks
}

/// Whether the active profile is production, matching the exact rule the app boot
/// path uses in `fail_fast_on_invalid_signing_secret`
/// (`matches!(config.profile.as_deref(), Some("prod" | "production"))`).
#[must_use]
// `pub(crate)` (not `pub`): reachable from `doctor` for deploy-profile grading
// but kept crate-internal. See the note on `canonicalize_deploy_profile` re: the
// clippy allow (private module in a bin-only crate).
#[allow(clippy::redundant_pub_crate)]
pub(crate) fn is_production_profile(profile: Option<&str>) -> bool {
    matches!(profile, Some("prod" | "production"))
}

/// Whether any enabled runtime feature requires a configured Postgres pool at
/// startup, mirroring the exact backend conditions the runtime enforces:
/// - `jobs.backend = "postgres"` → `job::start_postgres_runtime` calls
///   `state.pool().ok_or(...)` and errors without a pool.
/// - `scheduler.backend = "postgres"` → `scheduler::coordinator_from_config`
///   calls `state.pool().ok_or(...)` and errors without a pool.
/// - `jobs.backend = "sqlite"` / `scheduler.backend = "sqlite"` → the durable
///   `SQLite` queue and the lease table live in the app's own database, so both
///   error without a pool too (issue #1907).
///
/// Cache, channels, and idempotency have only in-memory/Redis backends (no
/// database variant), so they never require a DB pool and are deliberately not
/// included here.
#[must_use]
fn requires_database_pool(config: &AutumnConfig) -> bool {
    matches!(config.jobs.backend.as_str(), "postgres" | "sqlite")
        || matches!(
            config.scheduler.backend,
            autumn_web::config::SchedulerBackend::Postgres
                | autumn_web::config::SchedulerBackend::Sqlite
        )
}

/// The label a preflight line leads with: the stable grader name, plus the fleet
/// host in parentheses when the check is scoped (issue #1621, plan §5.2).
///
/// Pure so the fleet rendering rule is testable without capturing stderr. An
/// unscoped check (every check in a single-host deploy, and every project-wide
/// grader in a fleet) renders as the bare name — byte-identical to pre-#1621.
fn preflight_label(check: &PreflightCheck) -> String {
    check.scope.as_ref().map_or_else(
        || check.name.to_owned(),
        |scope| format!("{} ({scope})", check.name),
    )
}

/// Print each preflight check as a pass/fail line and return the failure count.
/// Shared by `check` and `up` so both surfaces report graders identically.
fn report_preflight(checks: &[PreflightCheck]) -> usize {
    let mut failed = 0_usize;
    for check in checks {
        let label = preflight_label(check);
        if check.passed {
            eprintln!("\u{2705} {label}: {}", check.detail);
        } else if check.deferred {
            // Non-blocking: verified in the service's own runtime, not here.
            // Surfaced as a warning so it is visible but never aborts the deploy.
            eprintln!("\u{26A0}\u{FE0F}  {label}: {}", check.detail);
            if let Some(hint) = check.hint {
                eprintln!("   \u{2192} {hint}");
            }
        } else {
            failed += 1;
            eprintln!("\u{274C} {label}: {}", check.detail);
            if let Some(hint) = check.hint {
                eprintln!("   \u{2192} {hint}");
            }
        }
    }
    eprintln!();
    failed
}

/// Refuse the rollout if any preflight check failed (issue #1621, AC-7).
///
/// `run_up` calls this right after `collect_fleet_preflight`, before it
/// builds any executor. A failing host stops the rollout before it
/// touches a server. Split into its own function so a test can drive
/// this exact decision with no disk and no network (issue #2269).
fn refuse_if_preflight_failed(checks: &[PreflightCheck]) -> Result<(), DeployError> {
    let failed = report_preflight(checks);
    if failed > 0 {
        return Err(DeployError::PreflightFailed(failed));
    }
    Ok(())
}

/// Run the preflight over EVERY configured host and report it (issue #1621, AC-7).
///
/// `hosts` is the ordered target list from [`deploy_host_list`]. With more than one
/// entry the per-host `ssh_reachability` grader runs once per host — so an
/// unreachable host in position 3 is named before any host is touched — and the
/// three project-wide graders run once. With at most one entry this is the
/// pre-#1621 single-host report verbatim, down to the absent `scope` suffix (AC-1;
/// proved by `deploy_check_output_is_identical_for_host_and_a_single_entry_hosts_list`).
///
/// Also prints the same config-manifest notice `deploy up` prints (#1952
/// check/up parity) — a confirmation naming the manifest(s) that will be
/// uploaded, or a loud warning when there is no local `autumn.toml` at all.
/// Purely informational: it is not one of the graded `checks` and never
/// affects the failure count or exit code.
fn run_check(
    config: &AutumnConfig,
    resolved: &ResolvedDeployConfig,
    hosts: &[String],
    configured_host_count: usize,
) -> Result<(), DeployError> {
    eprintln!("\u{1F342} autumn deploy check\n");

    let fleet = ResolvedFleet::from_targets(resolved, hosts);
    let checks = collect_fleet_preflight(config, &fleet, configured_host_count);
    let failed = report_preflight(&checks);

    // Mirror `deploy up`'s config-manifest signal here too (#1952 check/up
    // parity): `check` is the documented way to catch a broken deploy BEFORE
    // touching the server, so an operator running only `check` must see the same
    // "no autumn.toml found" warning (or upload confirmation) `up` would print,
    // not discover it only once `up` actually runs. Purely informational — it
    // never affects `failed`/the exit code, exactly like `up` never blocks on it.
    eprintln!(
        "{}",
        manifest_preflight_notice(&locate_manifest_uploads(resolved))
    );

    if failed == 0 {
        eprintln!("\u{2705} All {} preflight check(s) passed.", checks.len());
        Ok(())
    } else {
        eprintln!(
            "\u{274C} {failed} of {} preflight check(s) failed.",
            checks.len()
        );
        Err(DeployError::PreflightFailed(failed))
    }
}

/// Print the `deploy plan` dry-run: the rendered slot unit, the ordered per-host
/// steps, the fleet rollout section (multi-host only), and the `MediaMTX` section
/// (media-enabled only).
///
/// `hosts` is the ordered target list from [`deploy_host_list`] — the rollout
/// order. When it holds at most one entry, nothing fleet-specific is printed, so
/// single-host output stays byte-identical to pre-#1621 (AC-1); the differential
/// proof is `deploy_plan_output_is_identical_for_host_and_a_single_entry_hosts_list`.
fn print_plan(
    resolved: &ResolvedDeployConfig,
    hosts: &[String],
    media_cfg: &media::MediaMtxHostConfig,
    sqlite_note: Option<&str>,
) {
    println!("\u{1F342} autumn deploy plan (dry-run)\n");
    println!("systemd unit ({}.service):\n", resolved.service_name);
    println!("{}", render_systemd_unit(resolved));

    println!("Deploy steps (zero-downtime):");
    for (i, step) in build_deploy_plan(resolved).iter().enumerate() {
        println!("  {}. [{}] {}", i + 1, step.label, step.description);
    }
    if let Some(note) = sqlite_note {
        println!("\n  SQLite data file: {note}");
    }

    // Fleet rollout (issue #1621, AC-4): the steps above are what EACH host runs;
    // this section is the order they run in and where the single fleet-wide
    // migration lands. Printed only for a real fleet.
    if hosts.len() > 1 {
        for line in fleet::fleet_plan_lines(hosts) {
            println!("{line}");
        }
    }

    // MediaMTX host provisioning (issue #1974, Slice 7): only when the
    // `[media.mediamtx]` section is enabled — a non-media deploy prints nothing
    // new here.
    if media_cfg.enabled {
        print_media_plan(media_cfg);
    }
}

/// Print the `MediaMTX` host-provisioning section of `deploy plan` — the rendered
/// systemd unit, the ordered provisioning ops, and the CSP origins the app must
/// allow. Pure output; runs nothing.
fn print_media_plan(media_cfg: &media::MediaMtxHostConfig) {
    let controller = media::MediaMtxController::new(media_cfg.clone());
    println!(
        "\nMediaMTX host provisioning (media unit {}.service):\n",
        media_cfg.unit_name
    );
    println!("{}", media::render_mediamtx_unit(media_cfg));
    if media_cfg.install_binary {
        println!(
            "Before cutover: [media-install-binary] installs MediaMTX {} at {} if nothing \
             is there (pinned image digest).",
            media::MEDIAMTX_KNOWN_GOOD_VERSION,
            media_cfg.binary_path,
        );
    }
    println!("MediaMTX provisioning steps:");
    for (i, op) in controller.ensure_installed_ops().iter().enumerate() {
        println!("  {}. [{}]", i + 1, op.label());
    }
    println!(
        "\nMediaMTX doctor checks at `deploy up`: {}, {}, {}, {}, {}, {}",
        media::CHECK_MEDIAMTX_PORTS_DISTINCT,
        media::CHECK_MEDIAMTX_PORTS_MATCH_BASES,
        media::CHECK_FFMPEG_PREFLIGHT,
        media::CHECK_MEDIAMTX_BINARY,
        media::CHECK_RECORDINGS_DIR_WRITABLE,
        media::CHECK_MEDIAMTX_PORTS_AVAILABLE,
    );
    println!(
        "CSP: the app must allow these MediaMTX origins in connect-src/media-src \
         (frame-src for WebRTC): {}",
        media_cfg.required_csp_origins().join(", "),
    );
}

/// Grade the media host with the fail-closed, **non-mutating** doctor checks
/// (`FFmpeg` preflight, `MediaMTX` binary, recordings dir writable/creatable,
/// ports distinct/available, ports matching the app's base URLs) and abort the
/// deploy on any **blocking** failure — so a
/// host that cannot serve media fails fast BEFORE the app deploy touches
/// anything. A **deferred** check (an env/interpolation-indirected
/// `[media.ffmpeg] bin` the deployed service resolves from its own runtime
/// environment) is surfaced as a warning and does **not** abort — the service
/// resolves `FFmpeg` at runtime, so blocking the deploy here would be wrong,
/// while a concrete literal `FFmpeg` path that is missing/not-executable still
/// fails closed (see [`media::ffmpeg_preflight`] and
/// [`PreflightCheck::blocking`]). A no-op when `[media.mediamtx]` is not enabled.
/// This writes and restarts nothing; the mutating provisioning is deferred to
/// [`provision_media_host`], which runs only after the app cutover succeeds.
fn check_media_host_preflight(
    media_cfg: &media::MediaMtxHostConfig,
    ffmpeg_bin: &str,
    executor: &impl exec::DeployExecutor,
) -> Result<(), DeployError> {
    if !media_cfg.enabled {
        return Ok(());
    }
    eprintln!("\u{1F3A5} media host preflight (autumn-media)\n");

    let checks = media::collect_media_doctor_checks(executor, media_cfg, ffmpeg_bin);
    let failed = report_preflight(&checks);
    if failed > 0 {
        return Err(DeployError::PreflightFailed(failed));
    }
    Ok(())
}

/// Provision `MediaMTX` as a systemd unit over the live executor — write the
/// rendered `mediamtx.yml` + unit and enable/restart the service (issue #1974,
/// Slice 7). A no-op when `[media.mediamtx]` is not enabled.
///
/// **Runs only AFTER the app deploy/cutover has fully succeeded.** The app deploy
/// rolls back on failure (readiness-gate miss, migration failure) and leaves the
/// OLD release serving; there is deliberately no media teardown restoring the
/// previous `mediamtx.yml`, so mutating (and possibly restarting) the host
/// `MediaMTX` unit BEFORE the app is committed would strand a rolled-back release
/// against a media daemon whose ports/recording-paths/matchers just moved.
/// Deferring the mutation until the deploy is committed means a failed/rolled-back
/// app deploy never writes or restarts `MediaMTX`. The non-mutating doctor checks
/// already ran up front in [`check_media_host_preflight`].
fn provision_media_host(
    media_cfg: &media::MediaMtxHostConfig,
    executor: &impl exec::DeployExecutor,
) -> Result<(), DeployError> {
    if !media_cfg.enabled {
        return Ok(());
    }
    eprintln!("\u{1F3A5} provisioning MediaMTX host (autumn-media)\n");

    let controller = media::MediaMtxController::new(media_cfg.clone());
    exec::run_ops(&controller.ensure_installed_ops(), executor)
        .map_err(|e| DeployError::Exec(e.to_string()))?;
    eprintln!(
        "\u{2705} MediaMTX provisioned ({}.service)",
        media_cfg.unit_name
    );
    Ok(())
}

/// The pre-cutover ops that install the pinned `MediaMTX` binary (#1974).
///
/// Empty unless `[media.mediamtx]` is enabled with `install_binary = true`.
/// The op skips a host that already has an executable at `binary_path`.
fn media_binary_install_ops(media_cfg: &media::MediaMtxHostConfig) -> Vec<exec::DeployOp> {
    media::MediaMtxController::new(media_cfg.clone()).binary_install_ops()
}

/// Build the secret env-file body sourced by the systemd unit's
/// `EnvironmentFile`. Emits the runtime profile selector (`AUTUMN_ENV`, from the
/// resolved `[deploy] profile`, default `prod`) so the deployed app never
/// silently boots under the `dev` fallback, alongside the values the app needs
/// at runtime (the signing secret and the writable database URL). The result is
/// wrapped in [`exec::Secret`] so it is never logged (AC-5). The profile is a
/// plain non-secret value; secret handling is unchanged.
fn build_env_file(config: &AutumnConfig, resolved: &ResolvedDeployConfig) -> exec::Secret {
    let mut body = String::new();
    body.push_str("AUTUMN_ENV=");
    body.push_str(&resolved.profile);
    body.push('\n');
    if let Some(secret) = config
        .security
        .signing_secret
        .secret
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        body.push_str("AUTUMN_SECURITY__SIGNING_SECRET=");
        body.push_str(secret);
        body.push('\n');
    }
    if let Some(url) = resolve_writable_db_url(&config.database) {
        body.push_str("AUTUMN_DATABASE__URL=");
        body.push_str(url);
        body.push('\n');
    }
    exec::Secret::new(body)
}

/// Resolve the local path to the pre-built release binary this deploy uploads.
///
/// Slice 1 does NOT rebuild from source — it uploads the standalone binary
/// produced by `autumn build --embed` at `target/release/{app_name}`, failing
/// with an actionable error when it is missing.
fn resolve_release_binary(resolved: &ResolvedDeployConfig) -> Result<PathBuf, DeployError> {
    let path = PathBuf::from("target")
        .join("release")
        .join(&resolved.app_name);
    if path.exists() {
        Ok(path)
    } else {
        Err(DeployError::BinaryMissing(path.display().to_string()))
    }
}

/// Deterministic-per-second release id used to name the timestamped release dir.
/// Nondeterministic by design in production; tests inject a fixed id instead
/// through [`exec::first_deploy_ops`].
fn default_release_id() -> String {
    chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string()
}

/// Resolve the ordered local project directories the deploy reads config from.
///
/// Mirrors autumn-web's `find_config_file_named`, which is a *per-file*
/// manifest-dir-then-CWD fallback: `{AUTUMN_MANIFEST_DIR}/{file}` wins when it
/// exists, otherwise `{file}` relative to the CWD. So when `AUTUMN_MANIFEST_DIR`
/// is set we return `[manifest_dir, cwd]` (a file absent from the manifest dir
/// falls back to the CWD copy, exactly as the runtime would load it); when it is
/// unset we return `[cwd]` — the project root the rest of the deploy already
/// treats as authoritative (the release binary is resolved as
/// `target/release/<app>`).
fn manifest_project_dirs() -> Vec<PathBuf> {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    if let Ok(dir) = std::env::var("AUTUMN_MANIFEST_DIR")
        && !dir.trim().is_empty()
    {
        let manifest_dir = PathBuf::from(dir);
        if manifest_dir == cwd {
            return vec![cwd];
        }
        return vec![manifest_dir, cwd];
    }
    vec![cwd]
}

/// First directory in `dirs` that holds `filename` as a regular file — the
/// deploy-side mirror of the runtime's `find_config_file_named` per-file
/// manifest-dir-then-CWD fallback.
fn first_dir_with_file(dirs: &[PathBuf], filename: &str) -> Option<PathBuf> {
    dirs.iter().map(|d| d.join(filename)).find(|p| p.is_file())
}

/// Locate the RAW project config manifest file(s) to upload for #1952: the base
/// `autumn.toml` plus, when present, the profile-override sibling
/// `autumn-<profile>.toml` for the target deploy profile.
///
/// Pure over the passed `dirs`/`profile` so it is unit-testable against temp
/// dirs. We upload the raw files (NOT a flattened/merged config) because the app
/// applies its `[profile.<AUTUMN_ENV>]` overlay at runtime — `AUTUMN_ENV` is already
/// set in the uploaded env file — so shipping the raw manifest(s) preserves the
/// profile structure and matches the repo exactly.
///
/// The sibling lookup reuses the runtime's own pure profile helpers
/// (`autumn_web::config::normalize_profile_name` +
/// `profile_override_file_lookup_names`) so the deploy picks the SAME
/// `autumn-<profile>.toml` the host runtime will load — a single source of truth
/// prevents drift. The ordered lookup list is first-existing-wins (e.g.
/// `[deploy] profile = "Production"` prefers `autumn-production.toml` over
/// `autumn-prod.toml`, matching the runtime). `dirs` is the ordered
/// manifest-dir-then-CWD search path from [`manifest_project_dirs`]; each file is
/// resolved against it with the same per-file fallback the runtime's
/// `find_config_file_named` applies.
fn manifest_uploads_in(dirs: &[PathBuf], profile: &str) -> Vec<exec::ManifestUpload> {
    let mut uploads = Vec::new();

    if let Some(base) = first_dir_with_file(dirs, "autumn.toml") {
        uploads.push(exec::ManifestUpload {
            local: base,
            remote_basename: "autumn.toml".to_owned(),
        });
    }

    // Mirror the runtime: normalize the raw profile, then walk the ordered
    // override-file lookup names and upload the FIRST that exists locally (under
    // its own name), exactly as the host runtime loads the first that exists and
    // stops. Empty profile falls back to the deploy default `"prod"` (matching
    // `canonicalize_deploy_profile` / `default_deploy_profile`).
    let normalized =
        autumn_web::config::normalize_profile_name(profile).unwrap_or_else(|| "prod".to_owned());
    for name in autumn_web::config::profile_override_file_lookup_names(&normalized, profile) {
        let basename = format!("autumn-{name}.toml");
        if let Some(local) = first_dir_with_file(dirs, &basename) {
            uploads.push(exec::ManifestUpload {
                local,
                remote_basename: basename,
            });
            break;
        }
    }

    // The capacity contract the deployed config points at (#1733). Without
    // this the release ships an `autumn.toml` naming a `capacity_contract`
    // that is not there, the remote load fails, and — because contract
    // failures deliberately fall open — the advertised admission control is
    // silently absent on exactly the deploy path the guide recommends.
    if let Some(configured) = configured_capacity_contract(dirs, profile) {
        // `ManifestUpload` places every file flat in the release directory,
        // but the uploaded config still names the path it was written with. A
        // `contracts/prod.lock` uploaded as `prod.lock` would therefore be
        // missing at the path the app looks in — the same silent fall-open
        // this block exists to prevent. Ship only a contract that already sits
        // beside the manifest; anything nested is left to the operator, loudly.
        if Path::new(&configured)
            .parent()
            .is_some_and(|p| p != Path::new(""))
        {
            eprintln!(
                "\u{26A0}\u{FE0F}  warning: [server] capacity_contract is '{configured}', which is \
                 not beside autumn.toml.\n   The release directory is flat, so this file is NOT \
                 uploaded and the deployed app will\n   fall back to unlimited admission. Move the \
                 contract next to autumn.toml, or ship it\n   yourself as part of your release."
            );
        } else if let Some(local) = first_dir_with_file(dirs, &configured) {
            uploads.push(exec::ManifestUpload {
                local,
                remote_basename: configured,
            });
        }
    }

    uploads
}

/// `[server] capacity_contract` as the deployed config will see it.
///
/// Layers exactly as the runtime does — base `autumn.toml`, then the inline
/// `[profile.<name>]` sections of that same file, then the
/// `autumn-<profile>.toml` sibling — reusing the same helpers the media-host
/// resolution already mirrors. Getting this wrong is not cosmetic: a contract
/// configured only under `[profile.prod.server]` would be left out of the
/// release while the deployed runtime still resolves it, and admission control
/// would fall open with no signal.
///
/// A key present but empty clears the setting, matching the env override.
fn configured_capacity_contract(dirs: &[PathBuf], profile: &str) -> Option<String> {
    // The base file is OPTIONAL, exactly as it is for the runtime loader: a
    // deployment may legitimately ship only `autumn-prod.toml`. Requiring it
    // here would skip the contract for such a deployment while
    // `manifest_uploads_in` still uploaded the profile file that references
    // it — the config would name a contract that is not in the release, and
    // admission would fall open.
    let mut merged = first_dir_with_file(dirs, "autumn.toml")
        .and_then(|path| std::fs::read_to_string(path).ok())
        .and_then(|text| toml::from_str::<toml::Value>(&text).ok())
        .unwrap_or_else(|| toml::Value::Table(toml::map::Map::new()));

    let canonical =
        autumn_web::config::normalize_profile_name(profile).unwrap_or_else(|| "prod".to_owned());

    // Inline `[profile.<name>]` overlays from the base file, alias first so the
    // canonical spelling wins — identical to the runtime.
    for name in profile_inline_lookup_names(&canonical) {
        if let Some(section) = profile_section_from_base_toml(&merged.clone(), name) {
            deep_merge_toml(&mut merged, section);
        }
    }

    // Then the first existing `autumn-<profile>.toml` sibling.
    for name in autumn_web::config::profile_override_file_lookup_names(&canonical, profile) {
        if let Some(local) = first_dir_with_file(dirs, &format!("autumn-{name}.toml")) {
            if let Ok(text) = std::fs::read_to_string(&local)
                && let Ok(overlay) = toml::from_str::<toml::Value>(&text)
            {
                deep_merge_toml(&mut merged, overlay);
            }
            break;
        }
    }

    merged
        .get("server")
        .and_then(|server| server.get("capacity_contract"))
        .and_then(toml::Value::as_str)
        .filter(|value| !value.is_empty())
        .map(str::to_owned)
}

/// Locate the config manifest(s) to upload for the resolved deploy, reading from
/// the local project directories ([`manifest_project_dirs`]).
fn locate_manifest_uploads(resolved: &ResolvedDeployConfig) -> Vec<exec::ManifestUpload> {
    manifest_uploads_in(&manifest_project_dirs(), &resolved.profile)
}

/// Every basename this deploy writes into the release directory (#2589 item 11).
///
/// The app binary plus the uploaded manifests — including a capacity contract
/// under whatever name the config gives it, which no static rule could predict.
/// `collides_with_release_payload` refuses a relative `SQLite` data file that
/// matches one, because the data link is made first and `scp` writes through it.
///
/// `config` is unused today and taken anyway: it is the value that decides the
/// manifest set, and threading it now keeps the signature honest if the payload
/// list ever stops being derivable from `resolved` alone.
fn release_payload_basenames(
    _config: &AutumnConfig,
    resolved: &ResolvedDeployConfig,
) -> Vec<String> {
    let mut names = vec![resolved.app_name.clone()];
    names.extend(
        locate_manifest_uploads(resolved)
            .into_iter()
            .map(|upload| upload.remote_basename),
    );
    names
}

/// Format the operator-facing preflight line for the config-manifest upload
/// (#1952). Pure/testable: either a LOUD no-manifest warning (kills the previous
/// silent-defaults footgun) or a confirming line naming the uploaded file(s).
fn manifest_preflight_notice(uploads: &[exec::ManifestUpload]) -> String {
    if uploads.is_empty() {
        return "\u{26A0}\u{FE0F}  warning: no autumn.toml found in the project directory; the \
                deployed app will run built-in defaults for all non-secret settings (secrets \
                still come from the env file). Add an autumn.toml to control the deployed \
                configuration."
            .to_owned();
    }
    let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
    format!(
        "Uploading project config to the release dir: {}",
        names.join(", ")
    )
}

/// Perform a real deploy (issue #1607, Slices 1–3).
///
/// Runs the same preflight as `check` and aborts before touching the server if
/// anything fails (AC-6). It then probes the target ([`exec::probe_deploy_state`])
/// to choose between:
///
/// - **first deploy** ([`exec::first_deploy_ops`]) — install the reverse proxy on
///   the public port and stand the initial release up on a private loopback slot
///   behind it, or
/// - **zero-downtime redeploy** ([`exec::cutover_ops`]) — stand the candidate up
///   on the idle slot, run migrations before cutover, gate on `/ready`, then have
///   the proxy flip live traffic to it and drain the old release (AC-2/AC-3).
///
/// Either path carries a [`exec::candidate_teardown_ops`] plan so a failure
/// before go-live auto-rolls-back the candidate (AC-4): a redeploy leaves the old
/// release serving ([`exec::execute_redeploy`]); a first deploy has no previous
/// release and fails loudly after tearing the candidate down
/// ([`exec::execute_first_deploy`]).
/// The HTTPS port kamal-proxy binds by default (and cannot disable). A
/// public/HTTP port — or a blue/green slot port derived from it — equal to this
/// collides with the always-bound HTTPS listener.
const PROXY_HTTPS_PORT: u16 = 443;

/// Reject a deploy public/HTTP port that cannot work with the proxy topology.
///
/// One guard runs here, before any remote work, and it is **unconditional** (it
/// does not depend on whether TLS is enabled): kamal-proxy `run` binds its
/// `--https-port 443` listener by DEFAULT and that listener cannot be disabled,
/// and each blue/green slot binds a private loopback port derived from the
/// public port ([`exec::slot_app_port`]: blue = `public + 1`, green =
/// `public + 2`). If the proxy's HTTP port *or* either slot port lands on 443 it
/// collides with the always-bound HTTPS listener and the proxy can never start.
/// With blue/green at `+1`/`+2`, that rejects `public ∈ {441, 442, 443}`.
///
/// There is deliberately **no** TLS-gated port-80 requirement: per-app TLS is
/// provisioned by kamal-proxy on its always-bound 443 via `deploy --host --tls`
/// (TLS-ALPN-01, no port 80 needed), so enabling `[deploy.tls]` works on any
/// non-colliding public port — on both first deploy and redeploy — without a
/// proxy HTTP-port change.
fn validate_public_port(public_port: u16) -> Result<(), String> {
    // No port (proxy HTTP or a blue/green slot) may land on 443. Compute the slot
    // ports from the same offsets the deploy uses so the guard tracks the real
    // arithmetic instead of a hardcoded {441, 442, 443} set.
    let blue_port = exec::slot_app_port(public_port, exec::SLOT_BLUE);
    let green_port = exec::slot_app_port(public_port, exec::SLOT_GREEN);
    let collision = if public_port == PROXY_HTTPS_PORT {
        Some("the proxy's HTTP listener")
    } else if blue_port == PROXY_HTTPS_PORT {
        Some("the blue app slot")
    } else if green_port == PROXY_HTTPS_PORT {
        Some("the green app slot")
    } else {
        None
    };
    if let Some(which) = collision {
        return Err(format!(
            "deploy public/HTTP port {public_port} is invalid — {which} would land on \
             {PROXY_HTTPS_PORT}, which kamal-proxy reserves for its HTTPS listener \
             (blue/green app slots bind `public+1`/`public+2`); use 80 (the default) or \
             another port outside {}\u{2013}{PROXY_HTTPS_PORT}",
            PROXY_HTTPS_PORT - 2,
        ));
    }
    Ok(())
}

/// Detect a concurrent `server.port` change on the **redeploy** path, BEFORE any op
/// runs (issue #2073, Option C).
///
/// The reboot-durability upgrade (#2070) makes every redeploy refresh the shared
/// kamal-proxy unit and, when that unit changed, restart `kamal-proxy run` and
/// re-register the still-live upstream. Both the restart's public bind and the
/// re-register's DERIVED loopback target are correct ONLY when computed from the
/// port the live release was ACTUALLY deployed under — so a detected change must
/// resolve to a [`exec::PublicPortMove`] the caller threads through every op
/// (phases 1-3 run against `old_port`, never `new_port`) rather than a value that
/// silently drifts mid-cutover.
///
/// The comparison is sourced from the INSTALLED proxy unit's `--http-port` (captured
/// by [`exec::probe_deploy_state`]), which is the ground truth of what the running
/// proxy actually binds:
///
///   - [`exec::InstalledProxyPort::Absent`] → no installed unit, i.e. a first-deploy
///     shape (the durability refresh writes it fresh at the requested port).
///     Nothing to move → `Ok(None)`. (This branch only runs when `current` is a
///     symlink, so this is the rare shape where the proxy unit is missing but a
///     release symlink exists.)
///   - [`exec::InstalledProxyPort::Port`] equal to the requested port → unchanged
///     redeploy (the common durability-upgrade path) → `Ok(None)`.
///   - [`exec::InstalledProxyPort::Port`] DIFFERENT from the requested port →
///     `Ok(Some(PublicPortMove { old_port, new_port }))`.
///   - [`exec::InstalledProxyPort::Unreadable`] → the unit is present but its
///     `--http-port` couldn't be read/parsed, so we can't prove which port (if any)
///     needs moving → **fail closed** (refuse) rather than risk a mid-cutover bind
///     failure.
fn resolve_public_port_move(
    installed: &exec::InstalledProxyPort,
    new_public_port: u16,
) -> Result<Option<exec::PublicPortMove>, String> {
    match installed {
        // No installed proxy unit — first-deploy shape; the durability refresh writes
        // it fresh at the requested port, so there is nothing to move.
        exec::InstalledProxyPort::Absent => Ok(None),
        // Unchanged public port — the common redeploy / durability-upgrade path.
        exec::InstalledProxyPort::Port(current) if *current == new_public_port => Ok(None),
        exec::InstalledProxyPort::Port(old_port) => Ok(Some(exec::PublicPortMove {
            old_port: *old_port,
            new_port: new_public_port,
        })),
        // Fail closed: the unit is present but its --http-port is unreadable, so we
        // cannot prove whether the public port needs moving — refuse rather than risk
        // the durability restart rebinding the wrong port and stranding `:80`.
        exec::InstalledProxyPort::Unreadable => Err(format!(
            "Cannot verify the installed kamal-proxy's HTTP port before a redeploy \
             (its systemd unit is present but its `--http-port` could not be read), so \
             a concurrent server.port change (config requests {new_public_port}) cannot \
             be ruled out and is refused to avoid stranding public traffic mid-cutover. \
             Re-provision the host (or repair the kamal-proxy unit) and retry."
        )),
    }
}

/// Pre-flight refuse for an UNPROVABLE `shared/proxy-options` marker on the redeploy
/// path (issue #2074), mirroring [`resolve_public_port_move`]'s `Unreadable`
/// fail-closed arm.
///
/// The durability-refresh re-register (#2070/#2071) re-registers the still-live OLD
/// release; #2074 preserves that release's own TLS/host by reading them back from the
/// `shared/proxy-options` marker. When the marker is:
///
///   - [`exec::ProxyOptionsMarker::Options`] → the old options are known → preserve
///     them (no refuse);
///   - [`exec::ProxyOptionsMarker::Absent`] → a legacy host (or first deploy) that
///     never wrote the marker → **allowed**: proceed as legacy (re-register with the
///     new config and write the marker this deploy — see the redeploy arm). Refusing
///     here would block the FIRST redeploy of every pre-existing host, the deadlock
///     #2074 explicitly rejects;
///   - [`exec::ProxyOptionsMarker::Unreadable`] → the marker is present but its
///     `{tls}\t{host}` value couldn't be parsed, so the old options can't be proved →
///     **fail closed** (refuse): a concurrent `deploy.tls.host` change can't be safely
///     preserved across the one-time restart, and stamping the wrong host onto the
///     live release on a rollback is worse than refusing.
fn refuse_unprovable_proxy_options(marker: &exec::ProxyOptionsMarker) -> Result<(), String> {
    match marker {
        exec::ProxyOptionsMarker::Absent | exec::ProxyOptionsMarker::Options(_) => Ok(()),
        exec::ProxyOptionsMarker::Unreadable => Err(
            "Cannot verify the last-deployed proxy TLS/host options before a redeploy \
             (the shared/proxy-options marker is present but unreadable), so a concurrent \
             deploy.tls.host change cannot be preserved across the one-time reboot-durability \
             restart and is refused to avoid stranding the live release behind the wrong \
             TLS/host on a rollback. Redeploy with deploy.tls unchanged to repair the marker, \
             then change the host in a separate deploy. Tracked in #2074."
                .to_owned(),
        ),
    }
}

// ── Fleet-wide fail-closed refusals (issue #1621, §4.8) ──────────────────────
//
// All three are **pure predicates over the CONFIGURED host count**, evaluated in
// the rollout prologue before a single remote command runs, and all three are
// gated on `configured > 1` rather than on the number of hosts this run happens to
// touch: `--only` narrows a rollout, it does not change the topology that makes
// these unsafe. Each names the config key and the tracking issue, matching the
// house style of `reject_sqlite_sharding_topology` (`migrate.rs`).

/// Refuse a multi-host deploy backed by `SQLite` (issue #1621, §4.8).
///
/// `build_env_file` ships a byte-identical `AUTUMN_DATABASE__URL` to every host, so
/// a `sqlite://` URL means N independent database FILES — one per machine. There is
/// no advisory lock across them, "migrate exactly once" degenerates to "migrated on
/// exactly one host's database", and every host serves a different dataset behind
/// the same load balancer. That is data-destroying by construction, not a
/// performance footgun, so it fails closed.
fn refuse_sqlite_fleet(configured_hosts: usize, writable_db_sqlite: bool) -> Result<(), String> {
    if configured_hosts > 1 && writable_db_sqlite {
        return Err(
            "\u{2717} A multi-host deploy cannot run on SQLite. `[deploy] hosts` lists more \
             than one server and the configured `[database]` URL is a sqlite:// target, but \
             every host receives the SAME database URL — which means N independent database \
             FILES, one per machine: no shared schema, no advisory lock to serialize \
             migrations, and each host serving a different dataset behind your load \
             balancer. Point `[database] url` at a Postgres server every host can reach, or \
             deploy a single host with `[deploy] host`. Tracking: #1621."
                .to_owned(),
        );
    }
    Ok(())
}

/// Refuse a multi-host deploy with `[media.mediamtx] enabled` (issue #1621, §4.8).
///
/// `provision_media_host` runs after the cutover and has **no** teardown or
/// rollback path by design. Fanning it out would give N `MediaMTX` daemons on
/// identical ports with divergent recording sets, and nothing to undo them with
/// when the app rollout is compensated.
fn refuse_media_fleet(configured_hosts: usize, media_enabled: bool) -> Result<(), String> {
    if configured_hosts > 1 && media_enabled {
        return Err(
            "\u{2717} A multi-host deploy cannot provision MediaMTX. `[deploy] hosts` lists \
             more than one server and `[media.mediamtx] enabled = true`, but host media \
             provisioning has no teardown or rollback path: fanning it out would leave one \
             MediaMTX daemon per host on identical ports, with divergent recording sets and \
             nothing to undo them with when the app rollout is rolled back. Deploy media on \
             a single host with `[deploy] host`, or set `[media.mediamtx] enabled = false` \
             and provision the media host separately. Tracking: #1621."
                .to_owned(),
        );
    }
    Ok(())
}

/// Refuse a multi-host deploy with `[deploy.tls] enabled` (issue #1621, §4.8).
///
/// kamal-proxy is PER HOST — it binds that host's public port; it is not a fleet
/// load balancer. N hosts would each attempt ACME for the same `[deploy.tls] host`
/// from behind the operator's load balancer, only one can answer a given challenge,
/// and the rest burn Let's Encrypt failed-validation and duplicate-certificate rate
/// limits. Behind a load balancer, TLS terminates at the load balancer.
fn refuse_tls_fleet(configured_hosts: usize, tls_enabled: bool) -> Result<(), String> {
    if configured_hosts > 1 && tls_enabled {
        return Err(
            "\u{2717} A multi-host deploy cannot terminate TLS per host. `[deploy] hosts` \
             lists more than one server and `[deploy.tls] enabled = true`, but the \
             deploy-managed proxy runs on EVERY host: each one would request a certificate \
             for the same `[deploy.tls] host` from behind your load balancer, only one can \
             answer a given ACME challenge, and the rest burn Let's Encrypt \
             failed-validation and duplicate-certificate rate limits. Terminate TLS at the \
             load balancer that fronts the fleet and set `[deploy.tls] enabled = false`. \
             Tracking: #1621."
                .to_owned(),
        );
    }
    Ok(())
}

/// The loud line printed when a fleet deploys an app that auto-applies migrations
/// at boot (issue #1621, §4.8).
///
/// A **warning, not a refusal**: it is a real hazard but not a certainty, and
/// making it a refusal (or a preflight grader) would break existing single-host
/// users' scale-up and force a doctor-parity change for a rule the rollout itself
/// does not depend on.
const FLEET_AUTO_MIGRATE_WARNING: &str = "`[database] auto_migrate` is on and this deploy targets more than one host: every \
     host applies migrations at boot, so the hosts RACE each other during the rollout \
     and a checksum mismatch exits the process under `Restart=on-failure` — a crash \
     loop mid-rollout. Turn it off for fleets and let the rollout's single `migrate` \
     step own the schema (#1621).";

/// Whether the fleet must be warned about boot-time auto-migration (issue #1621,
/// §4.8) — pure.
///
/// `auto_migrate` supersedes the `auto_migrate_in_production` back-compat alias
/// (`auto_migrate` wins when set), mirroring the runtime's own resolution. The
/// alias is honoured without checking the profile: a deploy defaults to `prod`, and
/// under-warning about a crash loop is worse than over-warning.
fn fleet_auto_migrate_warning(
    configured_hosts: usize,
    auto_migrate: Option<bool>,
    auto_migrate_in_production: bool,
) -> Option<&'static str> {
    let enabled = auto_migrate.unwrap_or(auto_migrate_in_production);
    (configured_hosts > 1 && enabled).then_some(FLEET_AUTO_MIGRATE_WARNING)
}

/// The loud line printed when a fleet deploys an app whose background-work
/// backends are per-process (issue #1621, AC-8).
///
/// A **warning, not a refusal**, for the same reason as
/// [`FLEET_AUTO_MIGRATE_WARNING`] and more so: `[jobs] backend = "local"` and
/// `[scheduler] backend = "in_process"` are the DEFAULTS every un-configured app
/// runs, and they are exactly right on one host. Refusing would break every
/// existing single-host user's scale-up — the one flow AC-8's guide exists to
/// make easy — for a hazard the rollout itself does not depend on.
///
/// Composed rather than constant because it names only the key(s) that actually
/// apply; see [`fleet_shared_backend_warning`].
const FLEET_SHARED_BACKEND_WARNING_TAIL: &str = "each host then runs its OWN copy, so work enqueued on one host is only ever run by \
     that host, whatever is still queued dies when the next rollout drains that host's \
     old slot, `unique`/`concurrency` limits stop being enforced fleet-wide, and every \
     scheduled task fires once PER HOST. Move them to a shared backend (`postgres` or \
     `redis`) before you rely on background work across the fleet \u{2014} see \
     docs/guide/fleet-deploys.md (#1621).";

/// Whether the fleet must be warned that its background-work backends are
/// per-process (issue #1621, AC-8) — pure.
///
/// `jobs_backend` is compared case-insensitively after trimming, and anything that
/// is not the in-process `local` default is treated as durable: a backend this CLI
/// does not know about is the operator having configured something deliberately,
/// and over-warning them every deploy is worse than staying quiet.
///
/// Returns `None` for a single-host config — the in-process defaults are correct
/// there, and this must be silent on the byte-identical N==1 path (AC-1).
fn fleet_shared_backend_warning(
    configured_hosts: usize,
    jobs_backend: &str,
    scheduler_in_process: bool,
) -> Option<String> {
    if configured_hosts <= 1 {
        return None;
    }
    let jobs_local = jobs_backend.trim().eq_ignore_ascii_case("local");
    let keys = match (jobs_local, scheduler_in_process) {
        (true, true) => {
            "`[jobs] backend = \"local\"` (an in-process queue) and `[scheduler] \
                         backend = \"in_process\"` (a per-process timer) are in effect"
        }
        (true, false) => "`[jobs] backend = \"local\"` (an in-process queue) is in effect",
        (false, true) => {
            "`[scheduler] backend = \"in_process\"` (a per-process timer) is in effect"
        }
        (false, false) => return None,
    };
    Some(format!(
        "{keys} and this deploy targets more than one host \u{2014} they are PER HOST: \
         {FLEET_SHARED_BACKEND_WARNING_TAIL}"
    ))
}

/// Whether the resolved writable database URL names a `SQLite` backend (issue
/// #1621, §4.8).
///
/// Resolves the same URL the deploy would SHIP to every host
/// ([`resolve_writable_db_url`]) and reduces it to one bool **here**, so the URL —
/// which carries credentials — never enters the rollout driver's inputs, its
/// errors, or its output.
fn writable_db_is_sqlite(db: &autumn_web::config::DatabaseConfig) -> bool {
    resolve_writable_db_url(db).is_some_and(|url| {
        matches!(
            autumn_web::config::DatabaseBackend::detect(url),
            Some(autumn_web::config::DatabaseBackend::Sqlite)
        )
    })
}

/// Perform a real deploy of the whole configured fleet (issue #1607, Slices 1–3;
/// issue #1621).
///
/// Runs the same preflight as `check` — for EVERY configured host — and aborts
/// before touching any server if anything fails (AC-6/AC-7). It then mints ONE
/// release id for the whole run, probes every host read-only, plans the rollout,
/// and replaces the hosts ONE AT A TIME in `[deploy] hosts` order.
///
/// A single-host config is a one-host fleet: same ops, same output, same errors as
/// before #1621. The prologue here is the part that is fleet-wide by nature
/// (preflight, release id, release binary, env file, manifests, port validation);
/// everything host-shaped lives in [`run_up_with`], which takes those results as
/// data so the rollout loop is unit-testable against per-host fakes with no host,
/// no filesystem and no clock.
fn run_up(
    config: &AutumnConfig,
    resolved: &ResolvedDeployConfig,
    hosts: &[String],
    configured_host_count: usize,
    media_cfg: &media::MediaMtxHostConfig,
    ffmpeg_bin: &str,
    options: &DeployOptions,
) -> Result<(), DeployError> {
    eprintln!("\u{1F342} autumn deploy up\n");

    // Attach the SQLite data-file contract (#1909) BEFORE the fleet is built, so
    // every host's config carries it and every host links the same path. A
    // Postgres app resolves `None` and nothing below changes.
    let resolved = &with_sqlite_data_contract(resolved, config);

    // The rollout targets, in declaration order. A single-host config resolves to
    // a one-host fleet whose only element IS today's `resolved`, so everything
    // below is the pre-#1621 sequence at N = 1.
    let fleet = ResolvedFleet::from_targets(resolved, hosts);

    // Fail fast: run the full preflight and abort BEFORE any remote call. Every
    // host is graded here, so an unreachable host in position 3 is reported before
    // host 1 is touched.
    let checks = collect_fleet_preflight(config, &fleet, configured_host_count);
    refuse_if_preflight_failed(&checks)?;

    let binary = resolve_release_binary(resolved)?;
    let env_file = build_env_file(config, resolved);
    // Locate the project config manifest(s) to upload so the deployed app loads
    // the intended config rather than silent built-in defaults (#1952), and print
    // a loud line either confirming the upload or warning when there is no
    // autumn.toml to ship. The same bytes go to every host.
    let manifests = locate_manifest_uploads(resolved);
    eprintln!("{}", manifest_preflight_notice(&manifests));
    // Exactly ONE release id per fleet run (#1621): every host's `current` symlink
    // then resolves to the same release, so drift reporting is meaningful and a
    // rollback has a single target. Minting per host would give un-comparable
    // version identities and permanent reported drift.
    let release_id = default_release_id();
    let public_port = config.server.port;
    // kamal-proxy `run` binds 443 for its HTTPS listener BY DEFAULT (regardless of
    // any app's TLS flag, and it cannot be disabled), so a public/HTTP port whose
    // proxy-HTTP or blue/green slot port lands on 443 would collide and the proxy
    // would fail to start. Reject that up front with an actionable message instead
    // of a cryptic runtime bind failure on the host. TLS imposes no port-80
    // requirement — it is provisioned per app on the always-bound 443.
    validate_public_port(public_port).map_err(DeployError::Config)?;
    let proxy = proxy::KamalProxyController::new(resolved.readiness_timeout_secs)
        .with_tls_host(resolved.tls_host.clone());
    // The post-cutover bake (#3069): its limits come from `[deploy.bake]` and
    // the `[[slo]]` tables.
    let bake_policy = resolve_bake_policy(config, options.bake_secs)?;
    if let Some(policy) = &bake_policy {
        eprintln!("{}", policy.describe());
        for warning in &policy.warnings {
            eprintln!("\u{26A0}\u{FE0F}  {warning}");
        }
        eprintln!();
    }
    let metrics_path = bake::metrics_path(&config.actuator.prefix);
    let bake_host = bake::host_header(&config.security.trusted_hosts.hosts);

    run_up_with(
        &FleetUpInput {
            app_name: &resolved.app_name,
            profile: &resolved.profile,
            fleet: &fleet,
            proxy: &proxy,
            checks: &checks,
            env_file: &env_file,
            binary: &binary,
            manifests: &manifests,
            release_id: &release_id,
            public_port,
            media_cfg,
            ffmpeg_bin,
            configured_host_count,
            // Every fact is reduced to a bool HERE so the database URL (credentials
            // and all) never reaches the driver, its errors, or its output.
            db: FleetDatabaseFacts {
                sqlite: writable_db_is_sqlite(&config.database),
                auto_migrate: config.database.auto_migrate,
                auto_migrate_in_production: config.database.auto_migrate_in_production,
            },
            jobs_backend: &config.jobs.backend,
            scheduler_in_process: matches!(
                config.scheduler.backend,
                autumn_web::config::SchedulerBackend::InProcess
            ),
            // AC-3's default: a halted rollout compensates the hosts that already
            // cut over rather than leaving the fleet on two versions. `--no-rollback`
            // is halt-and-freeze: stop, report, change nothing else.
            auto_rollback: !options.no_rollback,
            bake: bake_policy.as_ref(),
            metrics_path: &metrics_path,
            bake_host: bake_host.as_deref(),
        },
        // Host presence is guaranteed by the passing ssh_reachability grader above,
        // so this `None` arm is unreachable in practice; it keeps the pre-#1621
        // error verbatim rather than panicking on an invariant proved elsewhere.
        |cfg| {
            exec::SshTarget::from_resolved(cfg)
                .map(exec::SshExecutor::new)
                .ok_or_else(|| DeployError::Config(DEPLOY_HOST_MISSING_DETAIL.to_owned()))
        },
    )
}

/// The bake policy from `[deploy.bake]`, the `[[slo]]` tables and the
/// `--bake-secs` flag (issue #3069). `None` means no bake.
fn resolve_bake_policy(
    config: &AutumnConfig,
    flag: Option<u64>,
) -> Result<Option<bake::BakePolicy>, DeployError> {
    let bake_config = config
        .deploy
        .as_ref()
        .map(|deploy| deploy.bake.clone())
        .unwrap_or_default();
    if flag.unwrap_or(bake_config.duration_secs) == 0 {
        return Ok(None);
    }
    let slos =
        autumn_web::slo::validate(&config.slo).map_err(|e| DeployError::Config(e.to_string()))?;
    // The prod profile rejects a request whose Host is not trusted, and
    // `127.0.0.1` is not trusted there. With no trusted host to send, every
    // sample would fail and every deploy would roll back.
    let prod = matches!(config.profile.as_deref(), Some("prod" | "production"));
    let hosts = &config.security.trusted_hosts.hosts;
    if prod && bake::host_header(hosts).is_none() && !hosts.iter().any(|h| h.trim() == "*") {
        return Err(DeployError::Config(
            "the bake needs a trusted host in the prod profile: add your domain to \
             [security.trusted_hosts] hosts, or turn the bake off"
                .to_owned(),
        ));
    }
    bake::resolve_policy(&bake_config, &slos, flag).map_err(DeployError::Config)
}

/// What this project's `[database]` config means for a fleet rollout (issue #1621,
/// §4.8).
///
/// Grouped rather than passed as loose flags because they answer ONE question
/// together — "what happens to the schema during this rollout?" — and because of
/// what is deliberately absent: the database URL itself. It carries credentials, so
/// every fact here is reduced to a bool at the point the URL is resolved, and the
/// rollout driver, its errors and its output can never quote it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct FleetDatabaseFacts {
    /// Whether that URL names a `SQLite` backend (the §4.8 refusal).
    sqlite: bool,
    /// `[database] auto_migrate`, verbatim (the §4.8 warning).
    auto_migrate: Option<bool>,
    /// `[database] auto_migrate_in_production` — the back-compat alias
    /// `auto_migrate` supersedes.
    auto_migrate_in_production: bool,
}

/// Everything the fleet rollout loop needs, already resolved by [`run_up`].
///
/// Every field is either fleet-wide by construction (`release_id`, `env_file`,
/// `binary`, `manifests`, `public_port` — the same bytes reach every host) or the
/// fleet itself. Passing them as data rather than re-deriving them inside the loop
/// is what makes the loop testable: nothing here reads the clock, the filesystem,
/// or a socket.
struct FleetUpInput<'a, P: ProxyController> {
    /// The app's stable name (e.g. `"myapp"`, from `Cargo.toml`). A halt
    /// alert's dedup key includes this (issue #2267), so two different apps
    /// sharing one alert destination never fold into one incident.
    app_name: &'a str,
    /// The TARGET deploy profile (e.g. `"prod"`). A halt reloads `[alerts]`
    /// under this profile (issue #2267), never the operator's ambient shell
    /// profile.
    profile: &'a str,
    /// The rollout targets, in order. Never empty.
    fleet: &'a ResolvedFleet,
    /// The proxy controller. kamal-proxy is PER HOST (it binds that host's public
    /// port); it is not a fleet load balancer, so one controller value describes
    /// every host's local proxy.
    proxy: &'a P,
    /// The preflight results the per-host executor gates on.
    checks: &'a [PreflightCheck],
    /// The secret env-file body, byte-identical on every host.
    env_file: &'a exec::Secret,
    /// Local path to the release binary uploaded to every host.
    binary: &'a Path,
    /// Config manifests uploaded into every host's release dir.
    manifests: &'a [exec::ManifestUpload],
    /// The ONE release id for this run.
    release_id: &'a str,
    /// The app's public port, fronted by each host's proxy.
    public_port: u16,
    /// `MediaMTX` host provisioning config.
    media_cfg: &'a media::MediaMtxHostConfig,
    /// Resolved `FFmpeg` binary path for the media preflight.
    ffmpeg_bin: &'a str,
    /// How many hosts the CONFIG declares, before `--only` narrowed `fleet`
    /// (issue #1621, §3.2/§4.8).
    ///
    /// Two things turn on this rather than on `fleet.hosts.len()`:
    ///
    /// - The §4.8 refusals describe a TOPOLOGY (one `SQLite` file per machine, N
    ///   `MediaMTX` daemons, N ACME clients racing for one certificate). Deploying
    ///   a subset of that topology does not make it safe, so `--only` must not be a
    ///   way to sneak past them.
    /// - The byte-identical single-host path (AC-1) is for a config that declares
    ///   ONE host — not for a three-host fleet narrowed to one. A narrowed rollout
    ///   keeps the fleet framing, the state table and the compensation semantics,
    ///   because the other two hosts still exist and are still on another release.
    configured_host_count: usize,
    /// What this project's `[database]` config means for the rollout — resolved
    /// once in the prologue, never re-read here.
    db: FleetDatabaseFacts,
    /// `[jobs] backend`, verbatim — for the per-host background-work warning
    /// (AC-8). Not a secret and not host-derived; see
    /// [`fleet_shared_backend_warning`].
    jobs_backend: &'a str,
    /// Whether `[scheduler] backend` is the per-process timer (the default), for
    /// the same warning.
    scheduler_in_process: bool,
    /// Whether a halted rollout automatically compensates the hosts that already
    /// cut over (issue #1621, §4.7). `true` in production; `false` is halt-and-freeze
    /// — the rollout stops and reports, leaving every host exactly as it is for
    /// inspection. The operator-facing `--no-rollback` flag that sets it lands with
    /// the fleet CLI surface; today it is an internal seam so the freeze path is
    /// tested, not dead.
    auto_rollback: bool,
    /// The post-cutover bake (issue #3069). `None`: no bake.
    bake: Option<&'a bake::BakePolicy>,
    /// The app's `/actuator/metrics` path, which the bake samples.
    metrics_path: &'a str,
    /// A `Host` header for the bake's metric requests, from
    /// `[security.trusted_hosts]`. The `prod` profile rejects `127.0.0.1`.
    bake_host: Option<&'a str>,
}

/// One host's read-only probe result: everything the rollout needs to know about
/// that host, decided BEFORE any host is touched.
struct HostProbeState {
    /// First deploy vs redeploy.
    mode: fleet::HostMode,
    /// That host's own blue/green slot layout.
    slots: exec::SlotPlan,
    /// Whether that host's live-slot marker drifted and must be repaired as the
    /// first op of its sequence.
    repair: bool,
    /// Proxy options the durability re-register must preserve on that host (#2074).
    reregister_options: exec::ProxyServiceOptions,
    /// Operator-facing description of the path this host takes.
    banner: String,
    /// Whether this host has no usable reverse-proxy binary and this deploy must
    /// install one as the FIRST op of that host's turn (issue #1607, AC-1).
    needs_proxy_install: bool,
    /// A concurrent `server.port` change to apply AFTER the cutover (issue #2073,
    /// Option C phase 4) — `None` on a first deploy or an unchanged redeploy port.
    port_move: Option<exec::PublicPortMove>,
}

/// Whether this host's deploy may prepare the target by installing a missing proxy
/// binary — the `[deploy] install_proxy` knob, projected onto the executor-level
/// type (issue #1607, AC-1).
const fn provisioning(cfg: &ResolvedDeployConfig) -> exec::ProxyProvisioning {
    if cfg.install_proxy {
        exec::ProxyProvisioning::Auto
    } else {
        exec::ProxyProvisioning::Disabled
    }
}

/// Probe ONE host read-only and apply every fail-closed refusal to it.
///
/// This runs for EVERY host before the first host is mutated (issue #1621, §4.3),
/// which is what makes a fleet rollout all-or-nothing at the refusal level: a
/// drifted host in position 3 refuses the rollout while hosts 1 and 2 are still
/// serving their old releases, instead of being discovered after two cutovers.
///
/// The refusals themselves are the UNCHANGED single-host guards; the only fleet
/// addition is that their messages name the host when there is more than one (a
/// single-host deploy keeps the exact pre-#1621 text).
fn probe_host_for_up<E, P>(
    cfg: &ResolvedDeployConfig,
    input: &FleetUpInput<'_, P>,
    executor: &E,
) -> Result<HostProbeState, DeployError>
where
    E: exec::DeployExecutor,
    P: ProxyController,
{
    let host = cfg.host.as_deref().unwrap_or_default();
    // The SAME question the driver asks (`is_single_host_deploy`), not
    // `fleet.is_single()`: a `--only`-narrowed repair on a multi-host fleet must
    // keep naming the host it is refusing to touch.
    let single = is_single_host_deploy(input.fleet, input.configured_host_count);
    // Host attribution is carried in the MESSAGE, never in an op label: labels are
    // `&'static str` and are load-bearing for the auto-rollback boundary lookup and
    // for every exact-vector test (#1621).
    let scoped = |message: String| {
        if single {
            message
        } else {
            format!("host {host}: {message}")
        }
    };

    // Decide whether the host has a WORKING reverse proxy (#1607 AC-1 host prep,
    // #2053 CLI-drift guard). READ-ONLY: a compatible binary passes silently, a
    // drifted one aborts here and is never replaced, and a host with none is merely
    // MARKED for preparation — the install itself is the first op of that host's own
    // turn, so this phase still mutates nothing anywhere in the fleet.
    let needs_proxy_install = matches!(
        exec::assess_proxy_readiness(input.proxy, executor, provisioning(cfg))
            .map_err(|e| DeployError::Exec(scoped(e.to_string())))?,
        exec::ProxyReadiness::NeedsInstall
    );

    // Probe the target to choose first-deploy vs zero-downtime redeploy. The same
    // round-trip also captures `kamal-proxy list` so a drifted live-slot marker
    // can be reconciled against the live proxy before slot-selection (#1938).
    let probe = exec::probe_deploy_state(cfg, executor)
        .map_err(|e| DeployError::Exec(scoped(e.to_string())))?;

    // Refuse a release-dir collision (#1621, §4.9). The release id has one-second
    // granularity, so a fast retry re-uses it; re-uploading into the dir
    // `shared/previous-release` still points at would make the "previous release"
    // hold the NEW binary and roll FORWARD on the next rollback. Nothing detects
    // that afterwards, so it is refused before anything is written.
    match exec::probe_release_dir(cfg, input.release_id, executor)
        .map_err(|e| DeployError::Exec(scoped(e.to_string())))?
    {
        exec::ReleaseDirState::Absent => {}
        exec::ReleaseDirState::Present => {
            return Err(DeployError::Config(scoped(format!(
                "release directory {}/{} already exists — a previous run of this release \
                 id already wrote into it, and re-uploading would put the NEW binary in \
                 the directory `shared/previous-release` points at (so a rollback would \
                 roll FORWARD). Wait a second and re-run `autumn deploy up`, or remove \
                 that directory if you are certain it is stale. Tracked in #1621.",
                cfg.releases_dir(),
                input.release_id,
            ))));
        }
        exec::ReleaseDirState::Unreadable => {
            return Err(DeployError::Config(scoped(format!(
                "cannot verify whether release directory {}/{} already exists (the probe \
                 returned neither sentinel), so a release-id collision cannot be ruled \
                 out and the deploy is refused rather than risk overwriting the release \
                 `shared/previous-release` points at. Tracked in #1621.",
                cfg.releases_dir(),
                input.release_id,
            ))));
        }
    }

    match probe.mode {
        exec::DeployMode::First => Ok(HostProbeState {
            mode: fleet::HostMode::from_deploy_mode(&probe.mode),
            slots: exec::SlotPlan::first(input.public_port),
            repair: false,
            // A first deploy registers the NEW config's options; there is no old
            // release whose options could need preserving.
            reregister_options: input.proxy.proxy_service_options(),
            banner: "first deploy".to_owned(),
            needs_proxy_install,
            // No installed proxy at all — nothing to move.
            port_move: None,
        }),
        exec::DeployMode::Redeploy { live_slot } => {
            // Detect a concurrent `server.port` change (#2073, Option C) BEFORE any op
            // runs, sourced from the installed proxy unit's `--http-port` captured in
            // the deploy-start probe. When present, every op through the drain of the
            // old release plans against `port_move.old_port` — the port the live
            // release was ACTUALLY deployed under — never the newly requested one; the
            // move itself is a separate, later phase (see `run_up_with`). No installed
            // unit means a first-deploy shape and resolves to `None`; an unreadable
            // unit fails closed (a move can't be proven safe).
            let port_move =
                resolve_public_port_move(&probe.installed_proxy_port, input.public_port)
                    .map_err(|message| DeployError::Config(scoped(message)))?;
            let effective_public_port = port_move.map_or(input.public_port, |m| m.old_port);
            // Pre-flight refuse (#2074): if the `shared/proxy-options` marker is present
            // but unreadable, we cannot prove the OLD release's TLS/host, so a concurrent
            // `deploy.tls.host` change can't be safely preserved across the durability
            // restart — fail closed BEFORE any op runs, so the live release keeps serving.
            refuse_unprovable_proxy_options(&probe.last_proxy_options)
                .map_err(|message| DeployError::Config(scoped(message)))?;
            // Choose the options the durability-refresh re-register carries for the
            // still-live OLD release (#2074). PRESERVE the marker's recorded options
            // when known; on an ABSENT marker fall back to the NEW config (proceed as
            // legacy — the durability-upgrade deploy's kamal-proxy table is empty, so
            // there is nothing to preserve, and refusing would deadlock every
            // pre-#2074 host's first redeploy). The marker is (re)written by
            // `cutover_ops` this deploy, so the next redeploy is fully protected. The
            // Unreadable case is already refused above, so it never reaches here.
            let reregister_options = match &probe.last_proxy_options {
                exec::ProxyOptionsMarker::Options(old) => old.clone(),
                _ => input.proxy.proxy_service_options(),
            };
            // Reconcile the (possibly stale) live-slot marker against the live proxy
            // before choosing the candidate slot — against `effective_public_port`,
            // the port the proxy is ACTUALLY installed on, so a concurrent
            // `server.port` change never makes this look for a slot the proxy never
            // registered. On an UNAMBIGUOUS proxy-vs-marker disagreement the proxy is
            // authoritative (so the candidate takes the genuinely-idle slot and never
            // restarts the live one); on any absent/unclear proxy signal this is
            // exactly the marker-based behavior as before (#1938, fail-safe).
            let reconcile = exec::reconcile_live_slot(
                live_slot,
                &probe.proxy_list,
                &cfg.service_name,
                effective_public_port,
            );
            if let Some(warn) = &reconcile.warn {
                // Loud + observable: drift is surfaced, not silently papered over.
                // (autumn-cli installs no tracing subscriber, so the deploy module
                // reports operator-facing state via eprintln! throughout.)
                eprintln!("\u{26A0}\u{FE0F}  {}", scoped(warn.clone()));
            }
            let slots = exec::SlotPlan::redeploy(effective_public_port, reconcile.live_slot);
            let mut banner = format!(
                "zero-downtime redeploy ({} \u{2192} {})",
                slots.live_slot, slots.candidate_slot
            );
            if let Some(mv) = port_move {
                banner = format!(
                    "{banner}, then moving server.port {} \u{2192} {}",
                    mv.old_port, mv.new_port
                );
            }
            Ok(HostProbeState {
                mode: fleet::HostMode::from_deploy_mode(&probe.mode),
                slots,
                repair: reconcile.repair,
                reregister_options,
                banner,
                needs_proxy_install,
                port_move,
            })
        }
    }
}

/// Drive the rollout: probe every host, plan, then replace the hosts ONE AT A TIME
/// (issue #1621, AC-2/AC-3/AC-4).
///
/// The executor factory is injected (generic, never `dyn`, and with no `Send`/`Sync`
/// bound) so a test can drive the whole loop — probe, plan, per-host execute — with
/// one scripted fake per host. Production hands it an `SshExecutor` per target.
///
/// Structure that is load-bearing rather than stylistic:
///
/// - **Every host is probed before ANY host is mutated.** All the fail-closed
///   refusals live in that phase, so a drifted host in position 3 refuses the whole
///   rollout with hosts 1 and 2 untouched.
/// - **Each host's ops are executed by their OWN `execute_*` call.** Two hosts' op
///   vectors are never concatenated: `execute_with_teardown` resolves the
///   auto-rollback boundary with the FIRST matching label, so a flat vector would
///   classify every later host's pre-flip failure as post-boundary and silently
///   disable teardown.
/// - **A failure HALTS the rollout, then compensates** (issue #1621, §4.6/§4.7).
///   Hosts after the failing one are never touched, and the hosts that already cut
///   over are rolled back in reverse order so the fleet converges on ONE version —
///   binaries only; a migration that already ran is never undone. The one exception
///   is a post-boundary HOUSEKEEPING failure (`record-proxy-options`, `drain-old`,
///   `prune`): the host is live and healthy on the new release, so the rollout
///   warns, marks it degraded, and CONTINUES. For a failed `drain-old`, the
///   driver retries one time. It continues only when the old slot stopped
///   (#2279). A rollout whose only failures are housekeeping therefore succeeds
///   (`Ok`) with degraded hosts named in the state table — rolling a whole fleet
///   back because an `rm -rf` of old release dirs failed would be a
///   self-inflicted outage.
///
/// **N = 1 is exempt from all of it.** A single-host config takes the pre-#1621
/// path verbatim: the raw executor error, no fleet vocabulary, no state table, no
/// compensation (there is no other host to converge with, and its own boundary
/// teardown already ran). That is AC-1, and it is why the `single` branches below
/// are not cosmetic. One exception (#2276): when the binaries went back after
/// `migrate`, the error gets one schema note ([`fleet::single_host_schema_note`]).
#[allow(clippy::too_many_lines)]
fn run_up_with<E, P, F>(input: &FleetUpInput<'_, P>, make_executor: F) -> Result<(), DeployError>
where
    E: exec::DeployExecutor,
    P: ProxyController,
    F: Fn(&ResolvedDeployConfig) -> Result<E, DeployError>,
{
    let fleet = input.fleet;
    // The pre-#1621 path is for a config that declares ONE host — see
    // [`FleetUpInput::configured_host_count`] for why a `--only`-narrowed fleet is
    // deliberately NOT single.
    let single = is_single_host_deploy(fleet, input.configured_host_count);
    let total = fleet.hosts.len();

    // ── FLEET-WIDE FAIL-CLOSED REFUSALS (§4.8) ───────────────────────────────
    // First thing in the driver, before an executor is even built: these describe
    // topologies that cannot be deployed safely at all, so the honest answer is to
    // refuse with zero remote commands rather than discover it after a cutover.
    refuse_sqlite_fleet(input.configured_host_count, input.db.sqlite)
        .map_err(DeployError::Config)?;
    refuse_media_fleet(input.configured_host_count, input.media_cfg.enabled)
        .map_err(DeployError::Config)?;
    // `first()` rather than `[0]`: the shared shape is identical across the fleet,
    // and an empty `hosts` — which `collect_fleet_preflight` now refuses to let a
    // run reach at all (#2274) — must still surface as the missing-host config
    // error every other hostless path returns, never as an index panic.
    let shared = fleet
        .hosts
        .first()
        .ok_or_else(|| DeployError::Config(DEPLOY_HOST_MISSING_DETAIL.to_owned()))?;
    refuse_tls_fleet(input.configured_host_count, shared.tls_enabled)
        .map_err(DeployError::Config)?;
    // A warning, not a refusal: hosts racing to auto-migrate at boot is a real
    // hazard but not a certainty, and refusing would break an existing single-host
    // user's scale-up.
    if let Some(warning) = fleet_auto_migrate_warning(
        input.configured_host_count,
        input.db.auto_migrate,
        input.db.auto_migrate_in_production,
    ) {
        eprintln!("\u{26A0}\u{FE0F}  {warning}\n");
    }
    // Same rule, same reason (AC-8): the in-process job queue and scheduler are
    // the DEFAULTS every un-configured app runs and are correct on one host, so a
    // fleet is warned rather than refused.
    if let Some(warning) = fleet_shared_backend_warning(
        input.configured_host_count,
        input.jobs_backend,
        input.scheduler_in_process,
    ) {
        eprintln!("\u{26A0}\u{FE0F}  {warning}\n");
    }

    // ONE executor per host, built up front and reused for that host's read-only
    // probe AND its execution.
    let executors = fleet
        .hosts
        .iter()
        .map(&make_executor)
        .collect::<Result<Vec<E>, DeployError>>()?;

    // MediaMTX host preflight (#1974 Slice 7): non-mutating doctor checks run before the
    // app deploy, so a bad media host fails fast with nothing written. The mutating
    // provisioning — write config and unit, restart — is deferred until after the app
    // cutover succeeds, so a rolled-back app deploy never touches the host MediaMTX unit.
    // No-op unless enabled (see fn).
    //
    // Single-host by construction rather than by branch: `provision_media_host` has no
    // teardown or rollback path, so a media-enabled fleet is refused outright above
    // (§4.8). Reaching here with media enabled proves the config declares exactly one
    // host, and `executors[0]` is it. With media disabled this and the provisioning call
    // below are both no-ops, so no host-count branch is needed.
    check_media_host_preflight(input.media_cfg, input.ffmpeg_bin, &executors[0])?;

    // ── ALL-HOSTS PROBE (read-only, serial, rollout order) ───────────────────
    // Nothing anywhere in the fleet is mutated by this phase.
    let probes = fleet
        .hosts
        .iter()
        .zip(&executors)
        .map(|(cfg, executor)| probe_host_for_up(cfg, input, executor))
        .collect::<Result<Vec<HostProbeState>, DeployError>>()?;

    let modes: Vec<fleet::HostMode> = probes.iter().map(|probe| probe.mode).collect();
    let plan = fleet::plan_fleet(fleet, &modes).map_err(|e| DeployError::Config(e.to_string()))?;

    if !single {
        for line in fleet::fleet_rollout_lines(&plan, input.release_id) {
            eprintln!("{line}");
        }
        eprintln!();
    }

    // ── EXECUTION (serial, one host at a time, rollout order) ────────────────
    let mut outcomes = vec![fleet::HostOutcome::Untouched; total];
    // Housekeeping debris is recorded OUTSIDE the outcome slot: a degraded host that
    // is later compensated becomes `CompensatedRollback`, and the failed
    // `record-proxy-options` that will fail its NEXT deploy closed must survive that
    // overwrite.
    let mut degraded: Vec<(String, &'static str)> = Vec::new();
    // Set when the rollout stops. Compensation runs after the loop, not inside it,
    // so the compensation set is computed from the FINAL per-host outcomes.
    let mut halt: Option<(String, &'static str)> = None;
    for (index, host_plan) in plan.hosts.iter().enumerate() {
        let cfg = &fleet.hosts[index];
        let state = &probes[index];
        let executor = &executors[index];

        let release_dir = format!("{}/{}", cfg.releases_dir(), input.release_id);
        let unit = render_app_unit(
            cfg,
            &release_dir,
            state.slots.candidate_port,
            state.slots.candidate_slot,
        );
        let mut ops = fleet::host_ops(
            host_plan,
            &fleet::HostOpsInput {
                cfg,
                proxy: input.proxy,
                unit: &unit,
                env_file: input.env_file,
                binary_local: input.binary,
                manifests: input.manifests,
                release_id: input.release_id,
                slots: &state.slots,
                reregister_options: &state.reregister_options,
            },
        );
        // Host preparation (#1607, AC-1): this host has no usable reverse-proxy binary,
        // so install one as the first op of its turn, ahead of the proxy unit that
        // supervises it and ahead of everything else. Running it here rather than during
        // the read-only probe phase is what keeps "no host is touched until every host is
        // graded" true, and it makes a failed install an ordinary pre-cutover failure:
        // the rollout halts, this host is compensated like any other, and no host that
        // already cut over is left behind.
        // Repair the drifted marker as an early op — before the cutover's
        // record-previous-release reads it — so the on-disk marker matches the proxy
        // truth even if the rest of the deploy is interrupted. Uses `state.slots
        // .public_port` — the EFFECTIVE public port `probe_host_for_up` planned this
        // host's slots from (the OLD port across a detected `server.port` move,
        // #2073) — never `input.public_port` (the newly requested one): the repair
        // must persist the port the live release ACTUALLY binds, not one derived
        // from a port that has not taken effect yet.
        if state.repair {
            ops.insert(
                0,
                exec::live_slot_marker_repair_op(
                    cfg,
                    state.slots.live_slot,
                    state.slots.public_port,
                ),
            );
        }
        // Install the MediaMTX binary (#1974). The proxy install below goes in
        // front, so the order is: proxy install, MediaMTX install, other ops. This
        // op only adds a file at an empty path, so it is safe before cutover. It is
        // empty when media is off.
        ops.splice(0..0, media_binary_install_ops(input.media_cfg));
        // Host preparation goes in AFTER the repair insert so it ends up ahead of
        // it: a host needing both is one with no proxy binary AND a drifted marker,
        // and installing the proxy is what makes every later op — the marker repair
        // included — worth attempting at all.
        if state.needs_proxy_install {
            eprintln!(
                "{}host preparation: {}",
                if single {
                    String::new()
                } else {
                    format!("host {}: ", host_plan.host)
                },
                input.proxy.binary_install_note(),
            );
            let install = input.proxy.binary_install_ops().unwrap_or_default();
            ops.splice(0..0, install);
        }
        // First-deploy teardown must also unlink `current` and clear the live-slot
        // marker that first_deploy_ops creates — otherwise a failed first deploy
        // leaves them behind and the next `deploy up` wrongly takes the redeploy
        // path with nothing serving.
        let teardown = match host_plan.mode {
            // This is the pre-go-live path — its failure boundary IS the health-
            // gated `proxy-route` op, so a failure here means the route was never
            // established. There is nothing to deregister (issue #2270).
            fleet::HostMode::First => {
                exec::first_deploy_teardown_ops(cfg, input.release_id, &state.slots)
            }
            fleet::HostMode::Redeploy => {
                exec::candidate_teardown_ops(cfg, input.release_id, &state.slots)
            }
        };

        if single {
            eprintln!(
                "Deploying release {} to {} ({})\u{2026}\n",
                input.release_id, host_plan.host, state.banner,
            );
        } else {
            eprintln!(
                "[{}/{total} {}] deploying release {} ({})\u{2026}",
                index + 1,
                host_plan.host,
                input.release_id,
                state.banner,
            );
        }

        let result = match host_plan.mode {
            fleet::HostMode::First => {
                exec::execute_first_deploy(input.checks, &ops, &teardown, executor)
            }
            fleet::HostMode::Redeploy => {
                exec::execute_redeploy(input.checks, &ops, &teardown, executor)
            }
        };

        match result {
            Ok(()) => {
                // Option C phase 4 (#2073): the cutover just landed on the OLD public
                // port (phases 1-3 planned against it deliberately), so a detected
                // `server.port` change moves the proxy's public listener now, AFTER
                // the release is live and the old one has drained — its own failure
                // boundary, with its own rollback to `old_port` on failure.
                if let Some(mv) = state.port_move {
                    let options = input.proxy.proxy_service_options();
                    let rebind_ops = exec::public_port_rebind_ops(
                        cfg,
                        input.proxy,
                        input.release_id,
                        state.slots.candidate_port,
                        &options,
                        mv.new_port,
                    );
                    let rollback_ops = exec::public_port_rebind_ops(
                        cfg,
                        input.proxy,
                        input.release_id,
                        state.slots.candidate_port,
                        &options,
                        mv.old_port,
                    );
                    if let Err(rebind_err) = exec::execute_public_port_rebind(
                        &rebind_ops,
                        &rollback_ops,
                        mv.old_port,
                        mv.new_port,
                        executor,
                    ) {
                        if single {
                            // A rolled-back rebind still serves the new release
                            // on the old port, so it bakes first.
                            if matches!(rebind_err, exec::PublicPortRebindError::RolledBack { .. })
                                && let BakeStep::Fail(bake_error) = bake_host(
                                    input,
                                    index,
                                    single,
                                    host_plan,
                                    cfg,
                                    &state.slots,
                                    executor,
                                )
                            {
                                eprintln!("\u{26A0}\u{FE0F}  {rebind_err}");
                                return Err(bake_error);
                            }
                            return Err(DeployError::Exec(rebind_err.to_string()));
                        }
                        match rebind_err {
                            // The release is live and reachable at the OLD port — a
                            // recoverable, traffic-healthy degradation (exactly what
                            // `Degraded` means elsewhere), so the rollout continues
                            // past it like every other post-cutover housekeeping
                            // failure.
                            exec::PublicPortRebindError::RolledBack { .. } => {
                                outcomes[index] = fleet::HostOutcome::Degraded {
                                    label: "public-port-rebind",
                                };
                                degraded.push((host_plan.host.clone(), "public-port-rebind"));
                                eprintln!(
                                    "\u{26A0}\u{FE0F}  [{}/{total} {}] serving {} \u{2014} \
                                     {rebind_err}\n",
                                    index + 1,
                                    host_plan.host,
                                    input.release_id,
                                );
                                // The host serves the new release, so it bakes too.
                                if matches!(
                                    bake_host(
                                        input,
                                        index,
                                        single,
                                        host_plan,
                                        cfg,
                                        &state.slots,
                                        executor
                                    ),
                                    BakeStep::Halt | BakeStep::Fail(_)
                                ) {
                                    outcomes[index] = fleet::HostOutcome::LiveOnNew {
                                        failed_step: bake::BAKE_LABEL,
                                    };
                                    halt = Some((host_plan.host.clone(), bake::BAKE_LABEL));
                                    break;
                                }
                                continue;
                            }
                            // The proxy's public bind is now unknown — unlike a
                            // `Degraded` host this one may NOT be reachable, so it
                            // must never be reported as "traffic is fine" (that is
                            // `Degraded`'s fixed summary text) and must never be
                            // auto-compensated by an ordinary proxy-flip rollback,
                            // which could target a proxy that is not even listening.
                            // `Manual` is the existing "needs a human, do not touch"
                            // outcome (mirrors `AmbiguousMarkers`) — halt rather than
                            // roll forward.
                            exec::PublicPortRebindError::RollbackFailed { .. } => {
                                outcomes[index] = fleet::HostOutcome::Manual {
                                    reason: fleet::MANUAL_PUBLIC_PORT_UNKNOWN,
                                };
                                eprintln!(
                                    "\n\u{274C} rollout halted at {} (`public-port-rebind`) \
                                     \u{2014} the remaining hosts were not touched \u{2014} \
                                     {rebind_err}\n",
                                    host_plan.host,
                                );
                                halt = Some((host_plan.host.clone(), "public-port-rebind"));
                                break;
                            }
                        }
                    }
                }
                // The post-cutover bake (#3069).
                match bake_host(input, index, single, host_plan, cfg, &state.slots, executor) {
                    BakeStep::Continue => {}
                    BakeStep::Fail(error) => return Err(error),
                    BakeStep::Halt => {
                        outcomes[index] = fleet::HostOutcome::LiveOnNew {
                            failed_step: bake::BAKE_LABEL,
                        };
                        halt = Some((host_plan.host.clone(), bake::BAKE_LABEL));
                        break;
                    }
                }
                outcomes[index] = fleet::HostOutcome::Serving;
                if !single {
                    if host_plan.migrate == exec::MigrateStep::Run {
                        eprintln!("\u{26A0}\u{FE0F}  {}", fleet::FLEET_SCHEMA_MOVED_NOTE);
                    }
                    eprintln!(
                        "\u{2705} [{}/{total} {}] serving {}\n",
                        index + 1,
                        host_plan.host,
                        input.release_id,
                    );
                }
            }
            Err(err) => {
                // A one-host fleet keeps today's error: no fleet vocabulary, no
                // degrade-and-continue, no compensation. One exception (#2276): if
                // the binaries went back after `migrate`, add the schema note. The
                // fleet classifier decides this, so the two paths cannot diverge.
                outcomes[index] = fleet::classify_host_outcome(&err);
                if single {
                    // A housekeeping failure leaves the new release serving, so it
                    // bakes first. A failed bake is the error that matters.
                    if matches!(outcomes[index], fleet::HostOutcome::Degraded { .. })
                        && let BakeStep::Fail(bake_error) =
                            bake_host(input, index, single, host_plan, cfg, &state.slots, executor)
                    {
                        eprintln!("\u{26A0}\u{FE0F}  {err}");
                        return Err(bake_error);
                    }
                    let message = fleet::single_host_schema_note(&plan, &outcomes).map_or_else(
                        || err.to_string(),
                        |note| format!("{err}\n\u{26A0}\u{FE0F}  {note}"),
                    );
                    return Err(DeployError::Exec(message));
                }
                let failed_step = fleet::failed_step_label(&err);
                // #2279: a live old slot runs workers and the scheduler, so work
                // runs two times. Retry one time. Continue only on a proven stop.
                if matches!(
                    outcomes[index],
                    fleet::HostOutcome::Degraded { label } if label == fleet::DRAIN_OLD_LABEL
                ) {
                    let prefix = format!("[{}/{total} {}]", index + 1, host_plan.host);
                    let old_slot = match exec::retry_drain_old(cfg, state.slots.live_slot, executor)
                    {
                        Ok(old_slot) => old_slot,
                        Err(retry_err) => {
                            eprintln!("\u{26A0}\u{FE0F}  {prefix} the retry failed: {retry_err}");
                            exec::OldSlotState::Unreadable
                        }
                    };
                    outcomes[index] = fleet::drain_old_outcome(old_slot);
                    if old_slot == exec::OldSlotState::Stopped {
                        eprintln!(
                            "\u{26A0}\u{FE0F}  {prefix} `{}` failed, but the retry stopped and \
                             disabled the old slot.",
                            fleet::DRAIN_OLD_LABEL,
                        );
                    } else {
                        eprintln!(
                            "\u{26A0}\u{FE0F}  {prefix} serving {} \u{2014} but `{}` failed \
                             AFTER the cutover: {}.",
                            input.release_id,
                            fleet::DRAIN_OLD_LABEL,
                            fleet::OLD_SLOT_MAY_RUN_NOTE,
                        );
                    }
                }
                // Post-boundary housekeeping: the proxy is already serving the new
                // release on this host and only bookkeeping failed. Warn, record the
                // debris, and keep rolling — the alternative is an outage caused by
                // a failed `rm -rf` (#1621, §4.6).
                if let fleet::HostOutcome::Degraded { label } = outcomes[index] {
                    degraded.push((host_plan.host.clone(), label));
                    // Only a missing `shared/proxy-options` marker makes the next
                    // deploy refuse this host.
                    let refusal = if label == "record-proxy-options" {
                        ", which will refuse it"
                    } else {
                        ""
                    };
                    eprintln!(
                        "\u{26A0}\u{FE0F}  [{}/{total} {}] serving {} \u{2014} but `{label}` \
                         failed AFTER the cutover. Traffic is healthy, so the rollout \
                         continues; repair this host (a redeploy does) before the next \
                         deploy{refusal}.\n",
                        index + 1,
                        host_plan.host,
                        input.release_id,
                    );
                    // The host serves the new release, so it bakes too.
                    if matches!(
                        bake_host(input, index, single, host_plan, cfg, &state.slots, executor),
                        BakeStep::Halt | BakeStep::Fail(_)
                    ) {
                        outcomes[index] = fleet::HostOutcome::LiveOnNew {
                            failed_step: bake::BAKE_LABEL,
                        };
                        halt = Some((host_plan.host.clone(), bake::BAKE_LABEL));
                        break;
                    }
                    continue;
                }
                eprintln!(
                    "\n\u{274C} rollout halted at {} (`{failed_step}`) \u{2014} the remaining \
                     hosts were not touched.\n",
                    host_plan.host,
                );
                halt = Some((host_plan.host.clone(), failed_step));
                break;
            }
        }
    }

    if let Some((failed_host, failed_step)) = halt {
        if input.auto_rollback {
            compensate_fleet(input, &plan, &probes, &executors, &mut outcomes);
        }
        // Print the per-host state on the way out — AFTER compensation, so the table
        // describes where the fleet actually IS, and even when the compensating
        // rollback itself failed. That is precisely the case where the operator has
        // no other source of truth.
        for line in fleet::fleet_summary_lines(&plan, &outcomes, input.release_id) {
            eprintln!("{line}");
        }
        let error = fleet_halted(&plan, &outcomes, &degraded, failed_host, failed_step);
        // #2267: send a #1610 alert for the halt. This is best-effort. It
        // does not change `error` below.
        if let DeployError::FleetHalted(ref halt) = error {
            emit_fleet_halted_alert(halt, input.app_name, input.profile);
        }
        return Err(error);
    }

    // App deploy is committed on every host here: the cutovers succeeded and there
    // is no longer a rollback path. Only NOW provision the host MediaMTX unit
    // (write config/unit + restart) — deferring the mutation past this point means
    // a failed/rolled-back app deploy above never wrote or restarted MediaMTX
    // (#1974 Slice 7). No-op unless enabled (see fn), and a media-enabled fleet is
    // refused in the prologue (§4.8), so `executors[0]` is the only host whenever
    // this does anything at all.
    {
        let executor = &executors[0];
        provision_media_host(input.media_cfg, executor)?;
    }

    if single {
        eprintln!("\n\u{2705} Deploy complete. Roll back with `autumn deploy rollback`.");
    } else {
        for line in fleet::fleet_summary_lines(&plan, &outcomes, input.release_id) {
            eprintln!("{line}");
        }
        // Every host serves the new release either way; a degraded host is live and
        // healthy, so this is a success — but claiming an unqualified "complete"
        // when a host's `record-proxy-options` never landed would hide the thing
        // that fails its NEXT deploy closed. And on a `--only`-narrowed run `total`
        // is the SELECTED count, so "all N hosts" would read as a full-fleet
        // success while the skipped hosts sit on their old release.
        eprintln!(
            "{}",
            fleet::fleet_completion_line(
                input.release_id,
                total,
                input.configured_host_count,
                degraded.len(),
            )
        );
    }
    Ok(())
}

/// What the rollout does after one host's bake (#3069).
enum BakeStep {
    /// No bake, or the bake passed.
    Continue,
    /// A fleet host breached: halt and compensate.
    Halt,
    /// A single host breached; this is the deploy's error.
    Fail(DeployError),
}

/// Bake one host that serves the new release (#3069).
///
/// A first deploy does not bake: it has no previous release to return to. A
/// single host is rolled back here. A fleet host returns [`BakeStep::Halt`],
/// and the fleet compensation rolls it back with the others.
fn bake_host<E, P>(
    input: &FleetUpInput<'_, P>,
    index: usize,
    single: bool,
    host_plan: &fleet::HostPlan,
    cfg: &ResolvedDeployConfig,
    slots: &exec::SlotPlan,
    executor: &E,
) -> BakeStep
where
    E: exec::DeployExecutor,
    P: ProxyController,
{
    let Some(policy) = input.bake else {
        return BakeStep::Continue;
    };
    let prefix = if single {
        String::new()
    } else {
        format!(
            "[{}/{} {}] ",
            index + 1,
            input.fleet.hosts.len(),
            host_plan.host
        )
    };
    if matches!(host_plan.mode, fleet::HostMode::First) {
        eprintln!("{prefix}bake skipped: a first deploy has no previous release to roll back to.");
        return BakeStep::Continue;
    }
    let unit = exec::slot_unit_name(&cfg.service_name, slots.candidate_slot);
    let target = bake::BakeTarget {
        port: slots.candidate_port,
        metrics_path: input.metrics_path,
        host_header: input.bake_host,
        unit: &unit,
    };
    let breach = match bake::run(policy, &target, executor, &mut |line| {
        eprintln!("{prefix}{line}");
    }) {
        bake::BakeOutcome::Passed { responses, judged } => {
            if judged {
                eprintln!("{prefix}bake passed ({responses} responses).");
            } else {
                eprintln!(
                    "\u{26A0}\u{FE0F}  {prefix}bake passed with no verdict: {responses} \
                     responses is fewer than {}.",
                    policy.min_requests
                );
            }
            return BakeStep::Continue;
        }
        bake::BakeOutcome::Breached(breach) => breach,
    };
    eprintln!("\n\u{274C} {prefix}bake failed: {breach}\n");
    if !single {
        return BakeStep::Halt;
    }
    let result = if input.auto_rollback {
        match compensate_rollback(cfg, input, slots.public_port, executor) {
            fleet::HostOutcome::CompensatedRollback => BAKE_ROLLED_BACK,
            fleet::HostOutcome::Manual { .. } => BAKE_ROLLBACK_REFUSED,
            _ => BAKE_ROLLBACK_FAILED,
        }
    } else {
        BAKE_FROZEN
    };
    let schema_note = (result == BAKE_ROLLED_BACK && host_plan.migrate == exec::MigrateStep::Run)
        .then_some(fleet::SINGLE_HOST_SCHEMA_AHEAD_NOTE);
    if result != BAKE_ROLLED_BACK
        && let Err(error) = provision_media_host(input.media_cfg, executor)
    {
        // The new release still serves, so it still needs its media host.
        eprintln!("\u{26A0}\u{FE0F}  {error}");
    }
    BakeStep::Fail(DeployError::BakeFailed {
        host: host_plan.host.clone(),
        reason: breach.to_string(),
        result,
        schema_note,
    })
}

/// Compensate a halted rollout: undo every host that is already on the new release,
/// in strict REVERSE rollout order (issue #1621, §4.7, AC-3).
///
/// Three rules are load-bearing:
///
/// 1. **Best-effort CONTINUE.** A failed rollback on host j does not stop host j-1.
///    Stopping would leave MORE hosts on the new release — a bigger mixed fleet,
///    which is the harm AC-3 names.
/// 2. **Never swallowed.** Each host's result is recorded into its outcome slot and
///    reported. This deliberately does NOT reuse [`exec::run_ops`]'s teardown
///    sibling `run_teardown`, whose `let _ = …` is right for cleanup that must not
///    mask a real failure and actively dangerous at fleet scale.
/// 3. **Binaries only.** [`exec::rollback_ops`] and
///    [`exec::first_deploy_teardown_ops`] contain no `migrate` op by construction,
///    so a migration that already ran stays applied. The summary says so out loud.
///
/// Nothing here is new machinery: a redeploy host is compensated with exactly the
/// on-demand `autumn deploy rollback` primitives, and a completed FIRST deploy with
/// the first-deploy teardown (it has no previous release to return to).
fn compensate_fleet<E, P>(
    input: &FleetUpInput<'_, P>,
    plan: &fleet::FleetPlan,
    probes: &[HostProbeState],
    executors: &[E],
    outcomes: &mut [fleet::HostOutcome],
) where
    E: exec::DeployExecutor,
    P: ProxyController,
{
    let modes: Vec<fleet::HostMode> = plan.hosts.iter().map(|host| host.mode).collect();
    let actions = fleet::fleet_rollback_set(outcomes, &modes);
    if actions.is_empty() {
        return;
    }

    eprintln!(
        "\u{21A9}\u{FE0F}  Compensating {} host(s) in reverse rollout order \u{2014} BINARIES \
         only; a migration that already ran is NOT rolled back.\n",
        actions.len(),
    );
    for action in actions {
        let index = match action {
            fleet::RollbackAction::Rollback(index)
            | fleet::RollbackAction::Teardown(index)
            | fleet::RollbackAction::Manual(index, _) => index,
        };
        let cfg = &input.fleet.hosts[index];
        let host = plan.hosts[index].host.as_str();
        outcomes[index] = match action {
            fleet::RollbackAction::Rollback(_) => {
                eprintln!(
                    "\u{21A9}\u{FE0F}  [{host}] rolling back to the previous release\u{2026}"
                );
                compensate_rollback(
                    cfg,
                    input,
                    probes[index].slots.public_port,
                    &executors[index],
                )
            }
            fleet::RollbackAction::Teardown(_) => {
                eprintln!(
                    "\u{21A9}\u{FE0F}  [{host}] removing this run's first deploy \
                     (no previous release to return to)\u{2026}"
                );
                compensate_teardown(cfg, input, &probes[index].slots, &executors[index])
            }
            fleet::RollbackAction::Manual(_, reason) => {
                for line in fleet::manual_recovery_lines(cfg, reason) {
                    eprintln!("{line}");
                }
                // An ambiguous-marker host already describes itself more precisely
                // than "manual" does; keep the specific state.
                if matches!(outcomes[index], fleet::HostOutcome::AmbiguousMarkers) {
                    fleet::HostOutcome::AmbiguousMarkers
                } else {
                    fleet::HostOutcome::Manual { reason }
                }
            }
        };
        eprintln!();
    }
}

/// Roll ONE host back to its previous release, with the target-dir precheck
/// (issue #1621, §4.7).
///
/// Every refusal fails CLOSED to [`fleet::HostOutcome::Manual`]: the host stays on
/// the new release and is reported, which is strictly better than flipping it at a
/// release dir we cannot prove exists — that failure lands post-boundary, with no
/// teardown, turning one broken host into two.
///
/// `public_port` is the host's effective public port for this run
/// ([`exec::SlotPlan::public_port`]): the port before a `server.port` move. A
/// legacy two-field marker derives the previous slot's port from it, and the
/// previous release was deployed under that port, not the new one.
fn compensate_rollback<E, P>(
    cfg: &ResolvedDeployConfig,
    input: &FleetUpInput<'_, P>,
    public_port: u16,
    executor: &E,
) -> fleet::HostOutcome
where
    E: exec::DeployExecutor,
    P: ProxyController,
{
    let target = match exec::resolve_rollback_target(cfg, public_port, executor) {
        Ok(target) => target,
        // The host records no previous release (a first deploy clears the marker,
        // and a host deployed before the marker existed simply has none).
        Err(exec::DeployExecError::NoPreviousRelease) => {
            return manual_outcome(cfg, fleet::MANUAL_NO_PREVIOUS_RELEASE);
        }
        // The probe itself could not run: we know nothing, so we change nothing.
        Err(_) => {
            return manual_outcome(cfg, fleet::MANUAL_ROLLBACK_TARGET_UNPROVABLE);
        }
    };
    match exec::probe_rollback_target_dir(&target.release_dir, executor) {
        Ok(exec::ReleaseDirState::Present) => {}
        Ok(exec::ReleaseDirState::Absent) => {
            return manual_outcome(cfg, fleet::MANUAL_ROLLBACK_TARGET_MISSING);
        }
        Ok(exec::ReleaseDirState::Unreadable) | Err(_) => {
            return manual_outcome(cfg, fleet::MANUAL_ROLLBACK_TARGET_UNPROVABLE);
        }
    }

    let ops = exec::rollback_ops(cfg, input.proxy, &target);
    // Same teardown as the on-demand rollback: a failure at or before the
    // health-gated flip disables the slot it just restarted, so the host is left
    // serving what it was serving when compensation started.
    let teardown = exec::rollback_teardown_ops(cfg, &target);
    match exec::execute_rollback(input.checks, &ops, &teardown, executor) {
        Ok(()) => fleet::HostOutcome::CompensatedRollback,
        Err(err) => {
            let failed_step = fleet::failed_step_label(&err);
            eprintln!(
                "\u{274C} [{}] the compensating rollback FAILED at `{failed_step}` \u{2014} this \
                 host is still on {}. The remaining hosts are still compensated.",
                cfg.host.as_deref().unwrap_or_default(),
                input.release_id,
            );
            fleet::HostOutcome::CompensationFailed { failed_step }
        }
    }
}

/// Remove ONE host's just-completed FIRST deploy (issue #1621, §4.7).
///
/// A first deploy has no `shared/previous-release` marker, so there is nothing to
/// roll back to. The honest compensation is the first-deploy teardown: stop the
/// slot unit, remove this run's release dir, clear the `current` symlink and
/// slot markers, and record `torn down` — [`exec::first_deploy_teardown_ops`],
/// unchanged since #1621. This leaves the host in the nothing-installed state
/// that makes the next `deploy up` correctly take the First path again.
///
/// Driven through [`exec::run_ops`], not `run_teardown`: at fleet scale a silently
/// swallowed cleanup failure is how a host ends up half-removed with nobody told.
///
/// The proxy route is removed as its OWN, SEPARATE step, only once the app
/// teardown above has fully SUCCEEDED (issue #2270), so its public port refuses
/// connections instead of answering 502. Splitting it out like this — rather
/// than folding it into the same op list — is deliberate: a transport failure
/// (the local `ssh` launch itself dying) carries NO op label at all, so if the
/// route removal shared a list with the app teardown, that shape of failure
/// could never be told apart from one on an EARLIER, not-yet-attempted step.
/// Run alone, ANY failure here — a real remote error or a labelless transport
/// one — can only mean one thing: the app is confirmed gone (the first call
/// already returned `Ok`) and only the route is in question. That is reported
/// as its own outcome, [`fleet::HostOutcome::CompensatedTeardownRouteFailed`],
/// never the generic [`fleet::HostOutcome::CompensationFailed`] ("still on the
/// new release, roll it back" — untrue here, and impossible: a first deploy has
/// no previous release to roll back to).
fn compensate_teardown<E, P>(
    cfg: &ResolvedDeployConfig,
    input: &FleetUpInput<'_, P>,
    slots: &exec::SlotPlan,
    executor: &E,
) -> fleet::HostOutcome
where
    E: exec::DeployExecutor,
    P: ProxyController,
{
    let app_ops = exec::first_deploy_teardown_ops(cfg, input.release_id, slots);
    if let Err(err) = exec::run_ops(&app_ops, executor) {
        let failed_step = fleet::failed_step_label(&err);
        eprintln!(
            "\u{274C} [{}] removing the first deploy FAILED at `{failed_step}` \u{2014} this \
             host is still on {}. The remaining hosts are still compensated.",
            cfg.host.as_deref().unwrap_or_default(),
            input.release_id,
        );
        return fleet::HostOutcome::CompensationFailed { failed_step };
    }

    let deregister = input.proxy.deregister_op(&cfg.service_name);
    match exec::run_ops(&[deregister], executor) {
        Ok(()) => fleet::HostOutcome::CompensatedTeardown,
        Err(err) => {
            let failed_step = fleet::failed_step_label(&err);
            eprintln!(
                "\u{26A0}\u{FE0F}  [{}] removed the first deploy, but its proxy route removal \
                 FAILED at `{failed_step}` \u{2014} its public port may still answer 502 until it \
                 is redeployed or the route is removed by hand.",
                cfg.host.as_deref().unwrap_or_default(),
            );
            fleet::HostOutcome::CompensatedTeardownRouteFailed { failed_step }
        }
    }
}

/// Decline the automatic rollback for one host, print the by-hand recovery block,
/// and record the reason.
fn manual_outcome(cfg: &ResolvedDeployConfig, reason: &'static str) -> fleet::HostOutcome {
    for line in fleet::manual_recovery_lines(cfg, reason) {
        eprintln!("{line}");
    }
    fleet::HostOutcome::Manual { reason }
}

// ── #2267: send a #1610 alert on a halted rollout or on drift ───────────────
//
// AC-6 of #1621 asks for this. Do not make the operator poll a non-zero exit
// code for it. Follow the `db::backup` pattern from issue #1743: load the
// config, build the same channels `autumn alert test` uses, and deliver
// directly. This is best-effort. It never changes the command's exit code.

/// Build alert channels from `alerts`/`http`, already resolved.
///
/// Check `[alerts] enabled` first, the master switch (review finding on
/// #2267: a disabled config with transport credentials left in place must
/// send nothing). `is_active()` checks `enabled` AND a set destination.
/// Return an empty list when either check fails. An empty list is a no-op
/// downstream.
fn alert_channels_for(
    alerts: &autumn_web::alerts::AlertConfig,
    http: &autumn_web::config::HttpConfig,
) -> Vec<Arc<dyn AlertChannel>> {
    if !alerts.is_active() {
        return Vec::new();
    }
    let client = autumn_web::http::Client::from_config(&http.client);
    crate::alert::configured_http_channels(alerts, &client)
}

/// Read `[alerts]` and `[http]` from the raw project TOML layers alone — no
/// env-var overlay yet (the caller applies one — see
/// [`apply_alert_env_overrides`]), no full [`AutumnConfig`] deserialize.
/// Mirrors [`declared_server_port_in`]'s own merge of base `autumn.toml` ←
/// inline `[profile.<name>]` ← `autumn-<profile>.toml`.
///
/// Review finding on #2267: [`load_runtime_config`] can fail on a section
/// this command does not even use (a bad `[scheduler]`/`[database]` value),
/// the exact case [`status_public_port`] already degrades gracefully for
/// the port. Without this, that same failure would ALSO silence a valid
/// `[alerts]` destination — exactly the incident an operator most needs to
/// hear about. Deserializing only `alerts`/`http` out of the merged TOML
/// ignores every other top-level key, so a bad value there can not break
/// this the way it breaks the full `AutumnConfig` deserialize.
fn declared_alert_config_in(
    dirs: &[PathBuf],
    profile_raw: &str,
) -> Option<(
    autumn_web::alerts::AlertConfig,
    autumn_web::config::HttpConfig,
)> {
    #[derive(Deserialize, Default)]
    #[serde(default)]
    struct AlertsHttpTomlRoot {
        alerts: autumn_web::alerts::AlertConfig,
        http: autumn_web::config::HttpConfig,
    }

    let mut merged = toml::Value::Table(toml::map::Map::new());
    let base_toml: Option<toml::Value> = first_dir_with_file(dirs, "autumn.toml")
        .and_then(|path| std::fs::read_to_string(path).ok())
        .and_then(|text| toml::from_str::<toml::Value>(&text).ok());
    let canonical = canonicalize_deploy_profile(profile_raw);
    if let Some(base) = &base_toml {
        deep_merge_toml(&mut merged, base.clone());
        for name in profile_inline_lookup_names(&canonical) {
            if let Some(section) = profile_section_from_base_toml(base, name) {
                deep_merge_toml(&mut merged, section);
            }
        }
    }
    for name in autumn_web::config::profile_override_file_lookup_names(&canonical, profile_raw) {
        let Some(path) = first_dir_with_file(dirs, &format!("autumn-{name}.toml")) else {
            continue;
        };
        // Review finding on #2267: an unreadable or malformed override file
        // must fail this whole read, not be silently skipped in favor of
        // the base/inline config. A `[profile.prod]` override exists to
        // CHANGE or disable a destination — silently falling back to a
        // lower-priority layer could page using a destination the override
        // was meant to replace.
        let text = std::fs::read_to_string(&path).ok()?;
        let overlay: toml::Value = toml::from_str(&text).ok()?;
        deep_merge_toml(&mut merged, overlay);
        break;
    }

    // Review finding on #2267: `strict_config` hard-fails `load_runtime_config`
    // on a typo'd key inside `[alerts]`/`[http]` (e.g. `enabeld` for
    // `enabled`) — the exact scenario landing here. Plain deserialize
    // ignores an unrecognized field silently, which would default a
    // mistyped `enabled` switch back to `true`. Reject it instead, using
    // the SAME schema the primary path checks against.
    if merged_alerts_or_http_has_unknown_key(&merged) {
        return None;
    }

    let root: AlertsHttpTomlRoot = merged.try_into().ok()?;
    Some((root.alerts, root.http))
}

/// Whether `merged` has an unrecognized key under `alerts` or `http`.
///
/// Reuses [`AutumnConfig::validate_toml`]/[`AutumnConfig::get_schema_keys`]
/// — the same schema check `strict_config` runs on the primary path —
/// filtered to `alerts`/`http` paths only, so an unrelated unknown
/// top-level root (a plugin-owned table) is never mistaken for our own
/// error.
fn merged_alerts_or_http_has_unknown_key(merged: &toml::Value) -> bool {
    let Ok(toml_str) = toml::to_string(merged) else {
        return false;
    };
    let schema = AutumnConfig::get_schema_keys();
    AutumnConfig::validate_toml(&toml_str, &schema)
        .iter()
        .any(|(path, _)| {
            path == "alerts"
                || path.starts_with("alerts.")
                || path == "http"
                || path.starts_with("http.")
        })
}

/// Load `[alerts]` under the TARGET deploy profile. Build its channels.
///
/// Review finding on #2267: the ambient ("ambient" means the operator's
/// shell) profile can differ from the deploy profile, so a plain
/// `AutumnConfig::load()` can miss a production-only destination or send a
/// production incident to a dev one. Use [`load_runtime_config`] instead —
/// the same forced-profile load `run` uses for `check`/`rollback`/`up`. On
/// failure, fall back to [`declared_alert_config_in`] rather than giving up:
/// see its own doc for why and its narrower limitation.
fn deploy_alert_channels_for_profile(profile: &str) -> Vec<Arc<dyn AlertChannel>> {
    if let Ok(config) = load_runtime_config(profile) {
        return alert_channels_for(&config.alerts, &config.http);
    }
    let Some((alerts, http)) = declared_alert_config_in(&manifest_project_dirs(), profile) else {
        eprintln!("  \u{26A0} alert skipped: could not load configuration for profile {profile}");
        return Vec::new();
    };
    // Review finding on #2267: the TOML-only fallback above must still see
    // `AUTUMN_ALERTS__*`/`AUTUMN_HTTP__*` env overrides, or a destination
    // set only via env var (the documented, recommended way to supply a
    // secret) gets nothing here, and an `AUTUMN_ALERTS__ENABLED=false`
    // meant to silence a TOML-configured destination is ignored.
    //
    // If the `.env.<profile>` overlay itself fails to build (unreadable or
    // malformed), fall back to bare OS env rather than skipping the env
    // layer outright (review finding on #2267): real OS env vars are the
    // HIGHEST-priority layer regardless of `.env.<profile>`, so an
    // `AUTUMN_ALERTS__ENABLED=false` set directly in the process
    // environment must still apply even when the dotenv file can not be
    // read. Only the lower-priority `.env.<profile>` layer is lost here.
    let (alerts, http) = match deploy_profile_env_overlay(profile) {
        Ok(env) => apply_alert_env_overrides(alerts, http, &env),
        Err(_) => apply_alert_env_overrides(alerts, http, &autumn_web::config::OsEnv),
    };
    alert_channels_for(&alerts, &http)
}

/// Apply the same `AUTUMN_ALERTS__*`/`AUTUMN_HTTP__*` env overrides the
/// primary [`load_runtime_config`] path applies (issue #2267 review).
///
/// Reuses [`AutumnConfig::apply_env_overrides_with_env`] verbatim on a
/// scratch value — the exact method `AutumnConfig::load_with_env` itself
/// calls — so this can never drift from the primary path's env semantics.
/// Every OTHER section of the scratch value is a throwaway default; only
/// `alerts`/`http` are read back out.
fn apply_alert_env_overrides(
    alerts: autumn_web::alerts::AlertConfig,
    http: autumn_web::config::HttpConfig,
    env: &dyn Env,
) -> (
    autumn_web::alerts::AlertConfig,
    autumn_web::config::HttpConfig,
) {
    let mut scratch = AutumnConfig {
        alerts: Box::new(alerts),
        http,
        ..AutumnConfig::default()
    };
    scratch.apply_env_overrides_with_env(env);
    (*scratch.alerts, scratch.http)
}

/// Send `alert` to every channel in `channels`.
///
/// Use a short-lived runtime, like `autumn alert test` does. Log a failed
/// delivery. Do not stop for it. This must never change the command's exit
/// code. Do nothing when `channels` is empty. This happens when `[alerts]`
/// has no channel set.
fn deliver_alert(channels: &[Arc<dyn AlertChannel>], alert: &Alert) {
    if channels.is_empty() {
        return;
    }
    let runtime = match tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
    {
        Ok(rt) => rt,
        Err(e) => {
            eprintln!("  \u{26A0} alert not sent: could not start async runtime: {e}");
            return;
        }
    };
    runtime.block_on(async {
        for channel in channels {
            if let Err(error) = channel.deliver(alert).await {
                eprintln!(
                    "  \u{26A0} alert not delivered via {}: {error}",
                    channel.name()
                );
            }
        }
    });
}

/// Join host names into one alert-detail value. Return an empty string for
/// an empty list — for example, when no host was torn down.
fn join_hosts(hosts: &[String]) -> String {
    hosts.join(", ")
}

/// Join `(host, reason)` pairs into one alert-detail value.
fn join_host_reasons(pairs: &[(String, &'static str)]) -> String {
    pairs
        .iter()
        .map(|(host, reason)| format!("{host}: {reason}"))
        .collect::<Vec<_>>()
        .join("; ")
}

/// Build the alert for a halted fleet rollout (issue #2267, AC-6 of #1621).
///
/// This is a pure function. It does no I/O. So a test can call it directly.
/// It reuses the `ScheduledTaskFailure` condition. It does not add a new
/// `AlertCondition` variant. Issue #1743 made the same choice for a failed
/// backup upload. A halted rollout is also a task the framework runs, and
/// it did not finish.
///
/// Every field on `halt` is a host name or a fixed operation label (see
/// [`FleetHalt`]). So this alert can never carry a shell line or a raw
/// driver error.
///
/// Its dedup key includes `app_name` and `profile`, so a halt on staging
/// and a halt on production never merge into one incident, and neither do
/// two different apps' `prod` halts, even when they share a `PagerDuty`
/// routing key (review findings on #2267 — matches [`build_drift_alert`]'s
/// existing scoping, extended with the app name).
///
/// Sets its own `where_to_look` (review finding on #2267): the
/// `ScheduledTaskFailure` default is `/actuator/tasks`, an app runtime
/// endpoint with no fleet or rollout data. `autumn deploy status` is the
/// command that shows the fleet's actual state.
fn build_fleet_halted_alert(halt: &FleetHalt, app_name: &str, profile: &str) -> Alert {
    let alert = Alert::trigger(
        AlertCondition::ScheduledTaskFailure,
        format!("scheduled_task_failure:deploy-fleet-halted:{app_name}:{profile}"),
    )
    .title("Fleet rollout halted")
    .summary(halt.to_string())
    .where_to_look("autumn deploy status")
    .detail("app_name", app_name)
    .detail("profile", profile)
    .detail("failed_host", halt.failed_host.clone())
    .detail("failed_step", halt.failed_step)
    .detail("rolled_back", join_hosts(&halt.rolled_back))
    .detail("torn_down", join_hosts(&halt.torn_down))
    .detail("still_on_new", join_hosts(&halt.still_on_new))
    .detail("degraded", join_host_reasons(&halt.degraded))
    .detail(
        "route_removal_failed",
        join_host_reasons(&halt.route_removal_failed),
    )
    .detail("manual", join_host_reasons(&halt.manual));
    match halt.risk() {
        Some(risk) => alert.detail("risk", risk),
        None => alert,
    }
    .build()
}

/// Send an alert for a halted fleet rollout (issue #2267, AC-6 of #1621).
///
/// Loads `[alerts]` under `profile`, the TARGET deploy profile — not the
/// operator's ambient shell profile. This runs on any halt, if `[alerts]`
/// names a channel there. If no channel is set, this does nothing. So an
/// operator with no alert channel sees the same behavior as before. They
/// see a message and a non-zero exit.
fn emit_fleet_halted_alert(halt: &FleetHalt, app_name: &str, profile: &str) {
    let channels = deploy_alert_channels_for_profile(profile);
    deliver_alert(
        &channels,
        &build_fleet_halted_alert(halt, app_name, profile),
    );
}

/// Write a one-line summary of a [`fleet::DriftReport`] for an alert.
fn drift_alert_summary(report: &fleet::DriftReport) -> String {
    let mut parts = Vec::new();
    if report.version_drift {
        parts.push(format!(
            "{} known release(s) are live at once",
            report.known_releases().len()
        ));
    }
    if !report.state_drift.is_empty() {
        parts.push(format!(
            "{} host(s) have state drift",
            report.state_drift.len()
        ));
    }
    parts.join("; ")
}

/// Build the alert for drift found by `deploy status --strict` (issue #2267,
/// AC-6 of #1621).
///
/// This is a pure function. It does no I/O. Its dedup key includes
/// `app_name` and `profile`, so drift on staging and drift on production
/// never merge into one alert, and neither do two different apps' `prod`
/// drift (review finding on #2267).
///
/// It carries the same reason strings `fleet::fleet_drift` already prints —
/// never a raw driver error. So it needs no secrets check beyond what
/// `DriftReport` already gives.
///
/// Sets its own `where_to_look`, same reason as [`build_fleet_halted_alert`]
/// (review finding on #2267).
fn build_drift_alert(report: &fleet::DriftReport, app_name: &str, profile: &str) -> Alert {
    Alert::trigger(
        AlertCondition::ScheduledTaskFailure,
        format!("scheduled_task_failure:deploy-drift:{app_name}:{profile}"),
    )
    .title("Fleet drift detected")
    .summary(drift_alert_summary(report))
    .where_to_look("autumn deploy status")
    .detail("app_name", app_name)
    .detail("profile", profile)
    .detail("version_drift", report.version_drift.to_string())
    .detail("state_drift", join_host_reasons(&report.state_drift))
    .build()
}

/// Send an alert for drift found by `deploy status --strict` (issue #2267,
/// AC-6 of #1621). This is the cron path in `docs/guide/fleet-deploys.md`.
///
/// Loads `[alerts]` under `profile`, the TARGET deploy profile — not the
/// operator's ambient shell profile. This does nothing if `[alerts]` has no
/// channel set there. The caller must call this only in `--strict` mode. A
/// plain `deploy status` check must never page anyone.
fn emit_drift_alert(report: &fleet::DriftReport, app_name: &str, profile: &str) {
    let channels = deploy_alert_channels_for_profile(profile);
    deliver_alert(&channels, &build_drift_alert(report, app_name, profile));
}

/// Build the typed halt error from the recorded per-host outcomes (issue #1621,
/// AC-3).
///
/// Secrets discipline: every field is a host name or a `&'static str` op label —
/// never a shell line, a remote path, or a formatted driver error (a migration
/// failure's source can embed the database URL).
///
/// The lists describe the FINAL state, so this must be built after compensation:
/// a host the fleet rolled back is `rolled_back`, and a host whose rollback FAILED
/// stays in `still_on_new` — reporting the attempt instead of the result is how an
/// operator ends up believing a mixed fleet converged.
///
/// `degraded` is passed in rather than derived, because a degraded host that was
/// later compensated no longer carries that state in its outcome slot and its
/// housekeeping debris outlives the rollback.
fn fleet_halted(
    plan: &fleet::FleetPlan,
    outcomes: &[fleet::HostOutcome],
    degraded: &[(String, &'static str)],
    failed_host: String,
    failed_step: &'static str,
) -> DeployError {
    let named = |want: fn(&fleet::HostOutcome) -> bool| -> Vec<String> {
        plan.hosts
            .iter()
            .zip(outcomes)
            .filter(|(_, outcome)| want(outcome))
            .map(|(host, _)| host.host.clone())
            .collect()
    };
    DeployError::FleetHalted(Box::new(FleetHalt {
        failed_host,
        failed_step,
        rolled_back: named(|o| {
            matches!(
                o,
                fleet::HostOutcome::RolledBack { .. } | fleet::HostOutcome::CompensatedRollback
            )
        }),
        torn_down: named(|o| {
            matches!(
                o,
                fleet::HostOutcome::TornDown { .. }
                    | fleet::HostOutcome::CompensatedTeardown
                    | fleet::HostOutcome::CompensatedTeardownRouteFailed { .. }
            )
        }),
        // Shared with the summary table's own list, so the halt error and the state
        // table can never disagree about which hosts are still forward.
        still_on_new: named(fleet::HostOutcome::on_new_release),
        degraded: degraded.to_vec(),
        route_removal_failed: plan
            .hosts
            .iter()
            .zip(outcomes)
            .filter_map(|(host, outcome)| match outcome {
                fleet::HostOutcome::CompensatedTeardownRouteFailed { failed_step } => {
                    Some((host.host.clone(), *failed_step))
                }
                _ => None,
            })
            .collect(),
        manual: plan
            .hosts
            .iter()
            .zip(outcomes)
            .filter_map(|(host, outcome)| match outcome {
                fleet::HostOutcome::AmbiguousMarkers => {
                    Some((host.host.clone(), fleet::MANUAL_AMBIGUOUS_MARKERS))
                }
                fleet::HostOutcome::Manual { reason } => Some((host.host.clone(), *reason)),
                _ => None,
            })
            .collect(),
    }))
}

/// Perform a real on-demand rollback (issue #1607, Slice 3, AC-4).
///
/// Loads config via the same dotenv-aware path and runs the same preflight as
/// `up`, aborting before touching the server on any failure. It then resolves the
/// previous release on the target ([`exec::resolve_rollback_target`]) — failing
/// loudly and non-zero via [`exec::DeployExecError::NoPreviousRelease`] when
/// there is nothing to roll back to — and drives [`exec::rollback_ops`]: bring the
/// previous slot's unit back up, flip the proxy back to it, repoint `current`, and
/// re-probe `/ready`.
/// `hosts` is the ordered target list, already narrowed by `--only` (issue #1621).
/// With more than one entry this becomes a FLEET rollback: every host, in strict
/// REVERSE declaration order, best-effort-continue. With one entry (or none — a
/// config with no target still flows into the preflight report) it is the
/// pre-#1621 single-host path verbatim.
fn run_rollback(
    config: &AutumnConfig,
    resolved: &ResolvedDeployConfig,
    hosts: &[String],
    configured_host_count: usize,
) -> Result<(), DeployError> {
    eprintln!("\u{1F342} autumn deploy rollback\n");

    // Same SQLite data-file contract as `up` (#1909): a rollback target deployed
    // BEFORE the data file was adopted into `shared/` holds no file at that path
    // any more, so the rolled-back release is re-linked at it rather than
    // starting against a fresh, empty database.
    let resolved = &with_sqlite_data_contract(resolved, config);

    // The rollback targets, in declaration order. A single-host config (either
    // spelling) resolves to a one-host fleet whose only element IS today's
    // `resolved`, so the branch below is the pre-#1621 sequence at N = 1.
    let fleet = ResolvedFleet::from_targets(resolved, hosts);
    // Which rollback path this run takes, decided ONCE and reused by the preflight
    // gate below and the driver branch further down, so the two can never disagree.
    // Note this is `is_single()`, not `is_single_host_deploy`: rolling ONE host back
    // — whether that is the whole config or a `--only` narrowing of it — really is a
    // single-host rollback, and the fleet driver has no second host to converge with.
    let fleet_rollback = !fleet.is_single();

    // Fail fast: the same preflight as `up`, before any remote call. Every host is
    // graded, so an unreachable host in position 3 is reported before host 3 — or
    // any other host — is touched. The GATE is narrower than `up`'s, though: see
    // [`blocking_rollback_failures`].
    let checks = collect_fleet_preflight(config, &fleet, configured_host_count);
    let failed = report_preflight(&checks);
    if blocking_rollback_failures(&checks, fleet_rollback) > 0 {
        return Err(DeployError::PreflightFailed(failed));
    }
    if failed > 0 {
        eprintln!(
            "\u{26A0}\u{FE0F}  {failed} host(s) above did not answer the reachability probe. A \
             ROLLBACK continues without them \u{2014} stopping would leave the hosts that ARE \
             reachable on the release you are leaving \u{2014} but each is reported as NOT \
             rolled back and this command still exits non-zero.\n"
        );
    }

    // Show what a rollback will do before it runs (descriptive, not a dry-run gate).
    // These are the steps EACH host runs; the fleet ordering is printed below them.
    eprintln!("Rollback steps:");
    for (i, step) in build_rollback_plan(resolved).iter().enumerate() {
        eprintln!("  {}. [{}] {}", i + 1, step.label, step.description);
    }
    eprintln!();

    let public_port = config.server.port;
    let proxy = proxy::KamalProxyController::new(resolved.readiness_timeout_secs)
        .with_tls_host(resolved.tls_host.clone());

    if fleet_rollback {
        return run_fleet_rollback_with(&checks, &fleet, &proxy, public_port, |cfg| {
            exec::SshTarget::from_resolved(cfg)
                .map(exec::SshExecutor::new)
                .ok_or_else(|| DeployError::Config(DEPLOY_HOST_MISSING_DETAIL.to_owned()))
        });
    }

    // Same rule as the `up` driver (#2274): a hostless fleet is a config error with
    // a message, not an index panic.
    let single = fleet
        .hosts
        .first()
        .ok_or_else(|| DeployError::Config(DEPLOY_HOST_MISSING_DETAIL.to_owned()))?;
    let target = exec::SshTarget::from_resolved(single)
        .ok_or_else(|| DeployError::Config(DEPLOY_HOST_MISSING_DETAIL.to_owned()))?;
    let executor = exec::SshExecutor::new(target);

    // Resolve the previous release to roll back to (non-zero error if none).
    let rollback_target = exec::resolve_rollback_target(single, public_port, &executor)
        .map_err(|e| DeployError::Exec(e.to_string()))?;
    eprintln!(
        "Rolling back {} to {} ({})\u{2026}\n",
        single.host.as_deref().unwrap_or_default(),
        rollback_target.release_dir,
        rollback_target.slot,
    );

    let ops = exec::rollback_ops(single, &proxy, &rollback_target);
    // If the rollback fails at or before the health-gated flip, disable the slot it
    // restarted so the original release is left cleanly serving (the flip never
    // moved traffic, and no marker is written until after the flip).
    let teardown = exec::rollback_teardown_ops(single, &rollback_target);
    exec::execute_rollback(&checks, &ops, &teardown, &executor)
        .map_err(|e| DeployError::Exec(e.to_string()))?;

    eprintln!("\n\u{2705} Rollback complete.");
    Ok(())
}

/// The grader name a per-host reachability row carries. Kept as one constant so
/// the rollback gate below and the skip it implies can never key on different
/// spellings than [`grade_ssh_reachability`] emits.
const SSH_REACHABILITY_CHECK: &str = "ssh_reachability";

/// Whether a preflight check is a PER-HOST reachability row of a real fleet
/// (issue #1621): the grader name plus a scope, which
/// [`collect_fleet_preflight`] attaches only for a fleet of more than one host.
fn is_per_host_reachability(check: &PreflightCheck) -> bool {
    check.name == SSH_REACHABILITY_CHECK && check.scope.is_some()
}

/// How many preflight failures must ABORT a fleet rollback before it touches
/// anything (issue #1621, §3.2).
///
/// `deploy up` refuses the whole rollout if any host fails — AC-7 — because a
/// rollout is a CHANGE, and starting one against a fleet it cannot finish is how a
/// fleet ends up mixed. A rollback is the opposite kind of command: it is recovery,
/// its documented contract is best-effort-continue
/// ([`run_fleet_rollback_with`]), and the host that stopped answering SSH is very
/// often the reason the operator is rolling back at all. Refusing to move the
/// healthy majority off a bad release because one host is dead leaves MORE hosts on
/// the release being abandoned — the exact outcome that contract exists to prevent.
///
/// So exactly one class is downgraded to a reported, non-blocking row: a per-host
/// `ssh_reachability` failure in a real fleet. It is still printed by
/// [`report_preflight`], that host is still skipped and reported as NOT rolled back,
/// and the command still exits non-zero via [`DeployError::FleetRollbackFailed`].
///
/// Everything else keeps the hard gate. A project-wide grader describes the release
/// being rolled back TO rather than one host's reachability, and a SINGLE-host
/// rollback keeps the pre-#1621 gate verbatim (AC-1) — which is what
/// `fleet_rollback` is for: the softening only makes sense when
/// [`run_fleet_rollback_with`] is the code that actually runs, because only it
/// skips-and-reports the unreachable host. The single-host path would sail past the
/// gate straight into an SSH it already knows will fail, so for it EVERY failure
/// blocks, exactly as before #1621. (Pre-#1621 this fell out of the rows being
/// unscoped; since a `--only`-narrowed run now scopes its rows for attribution, the
/// gate keys on the path instead of inferring it.)
fn blocking_rollback_failures(checks: &[PreflightCheck], fleet_rollback: bool) -> usize {
    checks
        .iter()
        .filter(|check| check.blocking() && !(fleet_rollback && is_per_host_reachability(check)))
        .count()
}

/// Roll EVERY host in `fleet` back to its previous release, newest first (issue
/// #1621, §3.2).
///
/// The executor factory is injected (generic, never `dyn`, no `Send`/`Sync` bound)
/// so the whole loop is unit-testable against one scripted fake per host.
///
/// Three deliberate differences from the rollout driver, all following from the
/// fact that a rollback is a RECOVERY action rather than a change:
///
/// 1. **Reverse declaration order.** The rollout replaces hosts front to back, so
///    the hosts at the back have been on the new release for the shortest time;
///    undoing them first shrinks the mixed window from the newest end and mirrors
///    the compensation order exactly.
/// 2. **Best-effort continue, never halt.** A host that fails does not stop the
///    others: stopping would leave MORE hosts on the release the operator is trying
///    to leave. Every failure is recorded and reported — never swallowed.
/// 3. **No previous release is not fatal — to the OTHER hosts.** A host that has
///    never been redeployed (or was just added to the fleet) has no marker to roll
///    back to. It is reported as a SKIP rather than as a failed rollback, and it
///    never stops the rest of the fleet.
///
/// **Exit semantics (deliberate):** the command succeeds only when EVERY host
/// rolled back. A host that failed and a host that had nothing to roll back to are
/// distinguished in the table and in the operator's remedy, but both exit non-zero,
/// because the contract of a fleet rollback is that the FLEET returns to its
/// previous release — and a fleet where one host could not follow the others is
/// mixed. Reporting that as success is how a mixed fleet survives an incident
/// unnoticed.
fn run_fleet_rollback_with<E, P, F>(
    checks: &[PreflightCheck],
    fleet: &ResolvedFleet,
    proxy: &P,
    public_port: u16,
    make_executor: F,
) -> Result<(), DeployError>
where
    E: exec::DeployExecutor,
    P: ProxyController,
    F: Fn(&ResolvedDeployConfig) -> Result<E, DeployError>,
{
    let total = fleet.hosts.len();
    // ONE executor per host, built up front: a host with no SSH target is a config
    // error, and finding it here means nothing has been flipped yet.
    let executors = fleet
        .hosts
        .iter()
        .map(&make_executor)
        .collect::<Result<Vec<E>, DeployError>>()?;

    let names: Vec<String> = fleet
        .hosts
        .iter()
        .map(|cfg| cfg.host.clone().unwrap_or_default())
        .collect();
    eprintln!(
        "Rolling {total} hosts back to their previous release, ONE AT A TIME, NEWEST FIRST \
         (the reverse of `[deploy] hosts` order):\n"
    );

    // Every slot is overwritten below — the loop is exhaustive and, unlike the
    // rollout driver, never breaks early — so the seed value is unobservable. It is
    // the conservative one regardless: "nothing was rolled back here".
    let mut outcomes = vec![fleet::RollbackOutcome::NoPreviousRelease; total];
    for index in (0..total).rev() {
        let cfg = &fleet.hosts[index];
        let host = names[index].as_str();
        eprintln!("[{}/{total} {host}] rolling back\u{2026}", index + 1);
        // Preflight is fleet-wide, but a per-host reachability row belongs to ONE
        // host: forwarding another host's failed row would abort this host's
        // `execute_rollback` for a fault that is not its own
        // (see `blocking_rollback_failures`).
        let host_checks: Vec<PreflightCheck> = checks
            .iter()
            .filter(|check| {
                !is_per_host_reachability(check) || check.scope.as_deref() == Some(host)
            })
            .cloned()
            .collect();
        outcomes[index] = if host_checks.iter().any(PreflightCheck::blocking) {
            // Reported, never touched: its preflight row is already on screen, and
            // probing a host that did not answer a TCP connect would only stall the
            // hosts queued behind it.
            eprintln!(
                "\u{274C} [{host}] did not answer the preflight reachability probe \u{2014} \
                 this host was NOT rolled back. The remaining hosts still are."
            );
            fleet::RollbackOutcome::Failed {
                failed_step: SSH_REACHABILITY_CHECK,
            }
        } else {
            rollback_one_host(
                &host_checks,
                cfg,
                proxy,
                public_port,
                host,
                &executors[index],
            )
        };
        eprintln!();
    }

    for line in fleet::fleet_rollback_summary_lines(&names, &outcomes) {
        eprintln!("{line}");
    }

    let rolled_back = outcomes
        .iter()
        .filter(|outcome| matches!(outcome, fleet::RollbackOutcome::RolledBack))
        .count();
    // Non-zero unless EVERY host came back: a fleet that half-rolled-back is mixed,
    // and reporting that as success is how a mixed fleet survives an incident
    // unnoticed. The table above distinguishes "failed" from "nothing to roll back
    // to", which is what the operator's next move turns on.
    if rolled_back < total {
        return Err(DeployError::FleetRollbackFailed {
            not_rolled_back: total - rolled_back,
            total,
        });
    }
    eprintln!("\n\u{2705} Fleet rollback complete \u{2014} all {total} hosts restored.");
    Ok(())
}

/// Roll ONE host back to its previous release for a fleet-wide rollback.
///
/// Uses the UNCHANGED on-demand primitives ([`exec::resolve_rollback_target`] →
/// [`exec::rollback_ops`] → [`exec::execute_rollback`], with the same
/// [`exec::rollback_teardown_ops`]), so a fleet rollback is literally N single-host
/// rollbacks and can never drift from the one the operator runs by hand.
///
/// Returns an outcome instead of an error because the caller continues past a
/// failure: the report is the aggregate, and nothing here is swallowed. Only the
/// `&'static str` step LABEL is printed — never the driver's message, which can
/// carry remote output.
fn rollback_one_host<E, P>(
    checks: &[PreflightCheck],
    cfg: &ResolvedDeployConfig,
    proxy: &P,
    public_port: u16,
    host: &str,
    executor: &E,
) -> fleet::RollbackOutcome
where
    E: exec::DeployExecutor,
    P: ProxyController,
{
    let target = match exec::resolve_rollback_target(cfg, public_port, executor) {
        Ok(target) => target,
        Err(exec::DeployExecError::NoPreviousRelease) => {
            eprintln!(
                "\u{26A0}\u{FE0F}  [{host}] no previous release recorded \u{2014} nothing to \
                 roll back to on this host; it keeps serving what it is serving now."
            );
            return fleet::RollbackOutcome::NoPreviousRelease;
        }
        Err(err) => {
            let failed_step = fleet::failed_step_label(&err);
            eprintln!(
                "\u{274C} [{host}] could not resolve the previous release (`{failed_step}`) \
                 \u{2014} this host was NOT rolled back. The remaining hosts still are."
            );
            return fleet::RollbackOutcome::Failed { failed_step };
        }
    };
    eprintln!(
        "  \u{2192} {host} returns to {} ({})",
        target.release_dir, target.slot,
    );

    let ops = exec::rollback_ops(cfg, proxy, &target);
    // Same teardown as the on-demand rollback: a failure at or before the
    // health-gated flip disables the slot it just restarted, so this host is left
    // serving exactly what it served before the attempt.
    let teardown = exec::rollback_teardown_ops(cfg, &target);
    match exec::execute_rollback(checks, &ops, &teardown, executor) {
        Ok(()) => fleet::RollbackOutcome::RolledBack,
        Err(err) => {
            let failed_step = fleet::failed_step_label(&err);
            eprintln!(
                "\u{274C} [{host}] the rollback FAILED at `{failed_step}` \u{2014} this host \
                 was not restored. The remaining hosts still are."
            );
            fleet::RollbackOutcome::Failed { failed_step }
        }
    }
}

// ── `deploy status` (issue #1621, AC-6) ──────────────────────────────────────

/// Probe every fleet host read-only and collect its status row (issue #1621).
///
/// Serial and deterministic (declaration order), like every other fleet loop here:
/// threading the probes would put a `Sync` bound on `DeployExecutor` that the
/// `RefCell`-based test fake cannot satisfy, and status output must come out in
/// rollout order anyway. Parallelism is a later, isolated optimisation.
///
/// A host whose probe fails becomes an `unreachable` ROW, never an abort:
/// `deploy status` exists for incidents, and an incident is exactly when a host
/// may not answer. Only an executor-construction failure (a config with no SSH
/// target at all) aborts, because then NO host could be probed.
fn collect_fleet_status<E, F>(
    fleet: &ResolvedFleet,
    public_port: u16,
    make_executor: F,
) -> Result<Vec<fleet::HostStatus>, DeployError>
where
    E: exec::DeployExecutor,
    F: Fn(&ResolvedDeployConfig) -> Result<E, DeployError>,
{
    let mut statuses = Vec::with_capacity(fleet.hosts.len());
    for cfg in &fleet.hosts {
        let executor = make_executor(cfg)?;
        // The probe error is deliberately not printed: it can carry remote stderr,
        // and "unreachable" in the table is the operator-facing fact.
        let status = exec::probe_host_status(cfg, public_port, &executor).map_or_else(
            |_| fleet::HostStatus::unreachable(cfg.host.clone().unwrap_or_default()),
            |probe| fleet::HostStatus::from_probe(cfg, public_port, &probe),
        );
        statuses.push(status);
    }
    Ok(statuses)
}

/// The stable `deploy status --json` shape (issue #1621, AC-6).
///
/// The repo's skills are a first-class consumer, so the field set is a documented
/// contract:
///
/// - `hosts`: one object per host, in `[deploy] hosts` (rollout) order, with
///   `host` (string), `reachable` (bool), `mode`
///   (`"deployed"`/`"not deployed"`/`"unknown"`/`"unreachable"`), `release`
///   (string or null when unknown), `live_slot` (string or null), `ready` (HTTP
///   status number or null), `maintenance` (`true`/`false` as the host's RUNNING
///   slot unit observes it, or `null` when the CLI could not prove which flag file
///   that unit polls — see `fleet::DRIFT_MAINTENANCE_UNPROVEN`), `proxy_port`
///   (number or null),
///   `last_deploy` (AC-6's third fact: `{result, at}` — `result` is `"deployed"`,
///   `"rolled back"` or `"torn down"` (a first deploy the driver compensated away,
///   so the host serves nothing), `at` the host's UTC timestamp or null — and the
///   whole object is null when the host has never completed a cutover or the marker
///   could not be read), and `drift` (array of reason strings, empty when none).
///   `last_deploy` is the host's own last COMPLETED action, not a verdict on the
///   last rollout: a deploy that failed before cutover never rewrites it (see
///   `fleet::LAST_DEPLOY_SCOPE_NOTE`).
/// - `version_drift` (bool), `state_drift` (array of `{host, reason}`), and
///   `drifted` (bool — the `--strict` condition).
///
/// Everything here is a host name, an enum word, a number, or a `&'static str`
/// reason — never a shell line, a remote capture, or a driver error, so no secret
/// can reach it.
fn fleet_status_json(
    statuses: &[fleet::HostStatus],
    report: &fleet::DriftReport,
) -> serde_json::Value {
    let hosts: Vec<serde_json::Value> = statuses
        .iter()
        .map(|status| {
            let mode = if status.reachable {
                match status.mode {
                    Some(fleet::HostMode::First) => "not deployed",
                    Some(fleet::HostMode::Redeploy) => "deployed",
                    None => "unknown",
                }
            } else {
                "unreachable"
            };
            serde_json::json!({
                "host": status.host,
                "reachable": status.reachable,
                "mode": mode,
                "release": match &status.release {
                    fleet::ReleaseId::Known(id) => serde_json::Value::String(id.clone()),
                    fleet::ReleaseId::Unknown => serde_json::Value::Null,
                },
                "live_slot": status.live_slot,
                "ready": status.ready_code,
                // Three-valued since #1621 review round 1: `true`/`false` are
                // proved states of the file the RUNNING slot unit polls, and
                // `null` is "the CLI could not prove which file that is". Both
                // false and null stay falsy for a consumer that tests the field
                // directly, so `maintenance == true` never widens.
                "maintenance": match status.maintenance {
                    exec::MaintenanceStatus::On => serde_json::Value::Bool(true),
                    exec::MaintenanceStatus::Off => serde_json::Value::Bool(false),
                    exec::MaintenanceStatus::Unknown => serde_json::Value::Null,
                },
                "proxy_port": match status.installed_proxy_port {
                    exec::InstalledProxyPort::Port(port) => {
                        serde_json::Value::Number(port.into())
                    }
                    _ => serde_json::Value::Null,
                },
                "last_deploy": status.last_deploy.as_ref().map_or(
                    serde_json::Value::Null,
                    |last| serde_json::json!({ "result": last.result, "at": last.at }),
                ),
                "drift": report
                    .state_drift
                    .iter()
                    .filter(|(host, _)| *host == status.host)
                    .map(|(_, reason)| *reason)
                    .collect::<Vec<_>>(),
            })
        })
        .collect();
    serde_json::json!({
        "hosts": hosts,
        "version_drift": report.version_drift,
        "state_drift": report
            .state_drift
            .iter()
            .map(|(host, reason)| serde_json::json!({ "host": host, "reason": reason }))
            .collect::<Vec<_>>(),
        "drifted": report.drifted(),
    })
}

/// `autumn deploy status`: probe every host read-only and render the shared
/// per-host table (or `--json`), exiting non-zero on drift only under `--strict`
/// (issue #1621, AC-6).
/// Say out loud that the public port was resolved WITHOUT validating the app
/// config, and what this command does about it (issue #1621, review round 1).
///
/// Never silent, and never on stdout: a `--json` consumer keeps the documented
/// shape while a human still sees WHY the port was resolved the hard way and WHICH
/// port the command is working against. `continues` is the caller's own second
/// line, because `status` (read-only) and `maintenance` (which uses the port only
/// to identify the live slot unit) owe the operator different sentences.
fn warn_degraded_port(port: &StatusPort, profile: &str, continues: &str) {
    let Some(reason) = &port.degraded else {
        return;
    };
    eprintln!(
        "\u{26A0}\u{FE0F}  this project's configuration does not validate under the \
         `{profile}` deploy profile: {reason}"
    );
    eprintln!("{continues}\n");
}

fn run_status(
    port: &StatusPort,
    app_name: &str,
    profile: &str,
    fleet: &ResolvedFleet,
    options: &DeployOptions,
) -> Result<(), DeployError> {
    if !options.json {
        eprintln!("\u{1F342} autumn deploy status\n");
    }
    warn_degraded_port(
        port,
        profile,
        &format!(
            "   `deploy status` is read-only, so it continues against the DECLARED \
             `[server] port = {}` for that profile (read without validation). \
             `autumn deploy check`/`up` still refuse to run until the config is fixed.",
            port.port
        ),
    );
    let statuses = collect_fleet_status(fleet, port.port, |cfg| {
        exec::SshTarget::from_resolved(cfg)
            .map(exec::SshExecutor::new)
            .ok_or_else(|| DeployError::Config(DEPLOY_HOST_MISSING_DETAIL.to_owned()))
    })?;
    let report = fleet::fleet_drift(&statuses);
    if options.json {
        // Reports (like `plan`) go to stdout; a `Value` cannot fail to serialise.
        println!(
            "{}",
            serde_json::to_string_pretty(&fleet_status_json(&statuses, &report))
                .expect("a serde_json::Value always serializes")
        );
    } else {
        for line in fleet::fleet_status_lines(&statuses, &report) {
            println!("{line}");
        }
    }
    if options.strict && report.drifted() {
        // #2267: send a #1610 alert for the drift. This runs only in
        // `--strict` mode. An interactive `deploy status` must not page
        // anyone.
        emit_drift_alert(&report, app_name, profile);
        return Err(DeployError::DriftDetected);
    }
    Ok(())
}

// ── `deploy maintenance on|off` fan-out (issue #1621, AC-5) ──────────────────

/// Serialize the maintenance flag body from the CLI flags (issue #1621).
///
/// Goes through `autumn_web::maintenance::MaintenanceConfig` — the exact struct
/// the RUNTIME deserializes — and the same pretty-printed JSON
/// `MaintenanceState::save_to_file` writes locally, so the fleet fan-out and the
/// local `autumn maintenance on` can never disagree about the wire format.
fn maintenance_flag_body(args: &MaintenanceOnArgs) -> String {
    let config = autumn_web::maintenance::MaintenanceConfig {
        message: args.message.clone(),
        allow_ips: args.allow_ips.clone(),
        readonly: args.readonly,
        bypass_header: args.bypass_header.clone(),
    };
    serde_json::to_string_pretty(&config).expect("MaintenanceConfig always serializes")
}

/// Fan `maintenance on|off` out over every fleet host (issue #1621, AC-5).
///
/// **Best-effort-and-aggregate — deliberately the OPPOSITE of the rollout
/// driver** (plan §6.2). Rollout halts and compensates because a mixed-version
/// fleet is the harm; a control-plane switch that succeeded on 2 of 3 hosts must
/// NOT be rolled back (that pushes users back into the live window the operator is
/// closing) and must NOT stop at the failure (the remaining hosts are still
/// serving). Every host is attempted, every outcome is named in the table, and the
/// command exits non-zero when ANY host failed.
///
/// Per amendment A2 each `on` writes up to two flag paths, shared one FIRST:
///
/// - `{app_dir}/shared/autumn-maintenance.json` — the authoritative path the
///   #1621 slot units point `AUTUMN_MAINTENANCE_FLAG_FILE` at; survives cutovers.
///   Always written first, so a #1621 unit reacts within its 500 ms poll even if
///   the second write fails.
/// - the file the host's **live slot unit** actually makes the app poll, when that
///   is a DIFFERENT file — a unit deployed before #1621 carries no override and
///   polls its own `WorkingDirectory`-relative `tmp/autumn-maintenance.json`.
///   Resolved from the proxy-selected live slot's unit, exactly as `deploy status`
///   resolves the flag it REPORTS (review round 3); never from the `current`
///   symlink, which can name a different release than the unit that is running.
///
/// `off` removes the same set (`rm -f`, absent files are not an error).
///
/// `public_port` is what maps the proxy's routed target back to a slot, so it is
/// resolved exactly as `deploy status` resolves it — degraded fallback included,
/// because a maintenance window gets closed mid-incident and an unrelated invalid
/// setting must not stand in the way.
///
/// The executor factory is injected (generic, never `dyn`, no `Send`/`Sync`
/// bound) so the whole loop is unit-testable against one scripted fake per host.
fn run_fleet_maintenance_with<E, F>(
    fleet: &ResolvedFleet,
    port: &StatusPort,
    profile: &str,
    action: DeployAction,
    args: Option<&MaintenanceOnArgs>,
    make_executor: F,
) -> Result<(), DeployError>
where
    E: exec::DeployExecutor,
    F: Fn(&ResolvedDeployConfig) -> Result<E, DeployError>,
{
    let on = matches!(action, DeployAction::MaintenanceOn);
    let verb = if on { "on" } else { "off" };
    eprintln!("\u{1F342} autumn deploy maintenance {verb}\n");
    warn_degraded_port(
        port,
        profile,
        &format!(
            "   `deploy maintenance` continues against the DECLARED `[server] port = {}` \
             for that profile (read without validation); it uses that port only to identify \
             which slot unit each host is running. `autumn deploy check`/`up` still refuse \
             to run until the config is fixed.",
            port.port
        ),
    );

    let total = fleet.hosts.len();
    // ONE executor per host, built up front: a host with no SSH target is a config
    // error, and finding it here means no host has been half-changed yet.
    let executors = fleet
        .hosts
        .iter()
        .map(&make_executor)
        .collect::<Result<Vec<E>, DeployError>>()?;
    let names: Vec<String> = fleet
        .hosts
        .iter()
        .map(|cfg| cfg.host.clone().unwrap_or_default())
        .collect();

    let default_args = MaintenanceOnArgs::default();
    let body = maintenance_flag_body(args.unwrap_or(&default_args));

    let mut outcomes = Vec::with_capacity(total);
    for (index, cfg) in fleet.hosts.iter().enumerate() {
        eprintln!(
            "[{}/{total} {}] maintenance {verb}\u{2026}",
            index + 1,
            names[index],
        );
        outcomes.push(maintenance_one_host(
            cfg,
            port.port,
            on,
            &body,
            &executors[index],
        ));
        eprintln!();
    }

    for line in fleet::fleet_maintenance_summary_lines(&names, &outcomes, on) {
        eprintln!("{line}");
    }

    let failed = outcomes.iter().filter(|outcome| outcome.failed()).count();
    if failed > 0 {
        return Err(DeployError::FleetMaintenanceFailed {
            verb: if on { "on" } else { "off" },
            failed,
            total,
        });
    }
    Ok(())
}

/// What the write path could prove about the file this host's RUNNING unit polls
/// (issue #1621, review round 3).
enum LiveFlagTarget {
    /// Nothing is promoted on this host, so no unit is serving and the shared write
    /// is the whole job.
    NoRelease,
    /// The live slot's unit resolves to exactly this file.
    Path(String),
    /// A release IS live, but its unit could not be read — so which file the
    /// application polls is NOT proved. Fail closed: never guessed from `current`.
    Unproved,
}

/// Apply `maintenance on|off` to ONE host, returning what happened — never an
/// error, because the caller continues past a failure (issue #1621, §6.2).
///
/// Two read-only probes first: `detect-current` (the same shared probe `up` runs)
/// for the live-slot decision, then `detect-maintenance-flag` — the SAME on-host
/// resolution `deploy status` reads the maintenance verdict with
/// ([`exec::probe_live_maintenance_flag`]) — for the file that slot's unit actually
/// makes the app poll. Resolving the write target the way the read path resolves
/// its answer is the point: the `current` symlink and the running unit disagree
/// whenever a proxy flip landed and `commit-markers` did not, and a flag written
/// under `current` is then a file nothing polls (review round 3).
///
/// Then the writes/removals per amendment A2, shared path FIRST.
///
/// Only op LABELS ever leave this function — the raw error can carry remote
/// stderr, and the aggregate report must not.
fn maintenance_one_host<E: exec::DeployExecutor>(
    cfg: &ResolvedDeployConfig,
    public_port: u16,
    on: bool,
    body: &str,
    executor: &E,
) -> fleet::MaintenanceOutcome {
    let Ok(probe) = exec::probe_deploy_state(cfg, executor) else {
        return fleet::MaintenanceOutcome::Failed {
            failed_step: "detect-current",
        };
    };
    let target = match probe.reconcile(cfg, public_port) {
        None => LiveFlagTarget::NoRelease,
        // An unreadable unit AND an unrunnable probe both mean the same thing here:
        // nothing is proved. The shared write still goes ahead below — it is the
        // authoritative path and costs nothing to be right about — but the host is
        // reported as only partially changed.
        Some(reconcile) => {
            match exec::probe_live_maintenance_flag(cfg, reconcile.live_slot, executor) {
                Ok(Some(flag)) => LiveFlagTarget::Path(flag.path),
                Ok(None) | Err(_) => LiveFlagTarget::Unproved,
            }
        }
    };

    let shared = cfg.maintenance_flag_file();
    // The file the live unit polls, ONLY when it is not the shared one already
    // being written: a #1621 unit points at the shared path, and writing a second
    // copy nothing reads would just leave litter for the next operator to wonder at.
    let live_path = match &target {
        LiveFlagTarget::Path(path) if *path != shared => Some(path.clone()),
        _ => None,
    };

    let mut ops: Vec<exec::DeployOp> = Vec::new();
    // The index the shared write lands at: a failure at or before it means the
    // host was NOT changed (fail closed); a failure after it means the shared
    // flag landed but the running unit's own file did not.
    let shared_index = if on {
        // Shared (authoritative) flag first: a #1621 unit reacts within 500 ms of
        // this single write, so the window starts closing even if the write below
        // fails (amendment A2).
        //
        // #2280: the shared flag's parent (`{app_dir}/shared`) only comes into
        // existence during `prepare-dirs` on a deploy, so a host that has NEVER
        // been deployed has no shared dir yet — and scp does not create
        // destination parents, so the write fails and the
        // `AppliedSharedOnly` success path (keyed on exactly this host shape) is
        // unreachable. mkdir -p ahead of the write, mirroring
        // `maintenance-prepare-live-flag-dir` below. It goes AHEAD of the write,
        // not in its place, to keep the amendment-A2 ordering: the shared flag is
        // still written first.
        if let Some(parent) = remote_parent_dir(&shared) {
            ops.push(exec::DeployOp::Run(exec::RemoteCommand::new(
                "maintenance-prepare-shared-flag-dir",
                format!("mkdir -p {}", exec::shell_quote(parent)),
            )));
        }
        let shared_index = ops.len();
        ops.push(exec::DeployOp::WriteFile {
            label: "maintenance-write-shared",
            contents: exec::FileContents::Plain(body.to_owned()),
            remote_path: shared,
            // 0600: the body can carry the `--bypass-header NAME:VALUE` token (a
            // credential that skips the 503 gate) and the `--allow-ips` list, and
            // this mode is applied to the local staging copy too. The flag is
            // written and read by the same `cfg.user` the slot unit runs as, so
            // 0600 is sufficient — same rule as the 0600 env file (AC-5).
            mode: Some(0o600),
        });
        if let Some(path) = &live_path {
            // The dir holding a pre-#1621 unit's flag (its `WorkingDirectory`'s
            // `tmp/`) may not exist yet — the runtime only creates it when IT
            // writes a flag — so mkdir -p first.
            if let Some(parent) = remote_parent_dir(path) {
                ops.push(exec::DeployOp::Run(exec::RemoteCommand::new(
                    "maintenance-prepare-live-flag-dir",
                    format!("mkdir -p {}", exec::shell_quote(parent)),
                )));
            }
            ops.push(exec::DeployOp::WriteFile {
                label: "maintenance-write-live-flag",
                contents: exec::FileContents::Plain(body.to_owned()),
                remote_path: path.clone(),
                // 0600 for the same reason as the shared write above.
                mode: Some(0o600),
            });
        }
        shared_index
    } else {
        // `rm -f` both paths in one op: absent files are the NORMAL case for at
        // least one of them (a host has either the new unit or the old), so a
        // missing file must never fail the `off`. No mkdir needed: `rm -f` does
        // not care that the parent does not exist.
        let mut paths = exec::shell_quote(&shared);
        if let Some(path) = &live_path {
            paths.push(' ');
            paths.push_str(&exec::shell_quote(path));
        }
        let shared_index = ops.len();
        ops.push(exec::DeployOp::Run(exec::RemoteCommand::new(
            "maintenance-clear",
            format!("rm -f {paths}"),
        )));
        shared_index
    };

    for (index, op) in ops.iter().enumerate() {
        if exec::run_ops(std::slice::from_ref(op), executor).is_err() {
            // The op label is known HERE regardless of the error's shape (an
            // upload failure carries no label), so the report can always name the
            // step without quoting the error.
            // A failure at or before the shared write leaves the host genuinely
            // UNCHANGED; failing anything after it means the shared flag landed
            // but the running unit's own file did not.
            let failed_step = op.label();
            return if index <= shared_index {
                fleet::MaintenanceOutcome::Failed { failed_step }
            } else {
                fleet::MaintenanceOutcome::LiveUnitUnchanged { failed_step }
            };
        }
    }
    match target {
        LiveFlagTarget::NoRelease => fleet::MaintenanceOutcome::AppliedSharedOnly,
        LiveFlagTarget::Path(_) => fleet::MaintenanceOutcome::Applied,
        // Fail closed. The shared flag changed, but a pre-#1621 unit would ignore
        // it, so this host must NOT be reported as maintained (or as released from
        // maintenance) when nothing proved which file it reads.
        LiveFlagTarget::Unproved => fleet::MaintenanceOutcome::LiveUnitUnchanged {
            failed_step: "detect-maintenance-flag",
        },
    }
}

/// The parent directory of a remote absolute path, or `None` when it has none.
fn remote_parent_dir(path: &str) -> Option<&str> {
    let (parent, _) = path.rsplit_once('/')?;
    (!parent.is_empty()).then_some(parent)
}

#[cfg(test)]
mod tests {
    // ── Tier 2 fail-fast on Windows (#1616) ────────────────────────────────
    //
    // The remote actions shell out to `ssh`/`sh`, and `up`, `rollback`, and
    // `maintenance` stage secrets with Unix file modes — `exec::stage_temp_file` skips
    // its `chmod 0600` off Unix — so a native Windows deploy would write the environment
    // file carrying the signing secret and database password without an owner-only mode.
    // That is exactly the silent degradation the platform policy forbids, so those
    // actions refuse up front.
    //
    // `check` and `plan` are the other half, and the half that first shipped wrong: they
    // are local-only, so refusing them claimed something untrue about the command and
    // took away the only way a Windows developer can validate a deploy config before
    // switching to WSL2.

    /// Every [`DeployAction`], for the completeness check below. The real gate
    /// is the wildcard-free match in `reaches_a_remote_host` — a new variant
    /// fails to compile until it is classified; this array only keeps the two
    /// lists in this module honest about covering it.
    const ALL_DEPLOY_ACTIONS: [DeployAction; 7] = [
        DeployAction::Check,
        DeployAction::Plan,
        DeployAction::Rollback,
        DeployAction::Up,
        DeployAction::Status,
        DeployAction::MaintenanceOn,
        DeployAction::MaintenanceOff,
    ];

    /// The actions that open an SSH session to a remote host. These are the
    /// Tier 2 surface: `up`/`rollback`/`maintenance` also stage secrets through
    /// `exec::stage_temp_file`, whose `chmod 0600` is `#[cfg(unix)]`.
    const REMOTE_ACTIONS: [DeployAction; 5] = [
        DeployAction::Up,
        DeployAction::Rollback,
        DeployAction::Status,
        DeployAction::MaintenanceOn,
        DeployAction::MaintenanceOff,
    ];

    /// The actions that never touch a remote host: `plan` renders the unit from
    /// `resolved` alone, and `check` grades config plus a portable
    /// `TcpStream::connect_timeout` reachability probe.
    const LOCAL_ACTIONS: [DeployAction; 2] = [DeployAction::Check, DeployAction::Plan];

    #[test]
    fn windows_deploys_are_refused_with_the_policy_message() {
        for action in REMOTE_ACTIONS {
            let refusal =
                windows_deploy_refusal("windows", action).expect("windows must be refused");
            assert!(refusal.contains("Tier 2 (WSL2)"), "{action:?}: {refusal}");
            assert!(
                refusal.contains(crate::platform::POLICY_DOC_URL),
                "{action:?}: {refusal}"
            );
        }
    }

    #[test]
    fn the_locally_verifiable_spine_runs_natively_on_windows() {
        // `deploy check` and `deploy plan` do NOT shell out to ssh and stage no
        // secrets — they grade config and render the unit. Refusing them would
        // take away the one way a Windows developer can validate a deploy config
        // before switching to WSL2 to run it, and it would be a false claim: they
        // work. (This is the regression the first green `windows-tier1` run hid,
        // because `Test (windows-latest)` had failed to link before reaching the
        // `integration::deploy::*` suite that proves it.)
        for action in LOCAL_ACTIONS {
            assert!(
                windows_deploy_refusal("windows", action).is_none(),
                "{action:?} is local-only and must run natively on Windows"
            );
        }
    }

    #[test]
    fn unix_deploys_are_not_refused() {
        for action in REMOTE_ACTIONS.iter().chain(LOCAL_ACTIONS.iter()).copied() {
            assert!(
                windows_deploy_refusal("linux", action).is_none(),
                "{action:?}"
            );
            assert!(
                windows_deploy_refusal("macos", action).is_none(),
                "{action:?}"
            );
        }
    }

    #[test]
    fn every_deploy_action_is_classified() {
        // A new `DeployAction` must be deliberately placed in one list or the
        // other. Without this, an added remote action would silently default to
        // "runs natively on Windows" — the silent degradation #1616 forbids.
        let classified = REMOTE_ACTIONS.len() + LOCAL_ACTIONS.len();
        assert_eq!(
            classified,
            ALL_DEPLOY_ACTIONS.len(),
            "every DeployAction must be classified as remote or local"
        );
        for action in ALL_DEPLOY_ACTIONS {
            assert!(
                REMOTE_ACTIONS.contains(&action) || LOCAL_ACTIONS.contains(&action),
                "{action:?} is not classified"
            );
        }
    }

    #[test]
    fn the_refusal_is_an_error_so_it_exits_non_zero() {
        // Fail *fast*: this must surface as an error the caller propagates,
        // never a warning printed before the deploy proceeds anyway.
        let err = DeployError::UnsupportedPlatform(
            windows_deploy_refusal("windows", DeployAction::Up).unwrap(),
        );
        assert!(err.to_string().contains("Tier 2 (WSL2)"));
    }

    #[test]
    fn the_refusal_does_not_masquerade_as_a_config_failure() {
        // `DeployError::Config` renders as "failed to load configuration: …",
        // which would send the operator hunting through autumn.toml for a
        // problem that is not there.
        let err = DeployError::UnsupportedPlatform(
            windows_deploy_refusal("windows", DeployAction::Up).unwrap(),
        );
        assert!(
            !err.to_string().contains("failed to load configuration"),
            "{err}"
        );
    }

    use super::*;

    fn resolved_defaults() -> ResolvedDeployConfig {
        ResolvedDeployConfig::resolve(&DeployConfig::default(), "myapp")
            .expect("deploy config resolves")
    }

    #[test]
    fn public_port_443_is_rejected_as_a_proxy_https_collision() {
        // kamal-proxy binds 443 for HTTPS by default (and can't disable it), so a
        // public/HTTP port of 443 collides and the proxy can't start — the guard
        // rejects it up front with an actionable message. It is unconditional (not
        // TLS-gated).
        let err = validate_public_port(443).expect_err("port 443 must be rejected");
        assert!(
            err.contains("443")
                && err.contains("HTTPS listener")
                && err.contains("proxy's HTTP listener"),
            "collision message must name 443/the HTTPS listener/the proxy HTTP port, got: {err}",
        );
        // A normal public port (the default 80, or any other) is accepted.
        assert!(validate_public_port(80).is_ok());
        assert!(validate_public_port(8080).is_ok());
    }

    #[test]
    fn public_ports_whose_slots_reach_443_are_rejected() {
        // Blue/green slots bind `public+1`/`public+2`, so 441 (green slot → 443)
        // and 442 (blue slot → 443) collide with the proxy's always-bound HTTPS
        // listener just as 443 itself does. All three are rejected unconditionally.
        let green = validate_public_port(441).expect_err("441 (green slot=443) rejected");
        assert!(
            green.contains("green app slot") && green.contains("443"),
            "441 message must name the green slot landing on 443, got: {green}",
        );
        let blue = validate_public_port(442).expect_err("442 (blue slot=443) rejected");
        assert!(
            blue.contains("blue app slot") && blue.contains("443"),
            "442 message must name the blue slot landing on 443, got: {blue}",
        );
        assert!(validate_public_port(443).is_err());
        // A safe non-{441,442,443} port is accepted — regardless of TLS, since the
        // guard is TLS-independent and TLS imposes no port requirement.
        assert!(validate_public_port(440).is_ok());
        assert!(validate_public_port(444).is_ok());
        assert!(validate_public_port(8080).is_ok());
    }

    #[test]
    fn tls_does_not_gate_the_public_port() {
        // There is NO TLS-gated port-80 requirement: per-app TLS is provisioned by
        // kamal-proxy on its always-bound 443 (TLS-ALPN-01), so a normal public
        // port is accepted whether or not `[deploy.tls]` is enabled. Only the
        // unconditional 443 collision applies.
        assert!(validate_public_port(80).is_ok());
        assert!(validate_public_port(3000).is_ok());
        assert!(validate_public_port(8080).is_ok());
    }

    #[test]
    fn redeploy_detects_a_concurrent_server_port_change() {
        // #2073 Option C. The installed proxy unit binds port 80; the operator now
        // redeploys with `server.port = 8080` — resolved to a `PublicPortMove` rather
        // than refused, naming old vs new port for the caller's later phase-4 rebind.
        let mv = resolve_public_port_move(&exec::InstalledProxyPort::Port(80), 8080)
            .expect("a changed server.port must resolve, not error")
            .expect("a changed server.port must be detected as a move");
        assert_eq!(mv.old_port, 80);
        assert_eq!(mv.new_port, 8080);
    }

    #[test]
    fn redeploy_allows_an_unchanged_server_port() {
        // The common durability-upgrade path: the installed unit's `--http-port` equals
        // the requested port, so there is no move (the restart re-execs on the SAME
        // port, no collision, derived == actual live port).
        assert_eq!(
            resolve_public_port_move(&exec::InstalledProxyPort::Port(80), 80),
            Ok(None),
            "an unchanged-port redeploy must resolve to no move",
        );
        // And with a non-default port that also happens to match.
        assert_eq!(
            resolve_public_port_move(&exec::InstalledProxyPort::Port(3000), 3000),
            Ok(None),
            "an unchanged non-default port must also resolve to no move",
        );
    }

    #[test]
    fn redeploy_fails_closed_on_an_unreadable_installed_port() {
        // The installed unit is present but its `--http-port` couldn't be read/parsed,
        // so we cannot prove which port (if any) needs moving — refuse (fail closed)
        // rather than risk the durability restart rebinding the wrong port and
        // stranding `:80`.
        let err = resolve_public_port_move(&exec::InstalledProxyPort::Unreadable, 80)
            .expect_err("an unreadable installed proxy port must fail closed");
        assert!(
            err.contains("could not be read"),
            "the fail-closed message must explain the unreadable unit: {err}",
        );
    }

    #[test]
    fn redeploy_allows_when_no_proxy_unit_is_installed() {
        // No installed proxy unit at all is a first-deploy shape (the durability refresh
        // writes it fresh at the requested port) — nothing to move, regardless of the
        // requested port.
        assert_eq!(
            resolve_public_port_move(&exec::InstalledProxyPort::Absent, 8080),
            Ok(None),
            "an absent installed proxy unit must resolve to no move",
        );
    }

    #[test]
    fn redeploy_moves_the_public_port_after_the_cutover_drains_the_old_release() {
        // #2073 Option C end-to-end: the installed proxy binds port 80, the config
        // requests `FLEET_PUBLIC_PORT` (3000). The cutover itself must plan entirely
        // against the OLD port 80 (live slot blue = 81, candidate slot green = 82 —
        // no collision with the still-live release), and the public-port move must
        // land strictly AFTER the old release drains.
        let fleet = fleet_of(&["web-a"]);
        let probe = "redeploy:blue\t81\n\
             ---autumn-kamal-proxy-list---\n\
             ---autumn-kamal-proxy-unit---\n--http-port 80\n"
            .to_owned();
        let recorder = fleet::test_support::FleetRecorder::new()
            .script("web-a", "proxy-compat-probe", compatible_deploy_help())
            .script("web-a", "detect-current", probe)
            .script("web-a", "probe-release-dir", "absent");
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect("a redeploy with a changed server.port succeeds (Option C)");

        let labels = recorder.run_labels_for("web-a");
        let drain = labels
            .iter()
            .position(|l| *l == "drain-old")
            .expect("the cutover drains the old release");
        // "proxy-restart-if-changed" runs TWICE: once as the cutover's OWN
        // durability-refresh call (a no-op through the unchanged OLD port), and once
        // as the phase-4 rebind. Both are unconditionally-present ops — the op
        // itself always runs; only its INNER shell script decides whether to
        // actually restart.
        let restarts: Vec<usize> = labels
            .iter()
            .enumerate()
            .filter(|(_, l)| **l == "proxy-restart-if-changed")
            .map(|(i, _)| i)
            .collect();
        assert_eq!(
            restarts.len(),
            2,
            "one restart-if-changed from the cutover's own durability refresh, one \
             from the phase-4 public-port rebind: {labels:?}"
        );
        assert!(
            restarts[0] < drain,
            "the durability-refresh restart-if-changed runs at the HEAD of the \
             cutover, before the old release ever drains: {labels:?}"
        );
        assert!(
            restarts[1] > drain,
            "the public-port move must run strictly AFTER the old release drains: \
             {labels:?}"
        );

        // The phase-4 re-register targets loopback 82 — the candidate's OWN port,
        // derived from the OLD public port (80 + green's +2) — now under the NEW
        // public port.
        let restart_shells: Vec<String> = recorder
            .calls_for("web-a")
            .iter()
            .filter_map(|c| match c {
                exec::test_support::RecordedCall::Run { label, shell }
                    if *label == "proxy-restart-if-changed" =>
                {
                    Some(shell.clone())
                }
                _ => None,
            })
            .collect();
        assert_eq!(restart_shells.len(), 2);
        assert!(
            restart_shells[1].contains("--target '127.0.0.1:82'"),
            "phase 4 re-registers the candidate's OWN loopback port: {}",
            restart_shells[1],
        );
    }

    #[test]
    fn a_public_port_rebind_failure_degrades_the_host_and_continues_the_rollout() {
        // #2073 Option C, fleet path: web-a's phase-4 rebind fails once (its FORWARD
        // restart, the label's 2nd occurrence — the 1st is the cutover's own
        // durability-refresh call, an unrelated no-op) but the rollback to the old
        // port succeeds. Traffic stays healthy at the old port, so the rollout
        // continues past web-a onto web-b.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let probe_a = "redeploy:blue\t81\n\
             ---autumn-kamal-proxy-list---\n\
             ---autumn-kamal-proxy-unit---\n--http-port 80\n"
            .to_owned();
        let recorder = fleet::test_support::FleetRecorder::new()
            .script("web-a", "proxy-compat-probe", compatible_deploy_help())
            .script("web-a", "detect-current", probe_a)
            .script("web-a", "probe-release-dir", "absent")
            .fail_on_occurrence("web-a", "proxy-restart-if-changed", 2);
        let recorder = script_redeploy(recorder, "web-b");
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect("a rolled-back port move degrades a host but never halts the rollout");

        let labels_a = recorder.run_labels_for("web-a");
        assert_eq!(
            labels_a
                .iter()
                .filter(|l| **l == "proxy-restart-if-changed")
                .count(),
            3,
            "one no-op from the cutover's own durability refresh, one FAILING phase-4 \
             forward attempt, one SUCCEEDING phase-4 rollback attempt: {labels_a:?}"
        );
        // The rollout continued past web-a's degradation onto web-b.
        assert!(
            recorder.run_labels_for("web-b").contains(&"drain-old"),
            "web-b must still be deployed after web-a degrades: {:?}",
            recorder.run_labels_for("web-b")
        );
    }

    #[test]
    fn a_public_port_rebind_double_failure_halts_the_rollout_as_manual() {
        // #2073 Option C, fleet path: web-a's phase-4 rebind fails AND its own
        // rollback ALSO fails (occurrences 2 and 3 of the label — occurrence 1, the
        // cutover's own durability-refresh call, still succeeds so the cutover
        // itself lands normally). The proxy's public bind on web-a is now unknown,
        // so the rollout halts rather than rolling forward onto web-b, and web-a is
        // reported `Manual` — never `Degraded` (which would falsely claim "traffic
        // is fine").
        let fleet = fleet_of(&["web-a", "web-b"]);
        let probe_a = "redeploy:blue\t81\n\
             ---autumn-kamal-proxy-list---\n\
             ---autumn-kamal-proxy-unit---\n--http-port 80\n"
            .to_owned();
        let recorder = fleet::test_support::FleetRecorder::new()
            .script("web-a", "proxy-compat-probe", compatible_deploy_help())
            .script("web-a", "detect-current", probe_a)
            .script("web-a", "probe-release-dir", "absent")
            .fail_on_occurrence("web-a", "proxy-restart-if-changed", 2)
            .fail_on_occurrence("web-a", "proxy-restart-if-changed", 3);
        let recorder = script_redeploy(recorder, "web-b");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a doubly-failed port move must halt the rollout");

        let halt = fleet_halt_of(&err);
        assert_eq!(halt.failed_host, "web-a");
        assert_eq!(halt.failed_step, "public-port-rebind");
        assert_eq!(
            halt.manual,
            vec![("web-a".to_owned(), fleet::MANUAL_PUBLIC_PORT_UNKNOWN)],
            "web-a must be reported Manual (needs a human), never Degraded, which \
             would falsely claim traffic is fine"
        );
        assert!(
            halt.degraded.is_empty(),
            "web-a's unknown public bind must not be counted as a healthy degradation: \
             {:?}",
            halt.degraded,
        );
        // web-b was graded (the fleet-wide probe phase runs before any host is
        // mutated) but never MUTATED — the halt happened at the first host.
        assert!(
            recorder
                .run_labels_for("web-b")
                .iter()
                .all(|l| READ_ONLY_PROBES.contains(l)),
            "web-b must not be mutated once the rollout halts at web-a: {:?}",
            recorder.run_labels_for("web-b")
        );
    }

    // --- proxy-options marker refuse / preserve decision (issue #2074) --------

    #[test]
    fn redeploy_fails_closed_on_an_unreadable_proxy_options_marker() {
        // The `shared/proxy-options` marker is present but unparseable, so the OLD
        // release's TLS/host can't be proved — a concurrent `deploy.tls.host` change
        // can't be safely preserved across the durability restart. Refuse (fail closed)
        // BEFORE any op runs, with the two-deploy repair guidance and the #2074 ref.
        let err = refuse_unprovable_proxy_options(&exec::ProxyOptionsMarker::Unreadable)
            .expect_err("an unreadable proxy-options marker must fail closed");
        assert!(
            err.contains("proxy-options") && err.contains("unreadable"),
            "the fail-closed message must name the unreadable proxy-options marker: {err}",
        );
        assert!(
            err.contains("deploy.tls unchanged") && err.contains("#2074"),
            "the message must spell out the two-deploy repair and reference #2074: {err}",
        );
    }

    #[test]
    fn redeploy_allows_an_absent_proxy_options_marker() {
        // A legacy host (or first deploy) never wrote the marker. Refusing would block
        // the FIRST redeploy of every pre-existing host — the deadlock #2074 rejects —
        // so an absent marker is ALLOWED (proceed as legacy: the deploy re-registers
        // with the new config and writes the marker, self-healing the next redeploy).
        assert!(
            refuse_unprovable_proxy_options(&exec::ProxyOptionsMarker::Absent).is_ok(),
            "an absent proxy-options marker must not trigger the refuse",
        );
    }

    #[test]
    fn redeploy_allows_a_readable_proxy_options_marker() {
        // A present, parseable marker is exactly the preserve path — it never refuses,
        // whether the recorded options match the new config or not (the re-register
        // simply carries the recorded options).
        let unchanged = exec::ProxyOptionsMarker::Options(exec::ProxyServiceOptions {
            tls: true,
            host: Some("app.example.com".to_owned()),
        });
        assert!(
            refuse_unprovable_proxy_options(&unchanged).is_ok(),
            "an unchanged readable marker must be allowed (preserve is a no-op)",
        );
        let changed = exec::ProxyOptionsMarker::Options(exec::ProxyServiceOptions {
            tls: false,
            host: None,
        });
        assert!(
            refuse_unprovable_proxy_options(&changed).is_ok(),
            "a readable marker whose options differ from the new config is still allowed \
             (the old options are preserved, not refused)",
        );
    }

    #[test]
    fn resolve_fills_default_chain_from_project_name() {
        let resolved = resolved_defaults();
        assert_eq!(resolved.app_name, "myapp");
        assert_eq!(resolved.app_dir, "/srv/autumn/myapp");
        assert_eq!(resolved.service_name, "myapp");
        assert_eq!(resolved.user, "root");
        assert_eq!(resolved.ssh_port, 22);
        assert_eq!(resolved.readiness_timeout_secs, 60);
        assert_eq!(resolved.keep_releases, 3);
        assert_eq!(resolved.host, None);
        assert_eq!(resolved.profile, "prod");
        // TLS is opt-in: an absent `[deploy.tls]` table leaves it disabled.
        assert!(!resolved.tls_enabled);
        assert_eq!(resolved.tls_host, None);
    }

    #[test]
    fn tls_absent_table_leaves_tls_disabled() {
        // The default `DeployConfig` (no `[deploy.tls]`) resolves to TLS off with
        // no host — byte-for-byte the historical HTTP-only behavior.
        let resolved = resolved_defaults();
        assert!(!resolved.tls_enabled);
        assert_eq!(resolved.tls_host, None);
    }

    #[test]
    fn tls_enabled_with_host_resolves_tls_host() {
        let cfg = DeployConfig {
            tls: autumn_web::config::DeployTlsConfig {
                enabled: true,
                host: Some("app.example.com".to_owned()),
            },
            ..DeployConfig::default()
        };
        let resolved =
            ResolvedDeployConfig::resolve(&cfg, "myapp").expect("enabled + host resolves");
        assert!(resolved.tls_enabled);
        assert_eq!(resolved.tls_host.as_deref(), Some("app.example.com"));
    }

    #[test]
    fn tls_enabled_without_host_is_a_resolve_error() {
        // Enabling TLS without a hostname cannot provision a certificate — a hard
        // resolve-time error, before any remote command runs.
        for host in [None, Some(String::new()), Some("   ".to_owned())] {
            let cfg = DeployConfig {
                tls: autumn_web::config::DeployTlsConfig {
                    enabled: true,
                    host,
                },
                ..DeployConfig::default()
            };
            let err = ResolvedDeployConfig::resolve(&cfg, "myapp")
                .expect_err("enabled TLS without a host must be rejected");
            assert!(
                err.contains("[deploy.tls]") && err.contains("host"),
                "error should name the section and the missing key, got: {err}",
            );
        }
    }

    #[test]
    fn host_preparation_is_on_by_default_and_declinable() {
        // #1607 (AC-1): the documented target-host precondition is at most a stock
        // Ubuntu LTS with SSH access, so preparing the host is the DEFAULT. The
        // opt-out exists for operators who provision the proxy themselves.
        assert!(
            resolved_defaults().install_proxy,
            "a bare `[deploy]` table must prepare the host"
        );
        assert_eq!(
            provisioning(&resolved_defaults()),
            exec::ProxyProvisioning::Auto
        );

        let declined = ResolvedDeployConfig::resolve(
            &DeployConfig {
                install_proxy: false,
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("declining host prep resolves");
        assert!(!declined.install_proxy);
        assert_eq!(provisioning(&declined), exec::ProxyProvisioning::Disabled);
    }

    // ── fleet host list (#1621) ───────────────────────────────────

    /// A `[deploy]` config carrying only the fleet list, so the fleet tests read
    /// as the TOML an operator would write.
    fn fleet_cfg(hosts: &[&str]) -> DeployConfig {
        DeployConfig {
            hosts: hosts.iter().map(|h| (*h).to_owned()).collect(),
            ..DeployConfig::default()
        }
    }

    #[test]
    fn fleet_resolve_keeps_declaration_order_as_the_rollout_order() {
        // #1621 (AC-1/AC-2): the order of `[deploy] hosts` IS the rollout order —
        // it is a documented contract, not an implementation detail, so resolution
        // must never sort or dedupe-reorder it.
        let fleet = ResolvedFleet::resolve(&fleet_cfg(&["web-3", "web-1", "web-2"]), "myapp")
            .expect("a well-formed fleet resolves");
        let hosts: Vec<Option<&str>> = fleet.hosts.iter().map(|h| h.host.as_deref()).collect();
        assert_eq!(
            hosts,
            vec![Some("web-3"), Some("web-1"), Some("web-2")],
            "fleet resolution must preserve declaration order, got: {hosts:?}"
        );
        assert!(
            !fleet.is_single(),
            "a 3-host fleet must not report as single-host, got: {:?}",
            fleet.hosts.len()
        );
    }

    #[test]
    fn fleet_resolve_rejects_host_and_hosts_set_together_naming_both_keys() {
        // #1621 (AC-1): the two spellings are mutually exclusive — with both set
        // the rollout order is ambiguous, so this fails closed BEFORE any remote
        // command runs, naming both keys so the operator knows what to delete.
        let cfg = DeployConfig {
            host: Some("203.0.113.10".to_owned()),
            hosts: vec!["web-1.example.com".to_owned()],
            ..DeployConfig::default()
        };
        let err = ResolvedFleet::resolve(&cfg, "myapp")
            .expect_err("host + hosts together must be rejected");
        assert!(
            err.contains("[deploy] host") && err.contains("[deploy] hosts"),
            "the mutual-exclusion error must name BOTH keys, got: {err}"
        );
        assert!(
            err.contains("#1621"),
            "fail-closed refusals cite the tracking issue, got: {err}"
        );
    }

    #[test]
    fn fleet_resolve_rejects_a_blank_hosts_entry_naming_its_index() {
        // #1621 (AC-1): a blank entry would resolve to a hostless SSH target and
        // fail mid-rollout with hosts already cut over. The index is 0-based and
        // named so the operator can find the offending line in a long list.
        for (index, hosts) in [
            (0_usize, vec![String::new(), "web-2".to_owned()]),
            (1, vec!["web-1".to_owned(), "   ".to_owned()]),
            (
                2,
                vec!["web-1".to_owned(), "web-2".to_owned(), "\t".to_owned()],
            ),
        ] {
            let cfg = DeployConfig {
                hosts,
                ..DeployConfig::default()
            };
            let err = ResolvedFleet::resolve(&cfg, "myapp")
                .expect_err("a blank hosts entry must be rejected");
            assert!(
                err.contains("[deploy] hosts") && err.contains(&format!("{index}")),
                "the blank-entry error must name the key and the 0-based index {index}, got: {err}"
            );
        }
    }

    #[test]
    fn fleet_resolve_rejects_duplicate_hosts_after_trimming_naming_the_value() {
        // #1621 (AC-1/AC-3): deploying the same machine twice makes the second
        // pass see its OWN new release as live, ping-pongs the blue/green slots and
        // corrupts the previous-release chain a fleet rollback depends on. Trim
        // first so `"web-1"` and `" web-1 "` are recognised as the same host.
        // (Literal duplicates only — DNS aliases are a documented limitation.)
        let cfg = fleet_cfg(&["web-1.example.com", "web-2", " web-1.example.com "]);
        let err = ResolvedFleet::resolve(&cfg, "myapp")
            .expect_err("a duplicate hosts entry must be rejected");
        assert!(
            err.contains("web-1.example.com"),
            "the duplicate error must name the repeated value, got: {err}"
        );
        assert!(
            err.contains("[deploy] hosts"),
            "the duplicate error must name the config key, got: {err}"
        );
    }

    #[test]
    fn fleet_resolve_without_any_host_keeps_the_deploy_host_message() {
        // #1621 (AC-1): with neither key set the operator sees the SAME
        // missing-host text as before, EXTENDED to mention the fleet spelling. The
        // literal substring "[deploy] host" is asserted by
        // `deploy_check_fails_fast_without_host` and quoted in operator runbooks,
        // so it must survive the extension verbatim.
        let err = ResolvedFleet::resolve(&DeployConfig::default(), "myapp")
            .expect_err("no host and no hosts must be rejected");
        assert!(
            err.contains("[deploy] host"),
            "the missing-target error must keep the historical `[deploy] host` \
             substring, got: {err}"
        );
        assert!(
            err.contains("hosts"),
            "the missing-target error must also offer the fleet spelling, got: {err}"
        );

        // A blank scalar host is the same case as an absent one.
        let blank = DeployConfig {
            host: Some("   ".to_owned()),
            ..DeployConfig::default()
        };
        let blank_err = ResolvedFleet::resolve(&blank, "myapp")
            .expect_err("a blank host must be rejected like an absent one");
        assert!(
            blank_err.contains("[deploy] host"),
            "a blank host must report the missing-target message, got: {blank_err}"
        );
    }

    #[test]
    fn single_entry_hosts_resolves_to_the_same_view_as_host() {
        // #1621 (AC-1, proof P5): a one-entry `hosts` list is byte-for-byte the
        // historical single-server deploy. Value equality against
        // `ResolvedDeployConfig::resolve` of the equivalent `host` config is the
        // structural guarantee — everything below `SshTarget::from_resolved` then
        // behaves identically by construction.
        let single = DeployConfig {
            host: Some("203.0.113.10".to_owned()),
            app_name: Some("shop".to_owned()),
            user: "deploy".to_owned(),
            ssh_port: 2222,
            readiness_timeout_secs: 90,
            keep_releases: 5,
            profile: "staging".to_owned(),
            ..DeployConfig::default()
        };
        let fleet_cfg = DeployConfig {
            host: None,
            hosts: vec!["203.0.113.10".to_owned()],
            ..single.clone()
        };

        let expected =
            ResolvedDeployConfig::resolve(&single, "myapp").expect("single host resolves");
        let fleet =
            ResolvedFleet::resolve(&fleet_cfg, "myapp").expect("single-entry fleet resolves");
        assert!(
            fleet.is_single(),
            "a one-entry hosts list must report as single-host, got {} hosts",
            fleet.hosts.len()
        );
        assert_eq!(
            fleet.hosts[0], expected,
            "a one-entry `hosts` list must resolve to exactly the `host` view; \
             fleet: {:?}, single: {expected:?}",
            fleet.hosts[0]
        );
    }

    /// A minimal loaded config for the preflight graders — no DB, no migrations,
    /// no secret — so the three project graders return stable, host-independent
    /// results and the assertions below are about SCOPE, not grading.
    fn preflight_config() -> AutumnConfig {
        AutumnConfig::default()
    }

    // ── SQLite data-file persistence (issue #1909) ─────────────────────────

    fn deploy_cfg() -> ResolvedDeployConfig {
        ResolvedDeployConfig::resolve(
            &DeployConfig {
                host: Some("203.0.113.10".to_owned()),
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("deploy config resolves")
    }

    #[test]
    fn classify_sqlite_data_file_separates_relative_absolute_and_not_sqlite() {
        let cfg = deploy_cfg();
        // A relative path resolves against the slot unit's WorkingDirectory (the
        // release dir), so it is the case the deploy has to relocate.
        for relative in ["sqlite://app.db", "sqlite://./app.db", "sqlite:data/app.db"] {
            assert!(
                matches!(
                    classify_sqlite_data_file(Some(relative), &cfg),
                    SqliteDataFile::Relative(_)
                ),
                "{relative}"
            );
        }
        // Spellings that name the same file normalize to one `ln -s` target.
        for spelling in ["sqlite://./app.db", "sqlite://app.db"] {
            assert_eq!(
                classify_sqlite_data_file(Some(spelling), &cfg),
                SqliteDataFile::Relative("app.db".to_owned()),
                "{spelling}"
            );
        }
        for spelling in [
            "sqlite://data/app.db",
            "sqlite://data//app.db",
            "sqlite://data/./app.db",
            "sqlite://data/nested/../app.db",
        ] {
            assert_eq!(
                classify_sqlite_data_file(Some(spelling), &cfg),
                SqliteDataFile::Relative("data/app.db".to_owned()),
                "{spelling}"
            );
        }
        // A `file:` URI is percent-decoded, because that is what SQLite opens.
        assert_eq!(
            classify_sqlite_data_file(Some("file:app%20data.db?mode=rwc"), &cfg),
            SqliteDataFile::Relative("app data.db".to_owned())
        );
        // An absolute path outside the app dir already survives a deploy.
        assert_eq!(
            classify_sqlite_data_file(Some("sqlite:///var/lib/myapp/app.db"), &cfg),
            SqliteDataFile::Persistent("/var/lib/myapp/app.db".to_owned())
        );
        // …as does one the operator put in the deploy's own persistent dir.
        assert_eq!(
            classify_sqlite_data_file(Some("sqlite:///srv/autumn/myapp/shared/data/app.db"), &cfg),
            SqliteDataFile::Persistent("/srv/autumn/myapp/shared/data/app.db".to_owned())
        );
        // Postgres and an unconfigured URL are not this grader's business.
        for other in [Some("postgres://u:p@h/app"), Some("   "), None] {
            assert_eq!(
                classify_sqlite_data_file(other, &cfg),
                SqliteDataFile::NotSqlite,
                "{other:?}"
            );
        }
    }

    /// The deploy target is always a POSIX host, so path grading must not follow
    /// the host this CLI runs on. `std::path` would: on Windows
    /// `Path::new("/srv/app.db").is_absolute()` is false, so every absolute
    /// target would be graded as a relative one and `autumn deploy check` from a
    /// Windows workstation would misjudge the Linux host it deploys to.
    #[test]
    fn path_grading_uses_posix_rules_on_every_host() {
        assert_eq!(
            lexically_normalized("/srv/autumn/myapp/shared/../releases/r1/app.db"),
            "/srv/autumn/myapp/releases/r1/app.db"
        );
        assert_eq!(
            lexically_normalized("./data//nested/../app.db"),
            "data/app.db"
        );
        // POSIX defines `/..` as `/`, so an ABSOLUTE path cannot climb out —
        // `/a/../..` is `/`. Returning `None` here made a real `app_dir`
        // spelling ungradable and the caller then called a database in the
        // releases dir durable.
        assert_eq!(
            lexically_normalized("/a/../.."),
            "/",
            "an absolute path cannot climb above the root"
        );
        assert_eq!(
            lexically_normalized("/../srv/autumn/myapp"),
            "/srv/autumn/myapp",
            "a leading `..` on an absolute path is dropped, as POSIX does"
        );
        assert_eq!(lexically_normalized("../app.db"), "../app.db");
        assert_eq!(lexically_normalized("."), "");
        // A leading `/` means absolute here, whatever the host says.
        assert!(
            lexically_normalized("/var/lib/app.db").starts_with('/'),
            "a POSIX absolute path must stay absolute"
        );
    }

    #[test]
    fn classify_sqlite_data_file_refuses_what_a_deploy_cannot_keep() {
        let cfg = deploy_cfg();
        // In-memory: gone at the next restart, deploy or no deploy.
        let memory = classify_sqlite_data_file(Some("sqlite::memory:"), &cfg);
        let SqliteDataFile::Refused(detail) = memory else {
            panic!("an in-memory database must be refused, got {memory:?}");
        };
        assert!(detail.contains("IN-MEMORY"), "{detail}");

        // Anything the deploy manages is transient: `releases/` is pruned by
        // retention, and `current` is only a symlink into it — a path through
        // `current` is inside the live release dir, whatever it looks like.
        for inside in [
            "sqlite:///srv/autumn/myapp/releases/20260714T120000Z/app.db",
            "sqlite:///srv/autumn/myapp/current/app.db",
            "sqlite:///srv/autumn/myapp/app.db",
        ] {
            let got = classify_sqlite_data_file(Some(inside), &cfg);
            let SqliteDataFile::Refused(detail) = got else {
                panic!("{inside} must be refused, got {got:?}");
            };
            assert!(
                detail.contains("/srv/autumn/myapp") && detail.contains("shared/data"),
                "the refusal must name the problem and the fix: {detail}"
            );
        }
        // …but a sibling path that merely SHARES the prefix is fine.
        assert!(matches!(
            classify_sqlite_data_file(Some("sqlite:///srv/autumn/myapp-staging/app.db"), &cfg),
            SqliteDataFile::Persistent(_)
        ));

        // `..` must be resolved BEFORE the containment check: this one reads as
        // `shared/` lexically but the kernel resolves it into `releases/`.
        let sneaky = classify_sqlite_data_file(
            Some("sqlite:///srv/autumn/myapp/shared/../releases/r1/app.db"),
            &cfg,
        );
        let SqliteDataFile::Refused(detail) = sneaky else {
            panic!("a path that resolves into releases/ must be refused, got {sneaky:?}");
        };
        assert!(
            detail.contains("/srv/autumn/myapp/releases/r1/app.db"),
            "the refusal must name the RESOLVED path: {detail}"
        );
        // The mirror image: a `..` that resolves back OUT of the app dir is fine,
        // and the normalized text is what the deploy uses.
        assert_eq!(
            classify_sqlite_data_file(
                Some("sqlite:///srv/autumn/myapp/../shared-data/app.db"),
                &cfg
            ),
            SqliteDataFile::Persistent("/srv/autumn/shared-data/app.db".to_owned())
        );
        // An absolute path cannot climb above the root: POSIX resolves
        // `/../../app.db` to `/app.db`, which is outside the app dir and so is
        // the operator's own file, left alone.
        assert_eq!(
            classify_sqlite_data_file(Some("sqlite:///../../app.db"), &cfg),
            SqliteDataFile::Persistent("/app.db".to_owned())
        );

        // A run of spaces mid-sentence means a `\\` continuation was dropped when
        // the message was written (same guard as `DeployError`'s own).
        for refused in [
            "sqlite::memory:",
            "sqlite:///srv/autumn/myapp/current/app.db",
            "sqlite://..",
        ] {
            if let SqliteDataFile::Refused(detail) = classify_sqlite_data_file(Some(refused), &cfg)
            {
                assert!(!detail.contains("   "), "{refused}: {detail}");
            }
        }

        // A relative path must name a FILE inside the release dir: `..` climbs out
        // of it, and a `.`-only path names the directory itself, which the link op
        // would then try to replace.
        for bad in [
            "sqlite://../../app.db",
            "sqlite://.",
            "sqlite://./",
            "sqlite://data/../..",
        ] {
            let got = classify_sqlite_data_file(Some(bad), &cfg);
            assert!(
                matches!(got, SqliteDataFile::Refused(_)),
                "{bad} must be refused, got {got:?}"
            );
        }
    }

    /// `[deploy] app_dir` can carry lexical aliases too. Comparing the raw
    /// spelling would let a database sitting in the releases dir it resolves to
    /// pass as durable, and release retention would then delete it.
    /// `/..` is `/` in POSIX, so an `app_dir` spelled `/../srv/autumn/myapp`
    /// names `/srv/autumn/myapp` and must grade exactly like it.
    ///
    /// The normalizer used to return `None` for that spelling and the caller
    /// `unwrap_or_default()`ed it, which skipped the containment check and fell
    /// through to `Persistent` — calling a database in the releases dir durable
    /// while release retention deletes it.
    #[test]
    fn an_app_dir_that_starts_above_root_still_grades_containment() {
        let aliased = ResolvedDeployConfig::resolve(
            &DeployConfig {
                host: Some("203.0.113.10".to_owned()),
                app_dir: Some("/../srv/autumn/myapp".to_owned()),
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("resolves");
        // Inside the releases dir the alias resolves to: refused, not "durable".
        let inside = classify_sqlite_data_file(
            Some("sqlite:///srv/autumn/myapp/releases/r1/app.db"),
            &aliased,
        );
        assert!(
            matches!(inside, SqliteDataFile::Refused(_)),
            "a database in the releases dir must be refused, got: {inside:?}"
        );
        // The shared dir is still durable through the same alias.
        assert!(
            matches!(
                classify_sqlite_data_file(
                    Some("sqlite:///srv/autumn/myapp/shared/data/app.db"),
                    &aliased,
                ),
                SqliteDataFile::Persistent(_)
            ),
            "the shared dir must stay durable through the aliased app dir"
        );
        // And a path genuinely outside is still the operator's own.
        assert!(
            matches!(
                classify_sqlite_data_file(Some("sqlite:///var/lib/app.db"), &aliased),
                SqliteDataFile::Persistent(_)
            ),
            "a path outside the app dir is left alone"
        );
    }

    /// An app dir that cannot be graded must FAIL CLOSED. Grading it durable is
    /// the dangerous direction: it is the answer that lets a deploy delete the
    /// database it just called safe.
    #[test]
    fn an_ungradable_app_dir_refuses_rather_than_claiming_durability() {
        let relative = ResolvedDeployConfig::resolve(
            &DeployConfig {
                host: Some("203.0.113.10".to_owned()),
                app_dir: Some("srv/autumn/myapp".to_owned()),
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("resolves");
        let graded = classify_sqlite_data_file(
            Some("sqlite:///srv/autumn/myapp/releases/r1/app.db"),
            &relative,
        );
        assert!(
            matches!(graded, SqliteDataFile::Refused(_)),
            "a non-absolute app dir must refuse, never grade Persistent: {graded:?}"
        );
    }

    #[test]
    fn classify_sqlite_data_file_normalizes_the_app_dir_as_well() {
        let aliased = ResolvedDeployConfig::resolve(
            &DeployConfig {
                host: Some("203.0.113.10".to_owned()),
                app_dir: Some("/srv/autumn/tmp/../myapp/".to_owned()),
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("resolves");

        let inside = classify_sqlite_data_file(
            Some("sqlite:///srv/autumn/myapp/releases/r1/app.db"),
            &aliased,
        );
        let SqliteDataFile::Refused(detail) = inside else {
            panic!("a database in the resolved releases dir must be refused, got {inside:?}");
        };
        assert!(
            detail.contains("/srv/autumn/myapp"),
            "the refusal must name the RESOLVED app dir: {detail}"
        );
        // The deploy's own persistent dir still passes, aliased spelling or not.
        assert!(matches!(
            classify_sqlite_data_file(
                Some("sqlite:///srv/autumn/myapp/shared/data/app.db"),
                &aliased
            ),
            SqliteDataFile::Persistent(_)
        ));
        // …and a path genuinely outside it is still the operator's own.
        assert!(matches!(
            classify_sqlite_data_file(Some("sqlite:///var/lib/myapp/app.db"), &aliased),
            SqliteDataFile::Persistent(_)
        ));
    }

    /// A relative database whose path is also a file the deploy uploads into the
    /// release dir is refused (#2589 item 11).
    ///
    /// `link-data` runs before the uploads and `scp` writes THROUGH a symlink, so
    /// the link is made first and the upload truncates the operator's database.
    /// The migration then finds an ELF or a TOML file where the database was,
    /// after the data is already gone. Preflight refuses it before any remote
    /// command runs.
    #[test]
    fn classify_sqlite_data_file_refuses_a_collision_with_a_release_payload() {
        let cfg = deploy_cfg().with_release_payloads(vec!["prod.lock".to_owned()]);

        for (url, expected) in [
            // The app binary, uploaded at `<release>/<app_name>`.
            ("sqlite://myapp", "myapp binary"),
            // The manifest family, matched by shape rather than by enumeration:
            // a database named `autumn.toml` must be refused on a project that
            // has no `autumn.toml` YET, since adding one starts truncating it.
            ("sqlite://autumn.toml", "autumn.toml"),
            ("sqlite://autumn-prod.toml", "autumn-prod.toml"),
            ("sqlite://autumn-Production.toml", "autumn-Production.toml"),
            // And whatever else this particular deploy uploads — a capacity
            // contract carries an arbitrary configured name that no static rule
            // could predict.
            ("sqlite://prod.lock", "prod.lock"),
        ] {
            let got = classify_sqlite_data_file(Some(url), &cfg);
            let SqliteDataFile::Refused(detail) = got else {
                panic!("{url} collides with a release payload but was graded {got:?}");
            };
            assert!(
                detail.contains(expected),
                "{url}: the refusal must name what it collides with: {detail}"
            );
        }

        // A normalized spelling collides just the same.
        assert!(matches!(
            classify_sqlite_data_file(Some("sqlite://./autumn.toml"), &cfg),
            SqliteDataFile::Refused(_)
        ));

        // Every payload is written FLAT in the release root, so a subdirectory
        // cannot collide — and that is the fix the refusal points the operator at.
        for safe in [
            "sqlite://app.db",
            "sqlite://data/myapp",
            "sqlite://data/autumn.toml",
            "sqlite://autumn.db",
            "sqlite://autumn-prod.db",
            // Not the manifest shape: no name between the prefix and the suffix.
            "sqlite://autumn-.toml",
        ] {
            assert!(
                matches!(
                    classify_sqlite_data_file(Some(safe), &cfg),
                    SqliteDataFile::Relative(_)
                ),
                "{safe} cannot collide with a release payload and must be kept"
            );
        }
    }

    /// The deploy owns `shared/` — only `shared/data` is the app's (#2589 round 18).
    ///
    /// `shared/` survives a release swap, which is why it was allowed, but the
    /// deploy writes its own state files there: `autumn.env` (the SECRET env
    /// file), `live-slot`, `previous-release`, `proxy-options`, `last-deploy`,
    /// the maintenance flag and the adoption marker. A database configured at one
    /// of those paths passed every containment check and was then truncated by
    /// the deploy step that writes it, before the migration ran.
    ///
    /// Asserted as a CLOSED namespace rather than a list of reserved names: a
    /// list would need revisiting every time a control file is added, which is
    /// the failure mode this grader kept hitting.
    #[test]
    fn classify_sqlite_data_file_refuses_deploy_owned_paths_under_shared() {
        let cfg = deploy_cfg();
        for owned in [
            "sqlite:///srv/autumn/myapp/shared/autumn.env",
            "sqlite:///srv/autumn/myapp/shared/live-slot",
            "sqlite:///srv/autumn/myapp/shared/previous-release",
            "sqlite:///srv/autumn/myapp/shared/proxy-options",
            "sqlite:///srv/autumn/myapp/shared/last-deploy",
            "sqlite:///srv/autumn/myapp/shared/sqlite-data-adopted",
            // Anything else the deploy might put there later, without this test
            // or the grader needing to learn its name.
            "sqlite:///srv/autumn/myapp/shared/some-future-state-file",
            "sqlite:///srv/autumn/myapp/shared/app.db",
        ] {
            let got = classify_sqlite_data_file(Some(owned), &cfg);
            let SqliteDataFile::Refused(detail) = got else {
                panic!("{owned} is a deploy-owned path but graded {got:?}");
            };
            assert!(
                detail.contains("/srv/autumn/myapp/shared/data"),
                "{owned}: the refusal must name where the database may live: {detail}"
            );
        }

        // `shared/data` itself, and anything under it, is still the app's.
        for ours in [
            "sqlite:///srv/autumn/myapp/shared/data/app.db",
            "sqlite:///srv/autumn/myapp/shared/data/nested/app.db",
        ] {
            assert!(
                matches!(
                    classify_sqlite_data_file(Some(ours), &cfg),
                    SqliteDataFile::Persistent(_)
                ),
                "{ours} must still be kept"
            );
        }
        // …and so is anything genuinely outside the app dir.
        assert!(matches!(
            classify_sqlite_data_file(Some("sqlite:///var/lib/myapp/app.db"), &cfg),
            SqliteDataFile::Persistent(_)
        ));
    }

    /// A payload as the FIRST path component, not only as the whole path
    /// (#2589 round 18).
    ///
    /// `scp <local> <release>/myapp` writes *into* `<release>/myapp` when a
    /// directory is there. So `sqlite://myapp/myapp` has `link-data` create
    /// `myapp/` and put the database link at `myapp/myapp` — exactly where the
    /// upload lands, following the link and replacing the database with the
    /// binary. The earlier rule returned `None` for every path containing `/`.
    #[test]
    fn classify_sqlite_data_file_refuses_a_payload_as_a_leading_component() {
        let cfg = deploy_cfg().with_release_payloads(vec!["prod.lock".to_owned()]);

        for url in [
            "sqlite://myapp/myapp",
            "sqlite://myapp/app.db",
            "sqlite://myapp/nested/app.db",
            "sqlite://autumn.toml/app.db",
            "sqlite://autumn-prod.toml/app.db",
            "sqlite://prod.lock/app.db",
            // The single-component case is just this rule with one segment.
            "sqlite://myapp",
            // And a spelling that normalizes onto one.
            "sqlite://./myapp/app.db",
        ] {
            assert!(
                matches!(
                    classify_sqlite_data_file(Some(url), &cfg),
                    SqliteDataFile::Refused(_)
                ),
                "{url}: a release payload as the leading component is written through"
            );
        }

        // A directory that is NOT a payload is still fine, at any depth.
        for safe in [
            "sqlite://data/app.db",
            "sqlite://data/myapp",
            "sqlite://data/autumn.toml",
            "sqlite://myapp.db",
        ] {
            assert!(
                matches!(
                    classify_sqlite_data_file(Some(safe), &cfg),
                    SqliteDataFile::Relative(_)
                ),
                "{safe} cannot collide and must be kept"
            );
        }
    }

    /// A relative `app_dir` is refused for a RELATIVE database too, not just an
    /// absolute one (#2589 item 16).
    ///
    /// The guard that decides containment for an absolute database also decides
    /// the LINK TARGET for a relative one: `sqlite_data_link_op` points the
    /// release at `{app_dir}/shared/data/<file>`, so a relative `app_dir` makes
    /// that target resolve beneath the release directory instead of the SSH
    /// working directory. The migration then opens a dangling link and the deploy
    /// fails after it has already touched the host.
    #[test]
    fn classify_sqlite_data_file_refuses_a_relative_app_dir_on_both_branches() {
        let relative_dir = ResolvedDeployConfig::resolve(
            &DeployConfig {
                host: Some("203.0.113.10".to_owned()),
                app_dir: Some("myapp".to_owned()),
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("resolves");

        for url in [
            // The branch the guard was originally written for…
            "sqlite:///var/lib/myapp/app.db",
            // …and the one it was missing.
            "sqlite://app.db",
            "sqlite://data/app.db",
        ] {
            let got = classify_sqlite_data_file(Some(url), &relative_dir);
            let SqliteDataFile::Refused(detail) = got else {
                panic!("a relative app_dir makes {url} undecidable, but it graded {got:?}");
            };
            assert!(
                detail.contains("myapp") && detail.contains("absolute"),
                "{url}: the refusal must name the app dir and the fix: {detail}"
            );
        }

        // A Postgres app is unaffected: the app dir is never consulted.
        assert!(matches!(
            classify_sqlite_data_file(Some("postgres://localhost/app"), &relative_dir),
            SqliteDataFile::NotSqlite
        ));
    }

    /// A deploy addresses paths as text, so one it cannot render it cannot ship.
    /// `file:app%FF.db` decodes to exactly such a name.
    #[cfg(unix)]
    #[test]
    fn classify_sqlite_data_file_refuses_a_non_utf8_path() {
        let got = classify_sqlite_data_file(Some("file:app%FF.db"), &deploy_cfg());
        let SqliteDataFile::Refused(detail) = got else {
            panic!("a non-UTF-8 path must be refused, got {got:?}");
        };
        assert!(detail.contains("not valid UTF-8"), "{detail}");
    }

    #[test]
    fn sqlite_data_persistence_grader_is_emitted_only_for_a_sqlite_app() {
        let cfg = deploy_cfg();

        // A Postgres deploy's preflight report must be byte-identical to
        // pre-#1909: no extra row at all.
        assert!(grade_sqlite_data_persistence(Some("postgres://h/app"), &cfg).is_none());
        assert!(grade_sqlite_data_persistence(None, &cfg).is_none());

        let pass = grade_sqlite_data_persistence(Some("sqlite://app.db"), &cfg)
            .expect("a SQLite app is graded");
        assert_eq!(pass.name, "sqlite_data_file");
        assert!(pass.passed, "a relative path is kept, not refused");
        assert!(
            pass.detail.contains("/srv/autumn/myapp/shared/data/app.db"),
            "the pass must name where the file is kept: {}",
            pass.detail
        );

        for refused in [
            "sqlite::memory:",
            "sqlite:///srv/autumn/myapp/current/app.db",
        ] {
            let fail =
                grade_sqlite_data_persistence(Some(refused), &cfg).expect("a SQLite app is graded");
            assert!(!fail.passed, "{refused} must fail preflight");
        }
    }

    #[test]
    fn preflight_scope_is_none_for_one_host_and_the_host_for_a_fleet() {
        // #1621 (T1.24, plan §5.2): `scope` is the additive field that lets a fleet
        // name WHICH host a per-host grader graded, without touching
        // `PreflightCheck::name` — an operator-visible `doctor --json` contract.
        //
        // It is `None` for a single-host fleet, which is what keeps `deploy check`
        // output byte-identical to pre-#1621 (AC-1, artifact 4). Do not "simplify"
        // this to always-Some.
        let config = preflight_config();

        let one = ResolvedFleet::resolve(&fleet_cfg(&["web-1.example.test"]), "myapp")
            .expect("one-host fleet resolves");
        let checks = collect_fleet_preflight(&config, &one, 1);
        assert!(
            checks.iter().all(|check| check.scope.is_none()),
            "a single-host fleet must carry no scope (AC-1): {:?}",
            checks
                .iter()
                .map(|c| (c.name, &c.scope))
                .collect::<Vec<_>>()
        );

        let many = ResolvedFleet::resolve(
            &fleet_cfg(&["web-1.example.test", "web-2.example.test"]),
            "myapp",
        )
        .expect("two-host fleet resolves");
        let checks = collect_fleet_preflight(&config, &many, 2);
        let scoped: Vec<(&str, Option<&str>)> = checks
            .iter()
            .map(|check| (check.name, check.scope.as_deref()))
            .collect();
        assert_eq!(
            scoped
                .iter()
                .filter(|(name, _)| *name == "ssh_reachability")
                .map(|(_, scope)| *scope)
                .collect::<Vec<_>>(),
            vec![Some("web-1.example.test"), Some("web-2.example.test")],
            "each per-host grader must name its host, in rollout order: {scoped:?}"
        );
        // The project-wide graders grade the PROJECT, not a host, so they stay
        // unscoped even in a fleet — scoping them would imply they were run N times.
        assert!(
            scoped
                .iter()
                .filter(|(name, _)| *name != "ssh_reachability")
                .all(|(_, scope)| scope.is_none()),
            "project-wide graders must stay unscoped: {scoped:?}"
        );
    }

    #[test]
    fn an_empty_fleet_still_fails_the_preflight_gate() {
        // #2274: `collect_fleet_preflight` is the fail-fast boundary — `run_up`,
        // `run_check`, and `run_rollback` all abort on the count it produces. Handing
        // back zero checks for a hostless fleet would report "0 failed", let the run walk
        // past that boundary, and leave the three `fleet.hosts[0]` sites downstream to
        // panic on an empty vec. `ResolvedFleet::from_targets` keeps a `None` host rather
        // than dropping the entry, so every real fleet has at least one element and this
        // arm is unreachable today — but `hosts` is a `pub` field on a `pub` struct, so
        // the invariant is a promise, not a type. The gate fails closed instead of
        // trusting it.
        let empty = ResolvedFleet { hosts: vec![] };
        let checks = collect_fleet_preflight(&preflight_config(), &empty, 0);
        assert!(
            checks
                .iter()
                .any(|check| check.blocking() && check.detail.contains(DEPLOY_HOST_MISSING_DETAIL)),
            "a fleet with no target must fail the preflight gate, not return no checks: {:?}",
            checks
                .iter()
                .map(|c| (c.name, c.passed, &c.detail))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn no_fleet_preflight_grader_returns_deferred() {
        // #1621 (T1.16, plan §5.3): `deploy_preflight_result` maps `deferred` →
        // `CheckStatus::Fail` while `report_preflight` treats it as a NON-blocking
        // warning, so a deferred fleet grader would mean `doctor --strict` fails a
        // config `deploy check` passes. The resolution is a rule, not a
        // reconciliation: FLEET graders pass or they fail — they never defer.
        // (`deferred` remains in use for the media graders, which are single-host by
        // construction; see the `[media]` fleet refusal.)
        let config = preflight_config();
        for hosts in [
            vec!["web-1.example.test"],
            vec!["web-1.example.test", "web-2.example.test"],
            vec![
                "web-1.example.test",
                "web-2.example.test",
                "web-3.example.test",
            ],
        ] {
            let fleet =
                ResolvedFleet::resolve(&fleet_cfg(&hosts), "myapp").expect("fleet resolves");
            for check in collect_fleet_preflight(&config, &fleet, hosts.len()) {
                assert!(
                    !check.deferred,
                    "fleet grader `{}` must never defer (scope {:?}): {}",
                    check.name, check.scope, check.detail
                );
            }
        }
    }

    #[test]
    fn preflight_report_label_appends_the_scope_only_when_present() {
        // #1621 (plan §5.2): `✅ ssh_reachability (web-2): …`. The NAME is unchanged
        // and stays the stable identifier; the host rides in parentheses after it,
        // so a single-host run (scope `None`) prints the pre-#1621 label verbatim.
        let plain = PreflightCheck::pass("ssh_reachability", "reachable");
        assert_eq!(preflight_label(&plain), "ssh_reachability");
        let scoped = plain.scoped(Some("web-2.example.test".to_owned()));
        assert_eq!(
            preflight_label(&scoped),
            "ssh_reachability (web-2.example.test)"
        );
        assert_eq!(
            scoped.name, "ssh_reachability",
            "the stable identifier must not absorb the host"
        );
    }

    #[test]
    fn doctor_deploy_check_names_are_the_shared_grader_names_prefixed() {
        // #1621 (T2.5, plan §5.5): doctor's deploy checks and `deploy check`'s
        // graders are enumerated from ONE ordered list, and doctor's operator-visible
        // `--json` names are exactly that list with a `deploy_` prefix. Deriving the
        // mapping mechanically (rather than trusting two hand-maintained literal
        // lists to stay in step) is what turns the comment-enforced parity invariant
        // into a machine-enforced one.
        assert_eq!(
            PREFLIGHT_GRADERS.len(),
            DOCTOR_PREFLIGHT_GRADERS.len(),
            "the two lists must stay the same length"
        );
        for (grader, doctor_name) in PREFLIGHT_GRADERS.iter().zip(DOCTOR_PREFLIGHT_GRADERS) {
            assert_eq!(
                doctor_name,
                format!("deploy_{grader}"),
                "doctor's name for `{grader}` must be the prefixed grader name"
            );
        }
        // …and the list is exactly what a fleet preflight emits (the per-host grader
        // once per host, then the project graders once).
        let fleet = ResolvedFleet::resolve(
            &fleet_cfg(&["web-1.example.test", "web-2.example.test"]),
            "myapp",
        )
        .expect("fleet resolves");
        let emitted: Vec<&str> = collect_fleet_preflight(&preflight_config(), &fleet, 2)
            .iter()
            .map(|check| check.name)
            .collect();
        assert_eq!(
            emitted,
            vec![
                "ssh_reachability",
                "ssh_reachability",
                "signing_secret",
                "database_url",
                "migrate_check"
            ],
            "the fleet preflight emits the per-host grader once per host, then the \
             project graders once"
        );
        let mut distinct = emitted.clone();
        distinct.sort_unstable();
        distinct.dedup();
        let mut expected = PREFLIGHT_GRADERS.to_vec();
        expected.sort_unstable();
        assert_eq!(distinct, expected);
    }

    #[test]
    fn fleet_resolve_trims_each_host_like_the_single_host_path() {
        // #1621 (AC-1): `ResolvedDeployConfig::resolve` trims the scalar `host`,
        // so the fleet list must trim each entry identically — otherwise a stray
        // space produces a different SSH target under the two spellings.
        let padded = fleet_cfg(&["  203.0.113.10  "]);
        let fleet = ResolvedFleet::resolve(&padded, "myapp").expect("padded fleet resolves");
        let expected = ResolvedDeployConfig::resolve(
            &DeployConfig {
                host: Some("  203.0.113.10  ".to_owned()),
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("padded single host resolves");
        assert_eq!(
            fleet.hosts[0], expected,
            "each fleet entry must be trimmed exactly like the scalar host, got: {:?}",
            fleet.hosts[0]
        );
    }

    #[test]
    fn fleet_resolve_shares_the_single_host_defaults_and_tls_validation() {
        // #1621 (AC-1): the fleet resolves the SHARED shape once through
        // `ResolvedDeployConfig::resolve`, so the app_name → app_dir →
        // service_name chain and the TLS-requires-host rejection are literally the
        // same code — they cannot drift between the two spellings.
        let fleet = ResolvedFleet::resolve(&fleet_cfg(&["web-1", "web-2"]), "myapp")
            .expect("a well-formed fleet resolves");
        for host in &fleet.hosts {
            assert_eq!(host.app_name, "myapp", "got: {host:?}");
            assert_eq!(host.app_dir, "/srv/autumn/myapp", "got: {host:?}");
            assert_eq!(host.service_name, "myapp", "got: {host:?}");
            assert_eq!(host.profile, "prod", "got: {host:?}");
        }

        // `[deploy.tls] enabled` without a host is rejected for a fleet exactly as
        // it is for a single server — before any host is touched.
        let cfg = DeployConfig {
            hosts: vec!["web-1".to_owned(), "web-2".to_owned()],
            tls: autumn_web::config::DeployTlsConfig {
                enabled: true,
                host: None,
            },
            ..DeployConfig::default()
        };
        let err = ResolvedFleet::resolve(&cfg, "myapp")
            .expect_err("enabled TLS without a host must be rejected for a fleet too");
        assert!(
            err.contains("[deploy.tls]") && err.contains("host"),
            "the fleet must reuse the single-host TLS rejection, got: {err}"
        );
    }

    #[test]
    fn fleet_of_one_renders_todays_unit() {
        // #1621 (AC-1, proof P7): the rendered systemd unit — the artifact that
        // actually lands on the server — must be byte-identical under both
        // spellings. This is the observable downstream of P5.
        let single = DeployConfig {
            host: Some("203.0.113.10".to_owned()),
            app_name: Some("shop".to_owned()),
            user: "deploy".to_owned(),
            ..DeployConfig::default()
        };
        let fleet_spelling = DeployConfig {
            host: None,
            hosts: vec!["203.0.113.10".to_owned()],
            ..single.clone()
        };

        let today = ResolvedDeployConfig::resolve(&single, "shop").expect("single host resolves");
        let fleet =
            ResolvedFleet::resolve(&fleet_spelling, "shop").expect("single-entry fleet resolves");

        let release_dir = "/srv/autumn/shop/releases/20240101120000";
        let today_unit = render_app_unit(&today, release_dir, 3001, "blue");
        let fleet_unit = render_app_unit(&fleet.hosts[0], release_dir, 3001, "blue");
        assert_eq!(
            fleet_unit, today_unit,
            "a one-entry fleet must render today's slot unit verbatim;\nfleet:\n{fleet_unit}\ntoday:\n{today_unit}"
        );

        // The `current`-symlink renderer stays in lockstep too.
        let today_service = render_systemd_unit(&today);
        let fleet_service = render_systemd_unit(&fleet.hosts[0]);
        assert_eq!(
            fleet_service, today_service,
            "a one-entry fleet must render today's service unit verbatim;\nfleet:\n{fleet_service}\ntoday:\n{today_service}"
        );
    }

    #[test]
    fn build_env_file_sets_production_profile_by_default() {
        // With no `[deploy] profile` set, the host env file must pin the app to
        // the production profile so the deployed service never silently boots
        // under the `dev` fallback.
        let config = AutumnConfig::default();
        let resolved = ResolvedDeployConfig::resolve(&DeployConfig::default(), "myapp")
            .expect("deploy config resolves");
        let env_file = build_env_file(&config, &resolved);
        assert!(
            env_file.expose().lines().any(|l| l == "AUTUMN_ENV=prod"),
            "env file should pin AUTUMN_ENV=prod by default, got: {:?}",
            env_file.expose()
        );
    }

    #[test]
    fn deploy_status_reads_its_probe_port_under_the_deploy_profile_without_validating() {
        // #1621 review round 1 (Codex 3). `deploy status` is the read-only command an
        // operator reaches for mid-incident, and it needs exactly one value from the
        // application config: `server.port`. Routing that through `load_runtime_config`
        // validated the whole config under the deploy profile, so an unrelated invalid
        // production setting aborted the command before a single host was probed. The
        // port must still come from the same profile resolution the deploy itself uses,
        // or status reports against the wrong port, so the fallback layers base ←
        // `[profile.prod]` ← `autumn-prod.toml` ← env, exactly like the loader.
        use autumn_web::config::MockEnv;

        let dir = tempfile::TempDir::new().expect("temp project dir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[server]\n\
             port = 8080\n\
             \n\
             [profile.prod.server]\n\
             port = 9090\n",
        )
        .expect("write autumn.toml");
        let dirs = vec![dir.path().to_path_buf()];

        // The PROFILE's port wins over the base one — a status graded against 8080
        // would derive the wrong slot ports and report a bogus proxy-port mismatch.
        assert_eq!(
            declared_server_port_in(&dirs, "prod", &MockEnv::new()),
            Some(9090),
        );
        // …and the alias spelling resolves the same file/section set.
        assert_eq!(
            declared_server_port_in(&dirs, "production", &MockEnv::new()),
            Some(9090),
        );
        // A different profile falls through to the base declaration.
        assert_eq!(
            declared_server_port_in(&dirs, "staging", &MockEnv::new()),
            Some(8080),
        );
        // `AUTUMN_SERVER__PORT` is the loader's highest layer, so it wins here too.
        assert_eq!(
            declared_server_port_in(
                &dirs,
                "prod",
                &MockEnv::new().with("AUTUMN_SERVER__PORT", "7070")
            ),
            Some(7070),
        );
        // The profile override FILE layers on top of the inline section, matching
        // `AutumnConfig::load_with_env`'s merge order.
        std::fs::write(
            dir.path().join("autumn-prod.toml"),
            "[server]\nport = 9191\n",
        )
        .expect("write autumn-prod.toml");
        assert_eq!(
            declared_server_port_in(&dirs, "prod", &MockEnv::new()),
            Some(9191),
        );
        // Nothing declared anywhere → `None`, so the caller substitutes the
        // framework default instead of this function inventing one.
        let empty = tempfile::TempDir::new().expect("temp dir");
        assert_eq!(
            declared_server_port_in(&[empty.path().to_path_buf()], "prod", &MockEnv::new()),
            None,
        );
    }

    #[test]
    fn deploy_status_degrades_instead_of_aborting_on_an_unrelated_config_error() {
        // #1621 review round 1 (Codex 3), the seam. A config error under the deploy
        // profile must NOT take the read-only fleet report offline; it must be
        // reported, with the probe still graded against the profile's declared port.
        let dir = tempfile::TempDir::new().expect("temp project dir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[server]\nport = 8080\n\n[profile.prod.server]\nport = 9090\n",
        )
        .expect("write autumn.toml");
        let dirs = vec![dir.path().to_path_buf()];

        let degraded = status_public_port_with(
            &dirs,
            "prod",
            Err(DeployError::Config(
                "scheduler.max_concurrency must be greater than 0".to_owned(),
            )),
        )
        .expect("a read-only status must not abort on an unrelated config error");
        assert_eq!(degraded.port, 9090, "the PROFILE's declared port is used");
        assert!(
            degraded
                .degraded
                .as_deref()
                .is_some_and(|reason| reason.contains("scheduler.max_concurrency")),
            "the degradation must be reported, never silent: {:?}",
            degraded.degraded
        );

        // The happy path is unchanged: a config that validates supplies the port and
        // reports no caveat at all.
        let ok = status_public_port_with(
            &dirs,
            "prod",
            Ok(AutumnConfig {
                server: autumn_web::config::ServerConfig {
                    port: 4321,
                    ..autumn_web::config::ServerConfig::default()
                },
                ..AutumnConfig::default()
            }),
        )
        .expect("a valid config resolves");
        assert_eq!(
            ok,
            StatusPort {
                port: 4321,
                degraded: None,
            },
        );
    }

    #[test]
    fn build_env_file_honors_deploy_profile_override() {
        // A non-prod target (e.g. staging) sets `[deploy] profile` and the host
        // env file carries that value verbatim.
        let config = AutumnConfig::default();
        let cfg = DeployConfig {
            profile: "staging".to_owned(),
            ..DeployConfig::default()
        };
        let resolved =
            ResolvedDeployConfig::resolve(&cfg, "myapp").expect("deploy config resolves");
        let env_file = build_env_file(&config, &resolved);
        assert!(
            env_file.expose().lines().any(|l| l == "AUTUMN_ENV=staging"),
            "env file should honor the [deploy] profile override, got: {:?}",
            env_file.expose()
        );
    }

    #[test]
    fn runtime_config_loads_profile_scoped_prod_values_for_env_file_and_grading() {
        // Regression (P1 follow-up to #1956): `autumn deploy` must reload its config
        // under the target deploy profile (default `prod`), so a signing secret and DB
        // URL that live only under `[profile.prod]` are loaded, graded, and uploaded
        // rather than the operator's ambient dev values. This exercises the exact seam
        // `run` → `load_runtime_config` uses: a `ForcedProfileEnv`, which reports
        // `AUTUMN_ENV=<deploy profile>`, fed to `AutumnConfig::load_with_env`, so the
        // loader layers `[profile.prod]` on top. `AUTUMN_MANIFEST_DIR` points config
        // loading at the temp project without mutating the process env or CWD.
        use autumn_web::config::MockEnv;

        let dir = tempfile::TempDir::new().expect("temp project dir");
        // Base/dev values are weak/placeholder and DIFFERENT from prod. The prod
        // signing secret (64 hex chars, not a demo value) and prod DB URL live
        // ONLY under `[profile.prod]`, exactly the combo that motivated the fix.
        let prod_secret = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
        let prod_db_url = "postgres://prod_user:prod_pw@proddb.internal/app";
        std::fs::write(
            dir.path().join("autumn.toml"),
            format!(
                "[deploy]\n\
                 host = \"deploy.example.test\"\n\
                 \n\
                 [database]\n\
                 primary_url = \"postgres://dev:dev@localhost/devapp\"\n\
                 \n\
                 [security.signing_secret]\n\
                 secret = \"changeme\"\n\
                 \n\
                 [profile.prod.database]\n\
                 primary_url = \"{prod_db_url}\"\n\
                 \n\
                 [profile.prod.security.signing_secret]\n\
                 secret = \"{prod_secret}\"\n"
            ),
        )
        .expect("write autumn.toml");

        // Deploy profile defaults to `prod`; no host so the ssh_reachability
        // grader fails fast without any network I/O (we only assert on the
        // signing-secret grade below).
        let resolved =
            ResolvedDeployConfig::resolve(&DeployConfig::default(), "demoapp").expect("resolves");
        assert_eq!(resolved.profile, "prod");

        // Force `AUTUMN_ENV=prod` (as `load_runtime_config` does) and point config
        // loading at the temp dir via a MockEnv-supplied AUTUMN_MANIFEST_DIR.
        let forced = ForcedProfileEnv {
            profile: resolved.profile.clone(),
            inner: MockEnv::new().with("AUTUMN_MANIFEST_DIR", dir.path().to_str().unwrap()),
        };
        let runtime_config =
            AutumnConfig::load_with_env(&forced).expect("load config under prod profile");

        // The env file the deploy would upload carries the PROD values and pins
        // AUTUMN_ENV to the deploy profile — never the dev/base placeholders.
        let env_file = build_env_file(&runtime_config, &resolved);
        let body = env_file.expose();
        assert!(
            body.lines().any(|l| l == "AUTUMN_ENV=prod"),
            "env file must pin AUTUMN_ENV to the deploy profile, got: {body:?}"
        );
        assert!(
            body.lines()
                .any(|l| l == format!("AUTUMN_SECURITY__SIGNING_SECRET={prod_secret}")),
            "env file must carry the PROD signing secret, got: {body:?}"
        );
        assert!(
            body.lines()
                .any(|l| l == format!("AUTUMN_DATABASE__URL={prod_db_url}")),
            "env file must carry the PROD database URL, got: {body:?}"
        );
        // The dev/base placeholders must NOT leak into the uploaded env file.
        assert!(
            !body.contains("changeme"),
            "env file must not ship the dev/base signing secret"
        );
        assert!(
            !body.contains("devapp"),
            "env file must not ship the dev/base database URL"
        );

        // Preflight grades the PROD signing secret: a strong prod secret PASSES
        // even though the weak base `changeme` would fail production grading. This
        // proves the weak base secret never leaks through the grade.
        let signing = collect_preflight(&runtime_config, &resolved)
            .into_iter()
            .find(|c| c.name == "signing_secret")
            .expect("preflight includes a signing_secret check");
        assert!(
            signing.passed,
            "the strong PROD signing secret must pass preflight: {}",
            signing.detail
        );
    }

    #[test]
    fn forced_profile_env_overrides_only_autumn_env() {
        // The wrapper reports the forced deploy profile for AUTUMN_ENV and
        // delegates every other key to the inner env unchanged.
        use autumn_web::config::MockEnv;

        let forced = ForcedProfileEnv {
            profile: "prod".to_owned(),
            inner: MockEnv::new()
                .with("AUTUMN_ENV", "dev")
                .with("SOME_OTHER_KEY", "kept"),
        };
        assert_eq!(forced.var("AUTUMN_ENV").as_deref(), Ok("prod"));
        assert_eq!(forced.var("SOME_OTHER_KEY").as_deref(), Ok("kept"));
        assert!(forced.var("UNSET_KEY").is_err());
    }

    #[test]
    fn forced_profile_env_honors_explicit_autumn_dotenv() {
        // The wrapper synthesizes `AUTUMN_DOTENV=1` only when the inner env has
        // NO explicit value. An operator running `AUTUMN_DOTENV=0 autumn deploy`
        // (or `false`) is deliberately opting OUT of `.env.<profile>` loading, so
        // the explicit value must be delegated through unchanged (`should_load`
        // honors `0`/`false` as the documented off switch).
        use autumn_web::config::MockEnv;

        // Explicit `0` is preserved (off).
        let off = ForcedProfileEnv {
            profile: "prod".to_owned(),
            inner: MockEnv::new().with("AUTUMN_DOTENV", "0"),
        };
        assert_eq!(off.var("AUTUMN_DOTENV").as_deref(), Ok("0"));
        // AUTUMN_ENV is still forced to the deploy profile.
        assert_eq!(off.var("AUTUMN_ENV").as_deref(), Ok("prod"));

        // Unset inner value → synthesize `1` (opt the deploy profile into the
        // `.env.<profile>` overlay).
        let unset = ForcedProfileEnv {
            profile: "prod".to_owned(),
            inner: MockEnv::new(),
        };
        assert_eq!(unset.var("AUTUMN_DOTENV").as_deref(), Ok("1"));

        // Explicit truthy values are also delegated verbatim.
        let on = ForcedProfileEnv {
            profile: "prod".to_owned(),
            inner: MockEnv::new().with("AUTUMN_DOTENV", "true"),
        };
        assert_eq!(on.var("AUTUMN_DOTENV").as_deref(), Ok("true"));
    }

    #[test]
    fn preflight_grades_signing_secret_against_resolved_deploy_profile() {
        // Regression: preflight must grade the signing secret against the SAME
        // profile that `build_env_file` writes to the host env file
        // (`AUTUMN_ENV=<resolved.profile>`, default `prod`), NOT the local CLI
        // runtime profile (`config.profile`, dev/None on a dev box). Otherwise a
        // weak/demo secret sails through `deploy check`/`deploy up` locally, but
        // the uploaded unit boots under `prod` and exits in
        // `fail_fast_on_invalid_signing_secret` — failing the deploy only AFTER
        // touching the host. The fix catches the weak secret locally.
        let find_signing = |checks: &[PreflightCheck]| {
            checks
                .iter()
                .find(|c| c.name == "signing_secret")
                .expect("preflight includes a signing_secret check")
                .clone()
        };

        // A weak/demo secret on a dev box: `config.profile` is None (non-prod),
        // so the OLD behavior (grading against `config.profile`) would PASS.
        let mut config = AutumnConfig::default();
        config.security.signing_secret.secret = Some("changeme".to_owned());
        assert!(
            !is_production_profile(config.profile.as_deref()),
            "guard: the local runtime profile is non-production in this test"
        );

        // Default deploy profile is `prod` (what the env file will pin), so the
        // weak secret must FAIL preflight locally, before any remote call.
        let prod_resolved =
            ResolvedDeployConfig::resolve(&DeployConfig::default(), "myapp").expect("resolves");
        assert_eq!(prod_resolved.profile, "prod");
        let prod_check = find_signing(&collect_preflight(&config, &prod_resolved));
        assert!(
            !prod_check.passed,
            "weak secret must fail preflight under the default (prod) deploy \
             profile: {}",
            prod_check.detail
        );
        // Never echo the secret value, even a known demo one.
        assert!(!prod_check.detail.contains("changeme"));

        // With a non-production deploy profile (e.g. staging) the same weak
        // secret still passes — a dev/staging deploy is not held to the
        // production strength rules, and the env file pins that same profile.
        let staging_resolved = ResolvedDeployConfig::resolve(
            &DeployConfig {
                profile: "staging".to_owned(),
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("deploy config resolves");
        let staging_check = find_signing(&collect_preflight(&config, &staging_resolved));
        assert!(
            staging_check.passed,
            "weak secret should pass preflight under a non-production deploy \
             profile: {}",
            staging_check.detail
        );
    }

    #[test]
    fn resolve_preserves_raw_profile_alias_while_grading_normalized() {
        // Regression: the app's runtime resolver
        // (`autumn_web::config::normalize_profile_name`) trims and case-folds profile
        // aliases, so `PROD`, `Production`, and ` production ` all boot under the
        // canonical `prod`. But the host's override-file lookup
        // (`profile_override_file_lookup_names`) keys off the raw selector spelling: it
        // prefers `autumn-production.toml` over `autumn-prod.toml` when the raw input
        // was `production`. So `resolved.profile`, and the `AUTUMN_ENV` value written
        // from it, must preserve the operator's trimmed raw spelling rather than the
        // alias-folded form, or override-file precedence flips on hosts carrying both
        // files. Grading is normalized separately, at the grade site, so a weak secret
        // under any alias still fails preflight locally.
        let find_signing = |checks: &[PreflightCheck]| {
            checks
                .iter()
                .find(|c| c.name == "signing_secret")
                .expect("preflight includes a signing_secret check")
                .clone()
        };

        let mut config = AutumnConfig::default();
        config.security.signing_secret.secret = Some("changeme".to_owned());

        // Non-canonical production spellings preserve the operator's trimmed raw
        // spelling in `resolved.profile` / AUTUMN_ENV, yet still grade as
        // production (canonicalize-at-grade) and thus FAIL the weak secret.
        for (raw, expected) in [
            ("PROD", "PROD"),
            ("Production", "Production"),
            (" production ", "production"),
        ] {
            let resolved = ResolvedDeployConfig::resolve(
                &DeployConfig {
                    profile: raw.to_owned(),
                    ..DeployConfig::default()
                },
                "myapp",
            )
            .expect("deploy config resolves");
            assert_eq!(
                resolved.profile, expected,
                "profile {raw:?} should preserve the trimmed raw spelling"
            );
            // The value written to AUTUMN_ENV is that same trimmed raw spelling,
            // so the host's override-file precedence is preserved.
            let expected_env = format!("AUTUMN_ENV={expected}");
            assert!(
                build_env_file(&config, &resolved)
                    .expose()
                    .lines()
                    .any(|l| l == expected_env),
                "env file should pin {expected_env:?} for raw profile {raw:?}"
            );
            // Grading normalizes the raw spelling, so it still grades production.
            assert!(
                is_production_profile(Some(&canonicalize_deploy_profile(&resolved.profile))),
                "normalized profile must grade as production for raw profile {raw:?}"
            );
            let check = find_signing(&collect_preflight(&config, &resolved));
            assert!(
                !check.passed,
                "weak secret must fail preflight for production spelling {raw:?}: {}",
                check.detail
            );
            assert!(!check.detail.contains("changeme"));
        }

        // A custom profile is preserved verbatim and grades non-production, so
        // the same weak secret passes (custom deploys aren't held to prod rules).
        let staging = ResolvedDeployConfig::resolve(
            &DeployConfig {
                profile: "staging".to_owned(),
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("deploy config resolves");
        assert_eq!(staging.profile, "staging");
        assert!(!is_production_profile(Some(&staging.profile)));
        let staging_check = find_signing(&collect_preflight(&config, &staging));
        assert!(
            staging_check.passed,
            "weak secret should pass preflight under the custom `staging` profile: {}",
            staging_check.detail
        );
    }

    #[test]
    fn resolve_honors_explicit_overrides() {
        let cfg = DeployConfig {
            host: Some("203.0.113.10".to_owned()),
            app_name: Some("web".to_owned()),
            app_dir: Some("/opt/web".to_owned()),
            service_name: Some("web-svc".to_owned()),
            ..DeployConfig::default()
        };
        let resolved =
            ResolvedDeployConfig::resolve(&cfg, "ignored").expect("deploy config resolves");
        assert_eq!(resolved.app_name, "web");
        assert_eq!(resolved.app_dir, "/opt/web");
        assert_eq!(resolved.service_name, "web-svc");
        assert_eq!(resolved.host.as_deref(), Some("203.0.113.10"));
    }

    #[test]
    fn resolve_blank_overrides_fall_back_to_defaults() {
        let cfg = DeployConfig {
            app_name: Some("   ".to_owned()),
            app_dir: Some(String::new()),
            ..DeployConfig::default()
        };
        let resolved =
            ResolvedDeployConfig::resolve(&cfg, "fallback").expect("deploy config resolves");
        assert_eq!(resolved.app_name, "fallback");
        assert_eq!(resolved.app_dir, "/srv/autumn/fallback");
    }

    #[test]
    fn systemd_unit_contains_service_paths_and_env_file() {
        let cfg = ResolvedDeployConfig::resolve(
            &DeployConfig {
                app_name: Some("shop".to_owned()),
                service_name: Some("shop-web".to_owned()),
                user: "deploy".to_owned(),
                ..DeployConfig::default()
            },
            "shop",
        )
        .expect("deploy config resolves");
        let unit = render_systemd_unit(&cfg);
        assert!(unit.contains("Description=Autumn application: shop"));
        assert!(unit.contains("User=deploy"));
        assert!(unit.contains("WorkingDirectory=/srv/autumn/shop/current"));
        // The unit execs the uploaded standalone app binary at the `current`
        // symlink directly — never `autumn serve --release` (which would rebuild
        // from source rather than run the pre-built release binary).
        assert!(unit.contains("ExecStart=/srv/autumn/shop/current/shop"));
        assert!(!unit.contains("autumn serve --release"));
        assert!(unit.contains("Restart=on-failure"));
        assert!(unit.contains("WantedBy=multi-user.target"));
        // Secrets come from an EnvironmentFile, never inlined into the unit.
        assert!(unit.contains("EnvironmentFile=/srv/autumn/shop/shared/autumn.env"));
        assert!(!unit.contains("Environment=SECRET"));
        // #1952: `render_systemd_unit` execs the `current` symlink, so it points
        // config loading at `current` (matching its WorkingDirectory), where the
        // active release's uploaded autumn.toml is reachable.
        assert!(unit.contains("Environment=AUTUMN_MANIFEST_DIR=/srv/autumn/shop/current"));
    }

    #[test]
    fn app_unit_points_the_maintenance_flag_at_the_shared_dir() {
        // #1621 R1, the deliberate cross-cutting register entry: the runtime's
        // maintenance flag path is cwd-relative and the slot unit's WorkingDirectory is
        // the release dir, so before this line a cutover orphaned the flag and silently
        // un-maintained the host. Pointing the override at the per-app `shared/` dir —
        // which `prepare-dirs` already creates, which survives cutovers, rollbacks, and
        // pruning, and which both slots see — is what makes `autumn deploy maintenance
        // on` mean anything. The line is added to both host spellings equally, since it
        // comes from `render_app_unit`, which the fleet driver and the single-host path
        // share, so the AC-1 differential invariant is untouched.
        let cfg = ResolvedDeployConfig::resolve(
            &DeployConfig {
                app_name: Some("shop".to_owned()),
                ..DeployConfig::default()
            },
            "shop",
        )
        .expect("deploy config resolves");
        let unit = render_app_unit(&cfg, "/srv/autumn/shop/releases/r1", 3001, "blue");
        assert!(
            unit.contains(
                "Environment=AUTUMN_MAINTENANCE_FLAG_FILE=/srv/autumn/shop/shared/autumn-maintenance.json"
            ),
            "slot unit must point the maintenance flag at the shared dir: {unit}"
        );
        // It must NOT land under the release dir — that is the defect being fixed.
        assert!(
            !unit.contains("AUTUMN_MAINTENANCE_FLAG_FILE=/srv/autumn/shop/releases"),
            "the maintenance flag must not be release-scoped: {unit}"
        );
        // The path the unit stamps IS the one the fan-out writes to.
        assert!(unit.contains(&format!(
            "Environment=AUTUMN_MAINTENANCE_FLAG_FILE={}",
            cfg.maintenance_flag_file()
        )));
        // …and it uses the framework's own env-var name and file name, never a
        // CLI-local re-declaration.
        assert!(unit.contains(autumn_web::maintenance::MAINTENANCE_FLAG_FILE_ENV));
        assert!(
            cfg.maintenance_flag_file()
                .ends_with(autumn_web::maintenance::MAINTENANCE_FLAG_BASENAME)
        );
    }

    #[test]
    fn app_unit_sets_manifest_dir_to_release_for_uploaded_config() {
        // #1952: the deployed slot unit (the one actually written by a deploy)
        // sets AUTUMN_MANIFEST_DIR to THIS release dir — where the manifest is
        // uploaded, coupled to the binary — so the app's config loader reads the
        // uploaded autumn.toml instead of built-in defaults, and a rollback that
        // re-renders the unit from the target release dir reads that release's OWN
        // manifest. It matches the unit's WorkingDirectory. Non-secret → an
        // `Environment=` line, not the 0600 env file.
        let cfg = ResolvedDeployConfig::resolve(
            &DeployConfig {
                app_name: Some("shop".to_owned()),
                ..DeployConfig::default()
            },
            "shop",
        )
        .expect("deploy config resolves");
        let release_dir = "/srv/autumn/shop/releases/r1";
        let unit = render_app_unit(&cfg, release_dir, 3001, "blue");
        assert!(
            unit.contains(&format!("Environment=AUTUMN_MANIFEST_DIR={release_dir}")),
            "slot unit must set AUTUMN_MANIFEST_DIR to the release dir: {unit}"
        );
        // It matches the unit's WorkingDirectory (both pinned to the release dir).
        assert!(unit.contains(&format!("WorkingDirectory={release_dir}")));
        // The env file (secrets) still lives in the shared dir at 0600.
        assert!(unit.contains("EnvironmentFile=/srv/autumn/shop/shared/autumn.env"));
    }

    #[test]
    fn render_systemd_unit_sets_manifest_dir_to_current_symlink() {
        // #1952: `autumn deploy render` (the `render_systemd_unit` renderer) execs
        // the `current` symlink, so its AUTUMN_MANIFEST_DIR must point at `current`
        // (matching its WorkingDirectory) — where the active release's manifest is
        // reachable — keeping the two renderers in lockstep.
        let cfg = ResolvedDeployConfig::resolve(
            &DeployConfig {
                app_name: Some("shop".to_owned()),
                ..DeployConfig::default()
            },
            "shop",
        )
        .expect("deploy config resolves");
        let unit = render_systemd_unit(&cfg);
        let current = cfg.current_symlink();
        assert!(
            unit.contains(&format!("Environment=AUTUMN_MANIFEST_DIR={current}")),
            "render_systemd_unit must set AUTUMN_MANIFEST_DIR to the current symlink: {unit}"
        );
        assert!(unit.contains(&format!("WorkingDirectory={current}")));
    }

    #[test]
    fn manifest_uploads_base_only_when_no_profile_sibling() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("autumn.toml"), "[server]\nport = 8080\n")
            .expect("write autumn.toml");
        let dirs = vec![dir.path().to_path_buf()];
        let uploads = manifest_uploads_in(&dirs, "prod");
        assert_eq!(uploads.len(), 1, "only autumn.toml is present");
        assert_eq!(uploads[0].remote_basename, "autumn.toml");
        assert_eq!(uploads[0].local, dir.path().join("autumn.toml"));
    }

    #[test]
    fn manifest_uploads_include_the_configured_capacity_contract() {
        // A release that ships `autumn.toml` naming a `capacity_contract` but
        // not the contract itself would silently disable the admission control
        // it advertises: the remote load fails and deliberately falls back to
        // unlimited (#1733).
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[server]\ncapacity_contract = \"capacity.lock\"\n",
        )
        .expect("write base");
        std::fs::write(dir.path().join("capacity.lock"), "version = 1\n").expect("write contract");
        let dirs = vec![dir.path().to_path_buf()];

        let uploads = manifest_uploads_in(&dirs, "prod");
        let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
        assert_eq!(names, vec!["autumn.toml", "capacity.lock"]);
    }

    #[test]
    fn manifest_uploads_skip_a_capacity_contract_that_is_not_configured() {
        // A stray capacity.lock nobody points at is not part of the release.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("autumn.toml"), "[server]\n").expect("write base");
        std::fs::write(dir.path().join("capacity.lock"), "version = 1\n").expect("write contract");
        let dirs = vec![dir.path().to_path_buf()];

        let uploads = manifest_uploads_in(&dirs, "prod");
        let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
        assert_eq!(names, vec!["autumn.toml"]);
    }

    #[test]
    fn manifest_uploads_read_the_contract_from_an_inline_profile_overlay() {
        // A contract configured only under `[profile.prod.server]` is still
        // resolved by the deployed runtime, so it must still travel with the
        // release — otherwise admission control falls open with no signal.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[server]\n\n[profile.prod.server]\ncapacity_contract = \"capacity.lock\"\n",
        )
        .expect("write base");
        std::fs::write(dir.path().join("capacity.lock"), "version = 1\n").expect("write contract");
        let dirs = vec![dir.path().to_path_buf()];

        let uploads = manifest_uploads_in(&dirs, "prod");
        let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
        assert_eq!(names, vec!["autumn.toml", "capacity.lock"]);
    }

    #[test]
    fn manifest_uploads_read_the_contract_from_a_profile_only_manifest() {
        // A deployment may ship only `autumn-prod.toml`. The runtime loads it
        // regardless, and `manifest_uploads_in` uploads it — so the contract it
        // names has to travel too.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("autumn-prod.toml"),
            "[server]\ncapacity_contract = \"capacity.lock\"\n",
        )
        .expect("write sibling");
        std::fs::write(dir.path().join("capacity.lock"), "version = 1\n").expect("write contract");
        let dirs = vec![dir.path().to_path_buf()];

        let uploads = manifest_uploads_in(&dirs, "prod");
        let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
        assert_eq!(names, vec!["autumn-prod.toml", "capacity.lock"]);
    }

    #[test]
    fn manifest_uploads_refuse_to_flatten_a_nested_contract_path() {
        // The release directory is flat, but the uploaded config still names
        // `contracts/prod.lock`. Uploading it as `prod.lock` would leave the
        // app looking at a path that does not exist — the very fall-open this
        // upload exists to prevent — so it is skipped with a warning instead.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[server]\ncapacity_contract = \"contracts/prod.lock\"\n",
        )
        .expect("write base");
        std::fs::create_dir_all(dir.path().join("contracts")).expect("mkdir");
        std::fs::write(dir.path().join("contracts/prod.lock"), "version = 1\n")
            .expect("write contract");
        let dirs = vec![dir.path().to_path_buf()];

        let uploads = manifest_uploads_in(&dirs, "prod");
        let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
        assert_eq!(names, vec!["autumn.toml"]);
    }

    #[test]
    fn manifest_uploads_honour_a_profile_sibling_clearing_the_contract() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[server]\ncapacity_contract = \"capacity.lock\"\n",
        )
        .expect("write base");
        std::fs::write(
            dir.path().join("autumn-prod.toml"),
            "[server]\ncapacity_contract = \"\"\n",
        )
        .expect("write sibling");
        std::fs::write(dir.path().join("capacity.lock"), "version = 1\n").expect("write contract");
        let dirs = vec![dir.path().to_path_buf()];

        let uploads = manifest_uploads_in(&dirs, "prod");
        let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
        assert_eq!(names, vec!["autumn.toml", "autumn-prod.toml"]);
    }

    #[test]
    fn manifest_uploads_include_profile_sibling_when_present() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("autumn.toml"), "[server]\n").expect("write base");
        std::fs::write(dir.path().join("autumn-prod.toml"), "[server]\n").expect("write sibling");
        let dirs = vec![dir.path().to_path_buf()];
        let uploads = manifest_uploads_in(&dirs, "prod");
        let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
        assert_eq!(names, vec!["autumn.toml", "autumn-prod.toml"]);
    }

    #[test]
    fn manifest_uploads_normalize_production_to_canonical_sibling() {
        // `[deploy] profile = "Production"` must resolve the SAME override file
        // the host runtime loads first. The runtime's ordered lookup for a raw
        // `Production` is ["production", "prod"], so a local `autumn-production.toml`
        // is uploaded under that exact name — never `autumn-Production.toml`.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("autumn.toml"), "[server]\n").expect("write base");
        std::fs::write(dir.path().join("autumn-production.toml"), "[server]\n")
            .expect("write sibling");
        let dirs = vec![dir.path().to_path_buf()];
        let uploads = manifest_uploads_in(&dirs, "Production");
        let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
        assert_eq!(names, vec!["autumn.toml", "autumn-production.toml"]);
        assert!(
            !uploads
                .iter()
                .any(|u| u.remote_basename == "autumn-Production.toml"),
            "must not upload the raw-cased spelling"
        );
    }

    #[test]
    fn manifest_uploads_check_canonical_profile_sibling() {
        // `[deploy] profile = "production"` should still ship the canonical
        // `autumn-prod.toml` if that is what the repo carries, matching the
        // runtime's own override-file lookup (production → ["production","prod"];
        // production absent, prod present → prod wins).
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("autumn.toml"), "[server]\n").expect("write base");
        std::fs::write(dir.path().join("autumn-prod.toml"), "[server]\n").expect("write sibling");
        let dirs = vec![dir.path().to_path_buf()];
        let uploads = manifest_uploads_in(&dirs, "production");
        assert!(
            uploads
                .iter()
                .any(|u| u.remote_basename == "autumn-prod.toml"),
            "canonical prod sibling is uploaded for raw profile `production`"
        );
    }

    #[test]
    fn manifest_uploads_raw_prod_prefers_prod_sibling_first() {
        // Raw `prod` → ordered lookup ["prod","production"], so when only the
        // canonical `autumn-prod.toml` exists it is chosen.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("autumn.toml"), "[server]\n").expect("write base");
        std::fs::write(dir.path().join("autumn-prod.toml"), "[server]\n").expect("write sibling");
        let dirs = vec![dir.path().to_path_buf()];
        let uploads = manifest_uploads_in(&dirs, "prod");
        let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
        assert_eq!(names, vec!["autumn.toml", "autumn-prod.toml"]);
    }

    #[test]
    fn manifest_uploads_custom_profile_uses_verbatim_sibling() {
        // A custom profile has no aliases: raw `staging` → ["staging"], uploaded
        // as `autumn-staging.toml`.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("autumn.toml"), "[server]\n").expect("write base");
        std::fs::write(dir.path().join("autumn-staging.toml"), "[server]\n")
            .expect("write sibling");
        let dirs = vec![dir.path().to_path_buf()];
        let uploads = manifest_uploads_in(&dirs, "staging");
        let names: Vec<&str> = uploads.iter().map(|u| u.remote_basename.as_str()).collect();
        assert_eq!(names, vec!["autumn.toml", "autumn-staging.toml"]);
    }

    #[test]
    fn manifest_uploads_first_lookup_name_wins_when_both_present() {
        // When BOTH `autumn-production.toml` and `autumn-prod.toml` exist, the one
        // matching the runtime's FIRST lookup name for the raw spelling is chosen
        // (first-existing-wins), so the deploy uploads exactly what the host loads.
        // Raw `production` → ["production","prod"] → production wins.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("autumn.toml"), "[server]\n").expect("write base");
        std::fs::write(dir.path().join("autumn-production.toml"), "[server]\n")
            .expect("write production");
        std::fs::write(dir.path().join("autumn-prod.toml"), "[server]\n").expect("write prod");
        let dirs = vec![dir.path().to_path_buf()];
        let uploads = manifest_uploads_in(&dirs, "production");
        let siblings: Vec<&str> = uploads
            .iter()
            .map(|u| u.remote_basename.as_str())
            .filter(|n| n.starts_with("autumn-"))
            .collect();
        assert_eq!(
            siblings,
            vec!["autumn-production.toml"],
            "only the first-lookup-name sibling is uploaded, matching the runtime"
        );
    }

    #[test]
    fn manifest_uploads_base_falls_back_to_cwd_dir() {
        // Mirror the runtime's find_config_file_named per-file fallback: when the
        // primary (manifest) dir has no autumn.toml but a fallback (CWD) dir does,
        // the base manifest is picked up from the fallback dir. The sibling honors
        // the same fallback.
        let manifest_dir = tempfile::tempdir().expect("manifest dir");
        let cwd = tempfile::tempdir().expect("cwd dir");
        // Manifest dir is empty; CWD carries the real config.
        std::fs::write(cwd.path().join("autumn.toml"), "[server]\n").expect("write base");
        std::fs::write(cwd.path().join("autumn-prod.toml"), "[server]\n").expect("write sibling");
        let dirs = vec![manifest_dir.path().to_path_buf(), cwd.path().to_path_buf()];
        let uploads = manifest_uploads_in(&dirs, "prod");
        assert_eq!(
            uploads.len(),
            2,
            "base + sibling picked up from the CWD fallback"
        );
        assert_eq!(uploads[0].remote_basename, "autumn.toml");
        assert_eq!(uploads[0].local, cwd.path().join("autumn.toml"));
        assert_eq!(uploads[1].remote_basename, "autumn-prod.toml");
        assert_eq!(uploads[1].local, cwd.path().join("autumn-prod.toml"));
    }

    #[test]
    fn manifest_uploads_primary_dir_wins_over_fallback() {
        // When both the manifest dir and the CWD fallback have autumn.toml, the
        // primary (manifest) dir wins — matching find_config_file_named.
        let manifest_dir = tempfile::tempdir().expect("manifest dir");
        let cwd = tempfile::tempdir().expect("cwd dir");
        std::fs::write(manifest_dir.path().join("autumn.toml"), "[server]\n").expect("primary");
        std::fs::write(cwd.path().join("autumn.toml"), "[server]\n").expect("fallback");
        let dirs = vec![manifest_dir.path().to_path_buf(), cwd.path().to_path_buf()];
        let uploads = manifest_uploads_in(&dirs, "prod");
        assert_eq!(uploads[0].local, manifest_dir.path().join("autumn.toml"));
    }

    #[test]
    fn manifest_uploads_empty_when_no_manifest() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dirs = vec![dir.path().to_path_buf()];
        let uploads = manifest_uploads_in(&dirs, "prod");
        assert!(uploads.is_empty(), "no autumn.toml → nothing to upload");
    }

    // ── Media config resolves under the deploy profile (Finding O) ───────────

    #[test]
    fn media_config_no_manifest_is_disabled_default() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dirs = vec![dir.path().to_path_buf()];
        let (cfg, bin) = load_media_host_config_in(&dirs, "prod").expect("loads");
        assert!(!cfg.enabled, "no autumn.toml → controller disabled");
        assert_eq!(bin, media::DEFAULT_FFMPEG_BIN);
    }

    #[test]
    fn media_config_honors_inline_profile_section() {
        // `[profile.prod.media.mediamtx]` enables media over a base that omits it —
        // a profiled deploy must see the profile's config, not the base default.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[media.ffmpeg]\nbin = \"/usr/bin/ffmpeg\"\n\
             [profile.prod.media.mediamtx]\nenabled = true\napi_port = 19997\n",
        )
        .expect("write base");
        let dirs = vec![dir.path().to_path_buf()];

        // prod: the inline profile section is layered on.
        let (prod, _) = load_media_host_config_in(&dirs, "prod").expect("loads prod");
        assert!(prod.enabled, "prod profile enables media");
        assert_eq!(prod.api_port, 19997);

        // dev: no matching profile section → base default (media disabled).
        let (dev, _) = load_media_host_config_in(&dirs, "dev").expect("loads dev");
        assert!(
            !dev.enabled,
            "dev has no profile media section → base default"
        );
    }

    #[test]
    fn media_config_honors_profile_override_file() {
        // The `autumn-prod.toml` override file enables media over a base that omits
        // it, matching the runtime's Layer-5 override.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(dir.path().join("autumn.toml"), "[server]\nport = 3000\n")
            .expect("write base");
        std::fs::write(
            dir.path().join("autumn-prod.toml"),
            "[media.mediamtx]\nenabled = true\nrtmp_port = 11935\n",
        )
        .expect("write prod override");
        let dirs = vec![dir.path().to_path_buf()];

        let (prod, _) = load_media_host_config_in(&dirs, "prod").expect("loads prod");
        assert!(prod.enabled, "autumn-prod.toml enables media");
        assert_eq!(prod.rtmp_port, 11935);
    }

    #[test]
    fn media_config_honors_profile_override_file_without_base_autumn_toml() {
        // Finding R: the base `autumn.toml` is OPTIONAL, exactly like
        // `AutumnConfig::load_with_env`. A deploy that supplies `[deploy] host` via
        // env and keeps `[media.mediamtx] enabled = true` ONLY in `autumn-prod.toml`
        // (with NO base autumn.toml) must still resolve the profile override and
        // provision MediaMTX — previously the loader early-returned the disabled
        // default the moment no base file existed, silently skipping the override.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("autumn-prod.toml"),
            "[media.mediamtx]\nenabled = true\nrtmp_port = 11935\n",
        )
        .expect("write prod override");
        let dirs = vec![dir.path().to_path_buf()];

        let (prod, _) = load_media_host_config_in(&dirs, "prod").expect("loads prod");
        assert!(
            prod.enabled,
            "profile-only media config is provisioned with no base autumn.toml"
        );
        assert_eq!(prod.rtmp_port, 11935);

        // dev: no `autumn-dev.toml` and no base → disabled default (the override
        // file is profile-scoped, so a different profile is unaffected).
        let (dev, _) = load_media_host_config_in(&dirs, "dev").expect("loads dev");
        assert!(!dev.enabled, "dev has no override file → disabled default");
    }

    #[test]
    fn media_config_profile_layer_overrides_base_value() {
        // Base enables media on one api_port; the profile override wins.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[media.mediamtx]\nenabled = true\napi_port = 9997\n",
        )
        .expect("write base");
        std::fs::write(
            dir.path().join("autumn-prod.toml"),
            "[media.mediamtx]\napi_port = 29997\n",
        )
        .expect("write prod override");
        let dirs = vec![dir.path().to_path_buf()];

        let (prod, _) = load_media_host_config_in(&dirs, "prod").expect("loads prod");
        assert!(
            prod.enabled,
            "base enablement is preserved under deep merge"
        );
        assert_eq!(
            prod.api_port, 29997,
            "profile override wins over the base value"
        );
    }

    #[test]
    fn media_config_base_only_when_profile_has_no_media_layer() {
        // No inline `[profile.prod]` and no autumn-prod.toml → the base config is
        // read verbatim under the profile.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[media.mediamtx]\nenabled = true\napi_port = 9001\n",
        )
        .expect("write base");
        let dirs = vec![dir.path().to_path_buf()];

        let (prod, _) = load_media_host_config_in(&dirs, "prod").expect("loads prod");
        assert!(prod.enabled);
        assert_eq!(prod.api_port, 9001);
    }

    #[test]
    fn media_config_fails_closed_on_invalid_value_in_active_profile_layer() {
        // A present-but-ill-typed value in the ACTIVE profile layer aborts, even
        // though the base is valid — the fail-closed rule spans every layer.
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[media.mediamtx]\nenabled = true\n",
        )
        .expect("write base");
        std::fs::write(
            dir.path().join("autumn-prod.toml"),
            "[media.mediamtx]\napi_port = \"nope\"\n",
        )
        .expect("write bad prod override");
        let dirs = vec![dir.path().to_path_buf()];

        let err = load_media_host_config_in(&dirs, "prod").expect_err("must fail closed");
        assert!(
            matches!(err, DeployError::Config(_)),
            "invalid profile-layer media config aborts the deploy: {err:?}"
        );
    }

    #[test]
    fn manifest_notice_warns_loudly_when_no_manifest() {
        let notice = manifest_preflight_notice(&[]);
        assert!(
            notice.contains("no autumn.toml") && notice.contains("built-in defaults"),
            "no-manifest notice must loudly warn about silent defaults: {notice}"
        );
    }

    #[test]
    fn manifest_notice_confirms_uploaded_files() {
        let uploads = vec![
            exec::ManifestUpload {
                local: PathBuf::from("/x/autumn.toml"),
                remote_basename: "autumn.toml".to_owned(),
            },
            exec::ManifestUpload {
                local: PathBuf::from("/x/autumn-prod.toml"),
                remote_basename: "autumn-prod.toml".to_owned(),
            },
        ];
        let notice = manifest_preflight_notice(&uploads);
        assert!(notice.contains("autumn.toml"));
        assert!(notice.contains("autumn-prod.toml"));
        assert!(!notice.contains("no autumn.toml"));
    }

    /// #2589 item 5: `deploy plan` shows the `SQLite` data steps in the order the
    /// real deploy runs them.
    #[test]
    fn deploy_plan_renders_the_sqlite_data_steps() {
        let labels = |url: &str| -> Vec<&'static str> {
            let mut config = AutumnConfig::default();
            config.database.url = Some(url.to_owned());
            let cfg = with_sqlite_data_contract(&resolved_defaults(), &config);
            build_deploy_plan(&cfg).iter().map(|s| s.label).collect()
        };
        let position = |labels: &[&str], label: &str| {
            labels
                .iter()
                .position(|l| *l == label)
                .unwrap_or_else(|| panic!("no {label} step: {labels:?}"))
        };

        let relative = labels("sqlite://app.db");
        assert!(position(&relative, "link-data") < position(&relative, "upload"));
        assert!(position(&relative, "migrate") < position(&relative, "record-data-adopted"));

        let absolute = labels("sqlite:///var/lib/myapp/app.db");
        assert!(position(&absolute, "check-data-dir") < position(&absolute, "upload"));
        assert!(!absolute.contains(&"link-data"), "{absolute:?}");

        let postgres = labels("postgres://db.example.com/app");
        for label in ["link-data", "check-data-dir", "record-data-adopted"] {
            assert!(!postgres.contains(&label), "{postgres:?}");
        }
    }

    /// #2589 item 5: a refused `SQLite` database is named in the plan.
    #[test]
    fn deploy_plan_names_a_refused_sqlite_database() {
        let mut config = AutumnConfig::default();
        config.database.url = Some("sqlite::memory:".to_owned());
        let note = sqlite_plan_note(&config, &resolved_defaults()).expect("a note");
        assert!(note.contains("IN-MEMORY"), "{note}");
        config.database.url = Some("sqlite://app.db".to_owned());
        assert_eq!(sqlite_plan_note(&config, &resolved_defaults()), None);
    }

    #[test]
    fn deploy_plan_runs_migrations_before_cutover_with_bounded_readiness_gate() {
        let resolved = resolved_defaults();
        let plan = build_deploy_plan(&resolved);
        let labels: Vec<&str> = plan.iter().map(|s| s.label).collect();

        let migrate = labels
            .iter()
            .position(|&l| l == "migrate")
            .expect("migrate step");
        let candidate = labels
            .iter()
            .position(|&l| l == "start-candidate")
            .expect("start-candidate step");
        let readiness = labels
            .iter()
            .position(|&l| l == "readiness-gate")
            .expect("readiness-gate step");
        let cutover = labels
            .iter()
            .position(|&l| l == "cutover")
            .expect("cutover step");
        let drain = labels
            .iter()
            .position(|&l| l == "drain")
            .expect("drain step");

        // (c) Migrations run before the readiness gate, which runs before cutover.
        assert!(
            migrate < readiness,
            "migrations must precede the readiness gate"
        );
        assert!(
            migrate < cutover,
            "migrations must precede cutover (a failed migration leaves the old version serving)"
        );
        assert!(readiness < cutover, "readiness gate must precede cutover");

        // (a) The candidate is started on a SEPARATE/distinct listener and the
        // step must NOT claim it binds the live `server.port` — starting on the
        // live port while the old release still serves would fail with
        // address-in-use before the readiness gate could run.
        let candidate_desc = &plan[candidate].description;
        let candidate_lc = candidate_desc.to_lowercase();
        assert!(
            candidate_lc.contains("separate") || candidate_lc.contains("distinct"),
            "candidate must start on a separate/distinct listener: {candidate_desc}"
        );
        assert!(
            candidate_lc.contains("does not bind") || candidate_lc.contains("not bind"),
            "candidate step must state it does NOT bind the live port: {candidate_desc}"
        );

        // (b) An explicit traffic-handoff/cutover step runs AFTER the readiness
        // gate and BEFORE draining the old release.
        assert!(
            readiness < cutover,
            "handoff must follow the readiness gate"
        );
        assert!(
            cutover < drain,
            "traffic handoff must precede draining the old release"
        );
        let cutover_desc = &plan[cutover].description.to_lowercase();
        assert!(
            cutover_desc.contains("hand") || cutover_desc.contains("traffic"),
            "cutover must describe a traffic handoff: {}",
            plan[cutover].description
        );

        // The readiness gate is bounded by the configured timeout and mentions
        // rollback on timeout (AC-4).
        let gate = &plan[readiness].description;
        assert!(
            gate.contains("60s"),
            "readiness gate should be bounded: {gate}"
        );
        assert!(
            gate.to_lowercase().contains("roll back"),
            "gate should roll back on timeout: {gate}"
        );

        // The plan ends by pruning to keep_releases.
        assert_eq!(plan.last().expect("non-empty plan").label, "prune");
        assert!(plan.last().unwrap().description.contains('3'));
    }

    #[test]
    fn rollback_plan_matches_rollback_ops_sequence() {
        let resolved = resolved_defaults();
        let plan = build_rollback_plan(&resolved);
        let labels: Vec<&str> = plan.iter().map(|s| s.label).collect();
        // The printed plan must mirror `exec::rollback_ops`' actual order.
        assert_eq!(
            labels,
            vec![
                "write-target-unit",
                "daemon-reload",
                "restart-previous",
                "proxy-flip",
                "record-previous",
                "repoint",
                "record-live-slot",
                "readiness-gate",
                "drain-rolled-back-slot",
            ],
            "printed rollback plan must match rollback_ops' execution order"
        );
        let pos = |l: &str| labels.iter().position(|&x| x == l).expect("step present");
        // Re-render the target unit and daemon-reload before restarting, so the
        // restart never relaunches a slot unit clobbered by an earlier failed
        // redeploy. Restart the previous unit before the health-gated flip, and flip
        // before repointing `current`; re-probe before draining the former-live slot.
        assert!(
            pos("write-target-unit") < pos("daemon-reload")
                && pos("daemon-reload") < pos("restart-previous"),
            "the target unit is re-rendered and daemon-reloaded before the restart"
        );
        assert!(
            pos("restart-previous") < pos("proxy-flip"),
            "previous unit must be up before the health-gated flip"
        );
        assert!(
            pos("proxy-flip") < pos("record-previous"),
            "flip must precede recording the previous-release marker"
        );
        assert!(
            pos("record-previous") < pos("repoint"),
            "the previous-release marker is recorded before `current` moves off it"
        );
        assert!(
            pos("proxy-flip") < pos("repoint"),
            "flip must precede the current-symlink repoint"
        );
        assert!(
            pos("restart-previous") < pos("readiness-gate"),
            "restart must precede the /ready re-probe"
        );
        assert!(
            pos("readiness-gate") < pos("drain-rolled-back-slot"),
            "the former-live slot is drained last, after the /ready re-probe"
        );
    }

    #[test]
    fn fleet_plan_matches_fleet_ops_sequence() {
        // #1621 (AC-4, T1.26): the forward twin of
        // `rollback_plan_matches_rollback_ops_sequence`. `build_deploy_plan` and the
        // fleet section it is printed with are DESCRIPTIVE — nothing links them to
        // `exec::cutover_ops` at compile time — so this guards the three claims the
        // printed fleet plan actually makes against the ops that really run.
        let fleet = ResolvedFleet::resolve(&fleet_cfg(&["web-a", "web-b", "web-c"]), "myapp")
            .expect("a well-formed fleet resolves");
        let modes = [
            fleet::HostMode::Redeploy,
            fleet::HostMode::Redeploy,
            fleet::HostMode::Redeploy,
        ];
        let plan = fleet::plan_fleet(&fleet, &modes).expect("a well-formed fleet plans");

        // (1) HOST ORDERING. The rendered section, the executable plan and the
        // resolved fleet all agree on declaration order — the documented rollout
        // contract.
        let hosts: Vec<String> = fleet
            .hosts
            .iter()
            .map(|h| h.host.clone().unwrap_or_default())
            .collect();
        let planned: Vec<String> = plan.hosts.iter().map(|h| h.host.clone()).collect();
        assert_eq!(
            planned, hosts,
            "the executable fleet plan must keep declaration order"
        );
        let rendered = fleet::fleet_plan_lines(&hosts).join("\n");
        let mut previous = 0usize;
        for host in &hosts {
            let at = rendered
                .find(host.as_str())
                .unwrap_or_else(|| panic!("{host} must be named in the plan:\n{rendered}"));
            assert!(
                at >= previous,
                "the printed fleet plan must list hosts in rollout order:\n{rendered}"
            );
            previous = at;
        }

        // (2) SINGLE MIGRATE. The section promises the migration runs once; the real
        // flattened op labels must carry exactly one `migrate`, before the first
        // cutover boundary anywhere in the fleet.
        let flat = fleet::test_support::fleet_op_labels(&fleet, &plan);
        assert_eq!(
            flat.iter().filter(|l| **l == "migrate").count(),
            1,
            "the plan promises one migration; the ops must schedule one: {flat:?}"
        );
        assert_eq!(
            rendered
                .matches(fleet::FLEET_MIGRATE_PLACEMENT_NOTE)
                .count(),
            1,
            "the migrate placement is one fleet-wide note, not a per-host line:\n{rendered}"
        );
        let migrate = flat
            .iter()
            .position(|l| *l == "migrate")
            .expect("the fleet migrates");
        let boundary = flat
            .iter()
            .position(|l| *l == "proxy-flip" || *l == "proxy-route")
            .expect("the fleet cuts over");
        assert!(
            migrate < boundary,
            "the plan's `[migrate] < [cutover]` claim must hold in the real ops: \
             migrate at {migrate}, boundary at {boundary}, labels: {flat:?}"
        );

        // (3) Step-label subset. Every printed step label either names a real executed
        // op or is one of the five deliberately mechanism-neutral labels: `build` is
        // local, `upload` executes as `upload-binary`, `cutover` as `proxy-flip`,
        // `drain` as `drain-old`, and `prepare-host` as the probe-gated `install-proxy`,
        // which runs only on a host with no proxy binary and so is legitimately absent
        // from this already-equipped fleet's ops. Partitioning, rather than a bare
        // `contains`, means a new plan step forces a deliberate decision here instead of
        // drifting away from the ops.
        let step_labels: Vec<&str> = build_deploy_plan(&fleet.hosts[0])
            .iter()
            .map(|s| s.label)
            .collect();
        let (executed, neutral): (Vec<&str>, Vec<&str>) =
            step_labels.iter().partition(|l| flat.contains(l));
        assert_eq!(
            executed,
            vec!["migrate", "start-candidate", "readiness-gate", "prune"],
            "these printed steps must name real executed ops: {step_labels:?} vs {flat:?}"
        );
        assert_eq!(
            neutral,
            vec!["build", "prepare-host", "upload", "cutover", "drain"],
            "only the documented mechanism-neutral plan labels may be absent from \
             the ops: {step_labels:?} vs {flat:?}"
        );
        // The plan's last step is `prune`, and so is the fleet's last real op.
        assert_eq!(
            step_labels.last().copied(),
            Some("prune"),
            "the printed plan ends with prune"
        );
        assert_eq!(
            flat.last().copied(),
            Some("prune"),
            "the fleet's last host ends with prune: {flat:?}"
        );
    }

    #[test]
    fn deploy_host_present_grader_is_offline_and_flags_missing_host() {
        // Present, non-blank host → passes with no network I/O.
        let ok = grade_deploy_host_present(Some("203.0.113.10"));
        assert!(ok.passed);
        assert_eq!(ok.name, "deploy_host");

        // Missing host → fails offline with the actionable `[deploy] host` hint,
        // matching the message `deploy check` uses.
        let missing = grade_deploy_host_present(None);
        assert!(!missing.passed, "missing host must fail offline");
        assert_eq!(missing.name, "deploy_host");
        assert_eq!(missing.detail, DEPLOY_HOST_MISSING_DETAIL);
        assert!(missing.hint.unwrap().contains("[deploy] host"));

        // Blank/whitespace host is treated the same as unset.
        let blank = grade_deploy_host_present(Some("   "));
        assert!(!blank.passed, "blank host must fail offline");
        assert_eq!(blank.detail, DEPLOY_HOST_MISSING_DETAIL);

        // Consistency: the offline host-present grader and the online SSH probe
        // report the missing-host case identically.
        let probe = grade_ssh_reachability(None, 22, Duration::from_millis(50));
        assert_eq!(probe.detail, missing.detail);
        assert_eq!(probe.hint, missing.hint);
    }

    #[test]
    fn ssh_reachability_fails_fast_without_host() {
        let check = grade_ssh_reachability(None, 22, Duration::from_millis(50));
        assert!(!check.passed);
        assert_eq!(check.name, "ssh_reachability");
        assert!(check.hint.unwrap().contains("[deploy] host"));

        // A blank host is treated the same as unset.
        let blank = grade_ssh_reachability(Some("   "), 22, Duration::from_millis(50));
        assert!(!blank.passed);
    }

    #[test]
    fn ssh_reachability_fails_when_all_addresses_unreachable() {
        // Offline + deterministic: the loopback with a port nothing listens on
        // refuses the connect on every resolved address, so the grader must FAIL
        // (not pass). Using a literal IP avoids DNS so the test never depends on
        // the resolver; port 1 is privileged and never bound by a test harness.
        let check = grade_ssh_reachability(Some("127.0.0.1"), 1, Duration::from_millis(100));
        assert!(!check.passed, "closed port should fail: {}", check.detail);
        assert_eq!(check.name, "ssh_reachability");
        assert!(check.detail.contains("cannot reach"));
    }

    #[test]
    fn signing_secret_grader_never_echoes_value() {
        let present = grade_signing_secret(Some("super-secret-value"), &[], false);
        assert!(present.passed);
        assert!(!present.detail.contains("super-secret-value"));

        let missing = grade_signing_secret(None, &[], false);
        assert!(!missing.passed);
        assert!(!grade_signing_secret(Some("   "), &[], false).passed);
    }

    #[test]
    fn signing_secret_grader_non_production_accepts_weak_secret() {
        // Outside production, a present, non-empty secret is enough: a dev/staging
        // deploy must not be blocked by the production strength rules.
        assert!(grade_signing_secret(Some("changeme"), &[], false).passed);
        assert!(grade_signing_secret(Some("short"), &[], false).passed);
        // A weak rotation secret is likewise fine outside production.
        assert!(grade_signing_secret(Some("changeme"), &["also-weak".to_owned()], false).passed);
    }

    #[test]
    fn signing_secret_grader_production_rejects_weak_secret() {
        // In production the grader reuses the runtime validator
        // (`autumn_web::security::validate_signing_secret`), which the app boot
        // path also runs before binding. A known demo value and a too-short
        // secret must both FAIL preflight so `deploy check` never greenlights a
        // release that would exit on startup.
        let demo = grade_signing_secret(Some("changeme"), &[], true);
        assert!(!demo.passed, "demo value must fail in production");
        assert!(demo.hint.is_some());
        // Never echo the secret value, even a known demo one.
        assert!(!demo.detail.contains("changeme"));

        let short = grade_signing_secret(Some("too-short"), &[], true);
        assert!(!short.passed, "too-short secret must fail in production");
        assert!(!short.detail.contains("too-short"));
    }

    #[test]
    fn signing_secret_grader_production_accepts_strong_secret() {
        // A 64-hex-char secret (openssl rand -hex 32) clears the runtime
        // validator's minimum length and is not a demo value.
        let strong = "a".repeat(64);
        let check = grade_signing_secret(Some(&strong), &[], true);
        assert!(
            check.passed,
            "strong production secret should pass: {}",
            check.detail
        );
        assert!(!check.detail.contains(&strong));
    }

    #[test]
    fn signing_secret_grader_production_missing_fails() {
        let check = grade_signing_secret(None, &[], true);
        assert!(!check.passed);
        assert!(check.hint.is_some());
    }

    #[test]
    fn signing_secret_grader_production_rejects_weak_previous_secret() {
        // The app boot path validates each `previous_secrets` entry with the same
        // rule and exits if any is weak, so a strong CURRENT secret paired with a
        // weak rotation entry must FAIL preflight rather than boot-crash later.
        let strong = "a".repeat(64);
        let check = grade_signing_secret(Some(&strong), &["changeme".to_owned()], true);
        assert!(
            !check.passed,
            "weak previous_secrets entry must fail in production"
        );
        assert!(check.hint.is_some());
        // Never echo the rotation secret value.
        assert!(!check.detail.contains("changeme"));
        // The message identifies it as a previous/rotation secret.
        assert!(
            check.detail.contains("previous"),
            "detail should name the rotation secret: {}",
            check.detail
        );
    }

    #[test]
    fn signing_secret_grader_production_accepts_strong_previous_secrets() {
        // Strong current + strong rotation entries pass.
        let strong = "a".repeat(64);
        let previous = vec!["b".repeat(64), "c".repeat(64)];
        let check = grade_signing_secret(Some(&strong), &previous, true);
        assert!(
            check.passed,
            "strong current + strong previous should pass: {}",
            check.detail
        );
    }

    #[test]
    fn signing_secret_grader_non_production_ignores_weak_previous_secret() {
        // Outside production, rotation entries are not strength-checked.
        let check = grade_signing_secret(Some("dev-secret"), &["changeme".to_owned()], false);
        assert!(check.passed);
    }

    #[test]
    fn database_url_grader_never_echoes_value() {
        // Force the DB-backed path so the missing-URL case still fails: a
        // configured `[database]` marks the app as database-backed.
        let absent = Path::new("autumn-deploy-no-such-migrations-dir-echo-guard");
        let present = grade_database_url(Some("postgres://user:pw@host/db"), absent, true, false);
        assert!(present.passed);
        assert!(!present.detail.contains("pw"));
        assert!(!grade_database_url(None, absent, true, false).passed);
    }

    #[test]
    fn database_url_grader_passes_for_db_free_app() {
        // No migrations directory and no configured `[database]`: a
        // zero-dependency daemon app has nothing to connect to, so preflight
        // must pass rather than require a URL.
        let tmp = tempfile::TempDir::new().unwrap();
        let absent_migrations = tmp.path().join("migrations");
        assert!(!absent_migrations.exists());
        let check = grade_database_url(None, &absent_migrations, false, false);
        assert!(
            check.passed,
            "DB-free app should pass the DB-URL preflight: {}",
            check.detail
        );
    }

    #[test]
    fn database_url_grader_fails_for_db_backed_runtime_without_url() {
        // No migrations dir and no `[database]` section, but a DB-backed runtime
        // feature (e.g. `jobs.backend = "postgres"` or `scheduler.backend =
        // "postgres"`) is enabled. Its startup path requires a configured pool,
        // so a missing writable URL must FAIL preflight rather than taking the
        // DB-free pass branch and failing at boot.
        let tmp = tempfile::TempDir::new().unwrap();
        let absent_migrations = tmp.path().join("migrations");
        assert!(!absent_migrations.exists());
        let check = grade_database_url(None, &absent_migrations, false, true);
        assert!(
            !check.passed,
            "DB-backed runtime feature without a URL must fail preflight"
        );
        assert!(
            check.hint.is_some(),
            "the failure should carry an actionable remediation hint"
        );
    }

    #[test]
    fn database_url_grader_passes_for_db_backed_runtime_with_url() {
        // The same DB-backed runtime feature WITH a writable primary URL passes.
        let tmp = tempfile::TempDir::new().unwrap();
        let absent_migrations = tmp.path().join("migrations");
        assert!(!absent_migrations.exists());
        let check = grade_database_url(
            Some("postgres://user:pw@host/db"),
            &absent_migrations,
            false,
            true,
        );
        assert!(
            check.passed,
            "DB-backed runtime feature with a URL should pass: {}",
            check.detail
        );
        assert!(!check.detail.contains("pw"));
    }

    #[test]
    fn database_url_grader_fails_for_db_backed_app_without_url() {
        // A migrations directory (the same presence check `grade_migrate_check`
        // uses) marks the app as database-backed, so a missing URL must fail
        // with an actionable hint.
        let tmp = tempfile::TempDir::new().unwrap();
        let migrations = tmp.path().join("migrations");
        std::fs::create_dir(&migrations).unwrap();
        let check = grade_database_url(None, &migrations, false, false);
        assert!(
            !check.passed,
            "DB-backed app without a URL should fail preflight"
        );
        assert!(
            check.hint.is_some(),
            "the failure should carry an actionable remediation hint"
        );
    }

    #[test]
    fn shard_only_config_resolves_a_usable_db_url() {
        use autumn_web::config::{DatabaseConfig, ShardConfig};

        // A shard-only app: no control `primary_url`/`url`/`replica_url`, but one
        // `[[database.shards]]` entry with a `primary_url`. `autumn migrate` would
        // target that shard, so the preflight must treat the app as having a
        // usable database and PASS even with a migrations directory present.
        let db = DatabaseConfig {
            shards: vec![ShardConfig {
                name: "shard0".to_owned(),
                primary_url: "postgres://user:pw@shard0/app".to_owned(),
                ..Default::default()
            }],
            ..Default::default()
        };
        assert!(db.effective_primary_url().is_none());

        let url = resolve_writable_db_url(&db);
        assert_eq!(url, Some("postgres://user:pw@shard0/app"));

        // Migrations dir present + database configured (has_shards) → DB-backed.
        let tmp = tempfile::TempDir::new().unwrap();
        let migrations = tmp.path().join("migrations");
        std::fs::create_dir(&migrations).unwrap();
        let check = grade_database_url(url, &migrations, true, false);
        assert!(
            check.passed,
            "shard-only app with migrations should pass the DB-URL preflight: {}",
            check.detail
        );
        // The grader must never echo the shard credentials.
        assert!(!check.detail.contains("pw"));
    }

    #[test]
    fn replica_only_config_resolves_no_writable_url_and_fails_with_migrations() {
        use autumn_web::config::DatabaseConfig;

        // A replica-only app: only `database.replica_url` is set — no control
        // `primary_url`/`url` and no `[[database.shards]]`. `autumn migrate` only
        // ever targets a writable primary/control or shard-primary URL (see
        // `migrate::build_targets`); it can never migrate against a replica. So
        // the writable-URL resolver must return None, and a project with a
        // `migrations/` dir must FAIL the DB-URL preflight rather than passing on
        // a replica the migration step can't use.
        let db = DatabaseConfig {
            replica_url: Some("postgres://user:pw@replica/app".to_owned()),
            ..Default::default()
        };
        assert!(db.effective_primary_url().is_none());

        let url = resolve_writable_db_url(&db);
        assert_eq!(
            url, None,
            "replica_url alone is not a writable migration target"
        );

        // Migrations dir present + database configured (replica_url set) →
        // DB-backed, but no writable URL → FAIL with an actionable hint.
        let tmp = tempfile::TempDir::new().unwrap();
        let migrations = tmp.path().join("migrations");
        std::fs::create_dir(&migrations).unwrap();
        let check = grade_database_url(url, &migrations, true, false);
        assert!(
            !check.passed,
            "replica-only app with migrations must fail the DB-URL preflight"
        );
        assert!(
            check.hint.is_some(),
            "the failure should carry an actionable remediation hint"
        );
        // The grader must never echo the replica credentials.
        assert!(!check.detail.contains("pw"));
    }

    #[test]
    fn migrate_check_passes_when_no_migrations_dir() {
        let dir = std::env::temp_dir().join("autumn-deploy-no-such-migrations-dir-xyz");
        let check = grade_migrate_check(&dir);
        assert!(
            check.passed,
            "absent migrations dir should pass: {}",
            check.detail
        );
    }

    #[test]
    fn is_production_profile_matches_runtime_rule() {
        assert!(is_production_profile(Some("prod")));
        assert!(is_production_profile(Some("production")));
        assert!(!is_production_profile(Some("dev")));
        assert!(!is_production_profile(Some("staging")));
        assert!(!is_production_profile(None));
    }

    #[test]
    fn requires_database_pool_detects_postgres_backends() {
        use autumn_web::config::{AutumnConfig, SchedulerBackend};

        // Default (local jobs, in-process scheduler): no pool required.
        let mut config = AutumnConfig::default();
        assert!(!requires_database_pool(&config));

        // jobs.backend = "postgres" → pool required.
        config.jobs.backend = "postgres".to_owned();
        assert!(requires_database_pool(&config));

        // scheduler.backend = postgres → pool required.
        let mut config = AutumnConfig::default();
        config.scheduler.backend = SchedulerBackend::Postgres;
        assert!(requires_database_pool(&config));

        // A non-postgres jobs backend (redis/local) does not require a PG pool.
        let mut config = AutumnConfig::default();
        config.jobs.backend = "redis".to_owned();
        assert!(!requires_database_pool(&config));
    }

    #[test]
    fn rollback_dispatch_does_not_load_media_config() {
        // Finding F: the media host config is loaded ONLY in the plan/up action
        // paths. `check`/`rollback` neither read nor provision MediaMTX, so a typo
        // in `[media.mediamtx]`/`[media.ffmpeg]` must not fail-close a rollback (a
        // regression the round-2 fail-closed load would otherwise reintroduce). The
        // load is filesystem-coupled (`manifest_project_dirs()`), so we assert the
        // dispatch source itself: the fallible load call appears only inside the
        // Plan and Up match arms, never in Check/Rollback.
        let src = include_str!("deploy.rs");
        // Build the needle at runtime so this test's own source text (which mentions
        // the fn name) can never be miscounted as a call site. The loader now takes
        // the resolved deploy config (Finding O), so match the call shape, not `()`.
        let needle = ["load_media_host_config", "(&resolved)?"].concat();
        let call_sites = src.matches(needle.as_str()).count();
        assert_eq!(
            call_sites, 2,
            "expected exactly two fallible load-media call sites (Plan + Up), found {call_sites}",
        );

        // Isolate `run()`'s match arms and prove Rollback/Check don't load media.
        let run_body = src
            .split("pub fn run(action: DeployAction)")
            .nth(1)
            .expect("run() present");
        let rollback_arm = run_body
            .split("DeployAction::Rollback =>")
            .nth(1)
            .expect("Rollback arm present");
        // Rollback dispatch line runs to the next arm.
        let rollback_line = rollback_arm
            .split("DeployAction::Up")
            .next()
            .expect("Up arm follows Rollback");
        assert!(
            !rollback_line.contains("load_media_host_config"),
            "the Rollback arm must not load the media config",
        );
        let check_arm = run_body
            .split("DeployAction::Check =>")
            .nth(1)
            .and_then(|s| s.split("DeployAction::Rollback").next())
            .expect("Check arm present");
        assert!(
            !check_arm.contains("load_media_host_config"),
            "the Check arm must not load the media config",
        );
    }

    #[test]
    fn media_provisioning_is_deferred_past_app_cutover_in_up() {
        // Finding K: the mutating MediaMTX provisioning must run only after the app
        // deploy and cutover commit. The app deploy rolls back on failure — readiness
        // gate, migrations — and leaves the old release serving, and there is
        // deliberately no media teardown, so writing and restarting the host MediaMTX
        // unit before the app is committed would strand a rolled-back release against a
        // moved media daemon. This asserts the source order of the `up` path: the
        // non-mutating preflight precedes the rollout loop, and `provision_media_host`
        // is invoked only after that loop has run every host to completion.
        //
        // #1621 re-anchored the middle marker. `run_up` is now a fleet-shaped driver
        // (`run_up` prologue plus `run_up_with` loop), so the commit point is the
        // per-host execution loop rather than a single `result.map_err(...)?` line — a
        // strictly stronger statement: provisioning must follow the last host's cutover,
        // not merely one host's.
        let src = include_str!("deploy.rs");
        let up_body = src
            .split("fn run_up(")
            .nth(1)
            .and_then(|s| s.split("\nfn run_rollback(").next())
            .expect("run_up body present");

        let preflight_at = up_body
            .find("check_media_host_preflight(input.media_cfg")
            .expect("preflight call present on the up path");
        // The per-host cutovers happen inside this loop. A failed host breaks out of
        // it and returns from the halt block immediately below — after its own
        // teardown and after any fleet compensation (#1621 slice 4) — so nothing
        // past that point runs.
        let commit_at = up_body
            .find("for (index, host_plan) in plan.hosts.iter().enumerate()")
            .expect("per-host execution loop present on the up path");
        let provision_at = up_body
            .find("provision_media_host(input.media_cfg, executor)?;")
            .expect("deferred provisioning call present on the up path");

        assert!(
            preflight_at < commit_at,
            "media preflight must precede the per-host execution loop",
        );
        assert!(
            commit_at < provision_at,
            "MediaMTX provisioning must run only AFTER every host's cutover commits — so a \
             rolled-back or halted rollout (which returns from the loop's halt path) never \
             reaches it",
        );

        // The preflight itself is non-mutating: it runs the doctor checks but must
        // NOT drive the controller ops (those live only in provision_media_host).
        let preflight_fn = src
            .split("fn check_media_host_preflight(")
            .nth(1)
            .and_then(|s| s.split("\nfn provision_media_host(").next())
            .expect("check_media_host_preflight present");
        assert!(
            preflight_fn.contains("collect_media_doctor_checks"),
            "preflight must run the doctor checks",
        );
        assert!(
            !preflight_fn.contains("ensure_installed_ops"),
            "preflight must NOT drive the mutating controller ops (write/restart)",
        );

        // And the mutating provisioning is reachable only on the post-commit path.
        let after_commit = &up_body[commit_at..];
        assert!(
            after_commit.contains("provision_media_host(input.media_cfg, executor)?;"),
            "provisioning must sit on the post-commit path (unreachable when a host's \
             deploy errors out and the rollout halts)",
        );
    }

    #[test]
    fn media_binary_install_runs_before_cutover_in_up() {
        // The MediaMTX binary install (#1974) only adds a file at an empty path,
        // so it runs BEFORE cutover, as the first media op on the host.
        // A failed install then halts the rollout like any pre-cutover failure,
        // and the app is never live without its media daemon.
        let src = include_str!("deploy.rs");
        let up_body = src
            .split("fn run_up(")
            .nth(1)
            .and_then(|s| s.split("\nfn run_rollback(").next())
            .expect("run_up body present");

        let loop_at = up_body
            .find("for (index, host_plan) in plan.hosts.iter().enumerate()")
            .expect("per-host execution loop present");
        let install_at = up_body
            .find("ops.splice(0..0, media_binary_install_ops(input.media_cfg));")
            .expect("the media binary install is spliced into the host's ops");
        let proxy_install_at = up_body
            .find("ops.splice(0..0, install);")
            .expect("the proxy install splice is present");
        let provision_at = up_body
            .find("provision_media_host(input.media_cfg, executor)?;")
            .expect("deferred provisioning call present");

        assert!(loop_at < install_at, "install runs inside the host's turn");
        assert!(
            install_at < proxy_install_at,
            "spliced before the proxy install, so it runs right after it"
        );
        assert!(install_at < provision_at);
    }

    // ── Fleet rollout driver (issue #1621, slice 3) ──────────────────────────
    //
    // These drive the WHOLE loop — prologue probe → plan → per-host execute —
    // against one strict recording fake per host, through the `run_up_with` seam.
    // Nothing here contacts a host, resolves a binary, or reads the filesystem:
    // every filesystem-coupled prologue step (preflight, binary resolution,
    // manifest location, release-id minting) is resolved by `run_up` and handed in
    // as data, which is what makes the rollout itself unit-testable.

    /// The read-only probe labels a rollout is allowed to run before (and without)
    /// mutating anything. Enumerated here, not imported, so a new mutating op can
    /// never quietly join the allowlist: the "zero mutations" assertions below are
    /// only as strong as this list is short.
    const READ_ONLY_PROBES: [&str; 3] =
        ["proxy-compat-probe", "detect-current", "probe-release-dir"];

    /// The exact ordered `Run` labels of today's single-host zero-downtime
    /// redeploy — the same vector `redeploy_produces_exact_zero_downtime_sequence`
    /// (`exec.rs`) pins, restated here so a fleet host's sequence is asserted
    /// against the protected contract and not merely against itself.
    const REDEPLOY_RUN_LABELS: [&str; 13] = [
        "proxy-snapshot-unit",
        "proxy-install",
        "proxy-restart-if-changed",
        "prepare-dirs",
        "daemon-reload",
        "start-candidate",
        "migrate",
        "readiness-gate",
        "proxy-flip",
        "commit-markers",
        "record-proxy-options",
        "drain-old",
        "prune",
    ];

    /// The exact ordered `Run` labels ONE host records in a fleet-wide rollback:
    /// the read-only previous-release probe, then the UNCHANGED on-demand
    /// `rollback_ops` sequence (`write-target-unit` is an upload, so it is not a
    /// `Run`). Restated here rather than imported so a fleet rollback can never
    /// quietly grow a step the single-host rollback does not have.
    const FLEET_ROLLBACK_RUN_LABELS: [&str; 7] = [
        "resolve-previous",
        "daemon-reload",
        "restart-previous",
        "proxy-flip",
        "commit-markers",
        "readiness-gate",
        "drain-rolled-back-slot",
    ];

    const FLEET_RELEASE_ID: &str = "20260714T120000Z";
    const FLEET_PUBLIC_PORT: u16 = 3000;

    /// The halt report inside a [`DeployError::FleetHalted`], or a panic naming
    /// what came instead. Every fleet-failure test asserts on the same shape, so
    /// unwrapping it once keeps those assertions about the FLEET rather than about
    /// the boxing.
    fn fleet_halt_of(err: &DeployError) -> &FleetHalt {
        match err {
            DeployError::FleetHalted(halt) => halt,
            other => panic!("expected a fleet halt, got: {other:?}"),
        }
    }

    fn fleet_of(hosts: &[&str]) -> ResolvedFleet {
        ResolvedFleet::resolve(
            &DeployConfig {
                hosts: hosts.iter().map(|h| (*h).to_owned()).collect(),
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("a well-formed fleet resolves")
    }

    /// Probe stdout for a host already serving on the blue slot. The unit/options
    /// delimiters are deliberately absent, so the installed proxy port and the
    /// proxy-options marker both degrade to `Absent` — "nothing to conflict with",
    /// the shape a legacy host presents.
    fn redeploy_probe() -> String {
        "redeploy:blue\t3001\n---autumn-kamal-proxy-list---\n".to_owned()
    }

    /// Probe stdout for a host with nothing installed yet.
    fn first_deploy_probe() -> String {
        "first\n---autumn-kamal-proxy-list---\n".to_owned()
    }

    /// Probe stdout whose `shared/proxy-options` marker is PRESENT but unparseable
    /// (no tab field) — the fail-closed `#2074` shape.
    fn unreadable_proxy_options_probe() -> String {
        "redeploy:blue\t3001\n\
         ---autumn-kamal-proxy-list---\n\
         ---autumn-kamal-proxy-unit---\n\
         --http-port 3000\n\
         ---autumn-kamal-proxy-options---\n\
         garbage\n"
            .to_owned()
    }

    /// A `kamal-proxy deploy --help` capture carrying every flag the cutover uses,
    /// so the compat probe passes.
    fn compatible_deploy_help() -> &'static str {
        "Usage:\n  kamal-proxy deploy SERVICE [flags]\n\nFlags:\n  \
         --target host:port\n  --health-check-path string\n  --host strings\n  \
         --tls\n  --deploy-timeout duration\n  --drain-timeout duration\n  \
         --force\n\
         ---autumn-kamal-proxy-remove-help---\
         Usage:\n  kamal-proxy remove SERVICE [flags]\n"
    }

    fn fleet_manifests() -> Vec<exec::ManifestUpload> {
        vec![exec::ManifestUpload {
            local: PathBuf::from("/local/autumn.toml"),
            remote_basename: "autumn.toml".to_owned(),
        }]
    }

    /// Script one host as a healthy redeploy: compatible proxy, serving on blue,
    /// no release-dir collision.
    fn script_redeploy(
        recorder: fleet::test_support::FleetRecorder,
        host: &str,
    ) -> fleet::test_support::FleetRecorder {
        recorder
            .script(host, "proxy-compat-probe", compatible_deploy_help())
            .script(host, "detect-current", redeploy_probe())
            .script(host, "probe-release-dir", "absent")
    }

    /// Script one host as a healthy FIRST deploy.
    fn script_first_deploy(
        recorder: fleet::test_support::FleetRecorder,
        host: &str,
    ) -> fleet::test_support::FleetRecorder {
        recorder
            .script(host, "proxy-compat-probe", compatible_deploy_help())
            .script(host, "detect-current", first_deploy_probe())
            .script(host, "probe-release-dir", "absent")
    }

    /// Script one BARE host (issue #1607, AC-1): the compat probe answers nothing,
    /// which is what a host with no kamal-proxy at `/usr/local/bin` looks like.
    fn script_bare_first_deploy(
        recorder: fleet::test_support::FleetRecorder,
        host: &str,
    ) -> fleet::test_support::FleetRecorder {
        recorder
            .script(host, "proxy-compat-probe", "")
            .script(host, "detect-current", first_deploy_probe())
            .script(host, "probe-release-dir", "absent")
    }

    #[test]
    fn a_bare_host_installs_the_proxy_as_the_first_op_of_its_own_turn() {
        // #1607 (AC-1): "the command performs any remaining host preparation
        // itself". The install must sit at the head of that host's OWN turn, not in
        // the all-hosts probe phase — otherwise a fleet whose last host is
        // unreachable would already have modified the earlier hosts before grading
        // finished, breaking "no host is touched until every host is graded".
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_bare_first_deploy(recorder, "web-a");
        recorder = script_bare_first_deploy(recorder, "web-b");
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect("a bare fleet deploys after preparing each host");

        for host in ["web-a", "web-b"] {
            let labels = recorder.run_labels_for(host);
            let install = labels
                .iter()
                .position(|l| *l == "install-proxy")
                .unwrap_or_else(|| panic!("host {host} must be prepared: {labels:?}"));
            let first_mutating = recorder
                .first_mutating(host, &READ_ONLY_PROBES)
                .expect("a deployed host mutates something");
            assert_eq!(
                labels[install..install + 2].to_vec(),
                vec!["install-proxy", "proxy-install"],
                "the install must precede the proxy unit it supervises on {host}: {labels:?}"
            );
            assert!(
                recorder
                    .positions_of("install-proxy")
                    .contains(&first_mutating),
                "host preparation must be the FIRST thing that touches {host} \
                 (its first mutating call was at tape position {first_mutating})"
            );
        }

        // Both hosts finished being GRADED before either was prepared: every
        // read-only probe on the fleet tape precedes the first install.
        let first_install = *recorder
            .positions_of("install-proxy")
            .first()
            .expect("the fleet prepares a host");
        for label in READ_ONLY_PROBES {
            let last_probe = *recorder
                .positions_of(label)
                .last()
                .unwrap_or_else(|| panic!("every host runs {label}"));
            assert!(
                last_probe < first_install,
                "the probe phase must finish before anything is installed: {label} at \
                 {last_probe}, first install at {first_install}"
            );
        }
    }

    #[test]
    fn a_bare_redeploy_host_is_prepared_before_its_marker_repair() {
        // A host can need BOTH: no proxy binary and a drifted live-slot marker. Host
        // preparation must still come first — the marker repair (and everything
        // after it) is only worth attempting once the proxy the host is supposed to
        // be running actually exists.
        let fleet = fleet_of(&["web-a"]);
        // The marker says blue (3001) but the proxy is serving green (public + 2 =
        // 3002), so the deploy reconciles onto the proxy's truth and repairs the
        // marker as an early op.
        let drifted = "redeploy:blue\t3001\n\
             ---autumn-kamal-proxy-list---\n\
             Service   Host          Target            State    TLS\n\
             myapp     example.com   127.0.0.1:3002   running  no\n\
             ---autumn-kamal-proxy-unit---\n--http-port 3000\n"
            .to_owned();
        let recorder = fleet::test_support::FleetRecorder::new()
            .script("web-a", "proxy-compat-probe", "")
            .script("web-a", "detect-current", drifted)
            .script("web-a", "probe-release-dir", "absent");
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect("a bare, drifted host deploys after being prepared");

        let labels = recorder.run_labels_for("web-a");
        let install = labels
            .iter()
            .position(|l| *l == "install-proxy")
            .expect("a bare host is prepared");
        let repair = labels
            .iter()
            .position(|l| *l == exec::LIVE_SLOT_REPAIR_LABEL)
            .expect("a drifted marker is repaired");
        assert!(
            install < repair,
            "host preparation must precede the marker repair: {labels:?}"
        );
        let first_mutating = recorder
            .first_mutating("web-a", &READ_ONLY_PROBES)
            .expect("a deployed host mutates something");
        assert!(
            recorder
                .positions_of("install-proxy")
                .contains(&first_mutating),
            "host preparation is still the FIRST thing that touches the host"
        );
    }

    #[test]
    fn declining_host_preparation_refuses_a_bare_host_without_touching_it() {
        // #1607: `[deploy] install_proxy = false` is the documented opt-out. It must
        // reach the assessor through the REAL call site — a hardcoded `Auto` there
        // would silently ignore the setting — and a declined host must be left
        // completely alone, not half-prepared.
        let mut cfg = fleet_cfg(&["web-a"]);
        cfg.install_proxy = false;
        let fleet = ResolvedFleet::resolve(&cfg, "myapp").expect("a one-host fleet resolves");
        let recorder = fleet::test_support::FleetRecorder::new()
            .script("web-a", "proxy-compat-probe", "")
            .script("web-a", "detect-current", first_deploy_probe())
            .script("web-a", "probe-release-dir", "absent");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a bare host with host prep declined must refuse");
        let message = err.to_string();
        assert!(
            message.contains("install_proxy"),
            "the refusal must name the setting in force: {message}"
        );
        assert_eq!(
            recorder.run_labels_for("web-a"),
            vec!["proxy-compat-probe"],
            "a declined host must be left untouched"
        );
    }

    #[test]
    fn a_failed_host_preparation_halts_the_rollout_and_touches_no_later_host() {
        // Host preparation is an ordinary PRE-cutover op, so its failure must behave
        // like any other: this host is compensated, and the rest of the fleet is
        // never reached.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_bare_first_deploy(recorder, "web-a");
        recorder = script_bare_first_deploy(recorder, "web-b");
        recorder = recorder.fail("web-a", "install-proxy");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a failed host preparation must fail the rollout");
        assert!(
            err.to_string().contains("install-proxy"),
            "the failing step is named: {err}"
        );
        // web-a never got past its first op: nothing was uploaded, nothing started,
        // and the only ops after the failure are the first-deploy teardown that
        // compensates it.
        let web_a = recorder.run_labels_for("web-a");
        let (probes, rest) = web_a.split_at(READ_ONLY_PROBES.len());
        assert_eq!(probes, READ_ONLY_PROBES);
        assert_eq!(rest[0], "install-proxy");
        assert!(
            rest[1..].iter().all(|l| l.starts_with("teardown-")),
            "only compensation may follow a failed host preparation: {web_a:?}"
        );
        // …and web-b was only ever GRADED, never touched.
        assert_eq!(
            recorder.run_labels_for("web-b"),
            READ_ONLY_PROBES.to_vec(),
            "a halt must leave every later host untouched"
        );
    }

    #[test]
    fn a_host_that_already_has_the_proxy_is_never_prepared() {
        // Idempotence, at the driver level: the compat probe answers, so nothing is
        // installed on either host.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_first_deploy(recorder, "web-a");
        recorder = script_redeploy(recorder, "web-b");
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect("an equipped fleet deploys");

        assert!(
            recorder.positions_of("install-proxy").is_empty(),
            "an equipped host must never be re-prepared"
        );
    }

    /// The release a compensated redeploy host rolls BACK to — the blue release it
    /// was serving before this run flipped it to green.
    const PREVIOUS_RELEASE_DIR: &str = "/srv/autumn/myapp/releases/20260101T000000Z";

    /// Script the two read-only probes a compensating rollback runs on a host: the
    /// previous-release marker, and the §4.7 precheck that the dir it names still
    /// exists. `target_dir` is the precheck's answer (`present`/`absent`/garbage).
    fn script_compensation(
        recorder: fleet::test_support::FleetRecorder,
        host: &str,
        target_dir: &'static str,
    ) -> fleet::test_support::FleetRecorder {
        recorder
            .script(
                host,
                "resolve-previous",
                format!("prev:{PREVIOUS_RELEASE_DIR}\tblue\t3001"),
            )
            .script(host, "probe-rollback-target", target_dir)
    }

    /// The ordered `Run` labels of a compensating rollback on one host: the two
    /// read-only probes, then the unchanged on-demand `rollback_ops` sequence
    /// (`write-target-unit` is an upload, so it is not a `Run`).
    const COMPENSATION_RUN_LABELS: [&str; 8] = [
        "resolve-previous",
        "probe-rollback-target",
        "daemon-reload",
        "restart-previous",
        "proxy-flip",
        "commit-markers",
        "readiness-gate",
        "drain-rolled-back-slot",
    ];

    /// The `Run` labels a host records for a full redeploy plus the compensating
    /// rollback that followed it.
    fn redeploy_then_compensated(migrated: bool) -> Vec<&'static str> {
        READ_ONLY_PROBES
            .iter()
            .copied()
            .chain(
                REDEPLOY_RUN_LABELS
                    .iter()
                    .copied()
                    .filter(|label| migrated || *label != "migrate"),
            )
            .chain(COMPENSATION_RUN_LABELS)
            .collect()
    }

    /// Build a driver input over `fleet` with every fleet-wide value fixed, so the
    /// per-host op vectors are byte-comparable against the single-host builders.
    struct FleetFixture {
        env_file: exec::Secret,
        manifests: Vec<exec::ManifestUpload>,
        proxy: proxy::KamalProxyController,
        media_cfg: media::MediaMtxHostConfig,
        binary: PathBuf,
    }

    impl FleetFixture {
        fn new() -> Self {
            Self {
                env_file: exec::Secret::new("AUTUMN_SECURITY__SIGNING_SECRET=topsecret\n"),
                manifests: fleet_manifests(),
                proxy: proxy::KamalProxyController::new(60),
                media_cfg: media::MediaMtxHostConfig::default(),
                binary: PathBuf::from("/local/target/release/myapp"),
            }
        }

        /// The production shape: a halt compensates the hosts that already cut over.
        fn input<'a>(
            &'a self,
            fleet: &'a ResolvedFleet,
        ) -> FleetUpInput<'a, proxy::KamalProxyController> {
            FleetUpInput {
                profile: "prod",
                app_name: "myapp",
                fleet,
                proxy: &self.proxy,
                checks: &[],
                env_file: &self.env_file,
                binary: &self.binary,
                manifests: &self.manifests,
                release_id: FLEET_RELEASE_ID,
                public_port: FLEET_PUBLIC_PORT,
                media_cfg: &self.media_cfg,
                ffmpeg_bin: "ffmpeg",
                // No `--only`: the rollout covers everything the config declares.
                configured_host_count: fleet.hosts.len(),
                db: FleetDatabaseFacts::default(),
                // Durable by default in the fakes: the AC-8 warning has its own
                // unit test, and it must not add a line to every driver tape.
                jobs_backend: "postgres",
                scheduler_in_process: false,
                auto_rollback: true,
                bake: None,
                metrics_path: "/actuator/metrics",
                bake_host: Some("app.example.com"),
            }
        }

        /// Halt-and-freeze: stop at the first failure and change nothing else, for
        /// inspection (#1621, §4.7 — the internal seam behind the `--no-rollback`
        /// flag the fleet CLI surface adds).
        fn input_frozen<'a>(
            &'a self,
            fleet: &'a ResolvedFleet,
        ) -> FleetUpInput<'a, proxy::KamalProxyController> {
            FleetUpInput {
                profile: "prod",
                app_name: "myapp",
                auto_rollback: false,
                ..self.input(fleet)
            }
        }

        /// The exact ordered calls today's SINGLE-host `run_up` would record for
        /// `cfg` on the given path — built from the same unchanged per-host
        /// builders, driven through the same plain recording fake.
        fn todays_calls(
            &self,
            cfg: &ResolvedDeployConfig,
            mode: fleet::HostMode,
            migrate: exec::MigrateStep,
        ) -> Vec<exec::test_support::RecordedCall> {
            let slots = match mode {
                fleet::HostMode::First => exec::SlotPlan::first(FLEET_PUBLIC_PORT),
                fleet::HostMode::Redeploy => {
                    exec::SlotPlan::redeploy(FLEET_PUBLIC_PORT, exec::SLOT_BLUE)
                }
            };
            let release_dir = format!("{}/{FLEET_RELEASE_ID}", cfg.releases_dir());
            let unit = render_app_unit(
                cfg,
                &release_dir,
                slots.candidate_port,
                slots.candidate_slot,
            );
            let ops = match mode {
                fleet::HostMode::First => exec::first_deploy_ops(
                    cfg,
                    &self.proxy,
                    &unit,
                    self.env_file.clone(),
                    &self.binary,
                    &self.manifests,
                    FLEET_RELEASE_ID,
                    &slots,
                    migrate,
                ),
                fleet::HostMode::Redeploy => exec::cutover_ops(
                    cfg,
                    &self.proxy,
                    &unit,
                    self.env_file.clone(),
                    &self.binary,
                    &self.manifests,
                    FLEET_RELEASE_ID,
                    &slots,
                    &self.proxy.proxy_service_options(),
                    migrate,
                ),
            };
            let recorder = exec::test_support::RecordingExecutor::new();
            exec::run_ops(&ops, &recorder).expect("the recording fake never fails");
            recorder.calls()
        }
    }

    #[test]
    fn fleet_halted_carries_only_host_names_and_static_labels() {
        // #1621: `FleetHalted` is the one error type that describes partial fleet
        // state, so it is the one most tempting to enrich with "context". Every
        // field is a host name or a `&'static str` op label — never a shell line, a
        // remote path, or a formatted source error (a failed migration's driver
        // error can embed the database URL, which is exactly why
        // `apply_pending_or_exit` redacts it).
        let err = fleet_halted(
            &fleet::FleetPlan {
                hosts: vec![
                    fleet::HostPlan {
                        host: "web-a".to_owned(),
                        mode: fleet::HostMode::Redeploy,
                        migrate: exec::MigrateStep::Run,
                    },
                    fleet::HostPlan {
                        host: "web-b".to_owned(),
                        mode: fleet::HostMode::Redeploy,
                        migrate: exec::MigrateStep::Skip,
                    },
                ],
            },
            &[
                fleet::HostOutcome::Degraded { label: "prune" },
                fleet::HostOutcome::AmbiguousMarkers,
            ],
            // #1621 slice 4: the degraded log and the manual list are the two
            // richest new fields, so the secrets assertion below covers them too.
            &[("web-a".to_owned(), "prune")],
            "web-b".to_owned(),
            "migrate",
        );

        let rendered = format!("{err}\n{err:?}");
        assert!(
            rendered.contains("web-b") && rendered.contains("migrate"),
            "the halt must name the failing host and step: {rendered}"
        );
        assert!(
            rendered.contains("prune") && rendered.contains("web-a"),
            "the degraded log must name the host and the housekeeping label: {rendered}"
        );
        assert!(
            rendered.contains(fleet::MANUAL_AMBIGUOUS_MARKERS),
            "an ambiguous-marker host must be reported as needing a human: {rendered}"
        );
        assert!(
            rendered.contains("NOT rolled back"),
            "the halt must state that the schema did not come back with the binaries: \
             {rendered}"
        );
        for secret in [
            "postgres://",
            "topsecret",
            "AUTUMN_SECURITY__SIGNING_SECRET",
            "systemd-run",
        ] {
            assert!(
                !rendered.contains(secret),
                "FleetHalted must never carry `{secret}`: {rendered}"
            );
        }
    }

    // ── #2267: a halted rollout or drift sends a #1610 operator alert ───────

    #[derive(Default)]
    struct CapturingChannel {
        received: Arc<std::sync::Mutex<Vec<Alert>>>,
    }

    impl AlertChannel for CapturingChannel {
        fn name(&self) -> &'static str {
            "capturing"
        }
        fn deliver<'a>(&'a self, alert: &'a Alert) -> autumn_web::alerts::AlertDeliveryFuture<'a> {
            let received = Arc::clone(&self.received);
            let cloned = alert.clone();
            Box::pin(async move {
                received.lock().expect("lock").push(cloned);
                Ok(())
            })
        }
    }

    fn sample_halt() -> FleetHalt {
        FleetHalt {
            failed_host: "web-b".to_owned(),
            failed_step: "migrate",
            rolled_back: vec!["web-a".to_owned()],
            torn_down: vec![],
            still_on_new: vec![],
            degraded: vec![("web-a".to_owned(), "prune")],
            route_removal_failed: vec![],
            manual: vec![("web-c".to_owned(), fleet::MANUAL_AMBIGUOUS_MARKERS)],
        }
    }

    #[test]
    fn alert_channels_for_respects_the_enabled_master_switch() {
        // Review finding on #2267: `[alerts] enabled = false` must silence a
        // deploy alert, even when a transport is still configured.
        let alerts = autumn_web::alerts::AlertConfig {
            enabled: false,
            pagerduty_routing_key: Some("R0123".to_owned()),
            ..Default::default()
        };
        let http = autumn_web::config::HttpConfig::default();

        assert!(
            alert_channels_for(&alerts, &http).is_empty(),
            "a disabled [alerts] config must build no channel"
        );
    }

    #[test]
    fn alert_channels_for_builds_channels_when_active() {
        let alerts = autumn_web::alerts::AlertConfig {
            enabled: true,
            pagerduty_routing_key: Some("R0123".to_owned()),
            ..Default::default()
        };
        let http = autumn_web::config::HttpConfig::default();

        assert_eq!(
            alert_channels_for(&alerts, &http).len(),
            1,
            "an enabled [alerts] config with a destination must build a channel"
        );
    }

    #[test]
    fn deploy_alert_channels_for_profile_is_empty_without_a_configured_destination() {
        // No fixture project directory is set up for this test, so the
        // profile load resolves to defaults (or fails) either way — this
        // must never panic, and with no [alerts] destination it must
        // deliver nothing.
        assert!(deploy_alert_channels_for_profile("prod").is_empty());
    }

    #[test]
    fn declared_alert_config_in_reads_the_target_profile_section() {
        // Review finding on #2267: this fallback must resolve the SAME
        // target-profile layering `load_runtime_config` would, so a
        // production-only destination is still found on this path too.
        let dir = tempfile::TempDir::new().expect("temp project dir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[deploy]\nhost = \"deploy.example.test\"\n\n\
             [profile.prod.alerts]\npagerduty_routing_key = \"R0123\"\n",
        )
        .expect("write autumn.toml");

        let (alerts, _http) = declared_alert_config_in(&[dir.path().to_path_buf()], "prod")
            .expect("the merged [alerts] subtree deserializes");

        assert_eq!(alerts.pagerduty_routing_key.as_deref(), Some("R0123"));
    }

    #[test]
    fn declared_alert_config_in_ignores_an_unrelated_bad_section() {
        // The exact failure this fallback exists for: a malformed OTHER
        // section must not stop `[alerts]` from being read.
        let dir = tempfile::TempDir::new().expect("temp project dir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[deploy]\nhost = \"deploy.example.test\"\n\n\
             [scheduler]\nbackend = 12345\n\n\
             [alerts]\npagerduty_routing_key = \"R0123\"\n",
        )
        .expect("write autumn.toml");

        let (alerts, _http) = declared_alert_config_in(&[dir.path().to_path_buf()], "prod")
            .expect("a bad [scheduler] value must not break the [alerts] read");

        assert_eq!(alerts.pagerduty_routing_key.as_deref(), Some("R0123"));
    }

    #[test]
    fn declared_alert_config_in_fails_closed_on_an_unreadable_profile_override() {
        // Review finding on #2267: a malformed `autumn-prod.toml` must fail
        // this whole read, not be silently skipped in favor of the
        // base/inline config -- that could page using a destination the
        // profile override was meant to change or disable.
        let dir = tempfile::TempDir::new().expect("temp project dir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[deploy]\nhost = \"deploy.example.test\"\n\n\
             [alerts]\npagerduty_routing_key = \"base-key\"\n",
        )
        .expect("write autumn.toml");
        std::fs::write(dir.path().join("autumn-prod.toml"), "not valid toml")
            .expect("write autumn-prod.toml");

        assert!(
            declared_alert_config_in(&[dir.path().to_path_buf()], "prod").is_none(),
            "a malformed profile override file must fail closed, not fall back to base config"
        );
    }

    #[test]
    fn declared_alert_config_in_fails_closed_on_an_unknown_alerts_key() {
        // Review finding on #2267: `strict_config` would hard-fail
        // `load_runtime_config` on a typo'd `[alerts]` key (`enabeld` for
        // `enabled`), landing here. Plain deserialize would silently drop
        // it and default the switch back to `true` -- exactly the
        // operator's mistyped attempt to turn it off.
        let dir = tempfile::TempDir::new().expect("temp project dir");
        std::fs::write(
            dir.path().join("autumn.toml"),
            "[deploy]\nhost = \"deploy.example.test\"\n\n\
             [alerts]\nenabeld = false\npagerduty_routing_key = \"R0123\"\n",
        )
        .expect("write autumn.toml");

        assert!(
            declared_alert_config_in(&[dir.path().to_path_buf()], "prod").is_none(),
            "a typo'd [alerts] key must fail closed, not silently default enabled back to true"
        );
    }

    #[test]
    fn apply_alert_env_overrides_reads_autumn_alerts_env_vars() {
        // Review finding on #2267: a destination set ONLY via env var (the
        // documented, recommended way to supply a secret) must still fire
        // on the TOML-only degraded-status fallback.
        use autumn_web::config::MockEnv;
        let alerts = autumn_web::alerts::AlertConfig::default();
        let http = autumn_web::config::HttpConfig::default();
        let env = MockEnv::new().with("AUTUMN_ALERTS__PAGERDUTY_ROUTING_KEY", "R9999");

        let (alerts, _http) = apply_alert_env_overrides(alerts, http, &env);

        assert_eq!(alerts.pagerduty_routing_key.as_deref(), Some("R9999"));
    }

    #[test]
    fn apply_alert_env_overrides_can_disable_a_toml_configured_destination() {
        // The other half of the same finding: AUTUMN_ALERTS__ENABLED=false
        // must still silence a destination the TOML-only read already found.
        use autumn_web::config::MockEnv;
        let alerts = autumn_web::alerts::AlertConfig {
            pagerduty_routing_key: Some("R0123".to_owned()),
            ..Default::default()
        };
        let http = autumn_web::config::HttpConfig::default();
        let env = MockEnv::new().with("AUTUMN_ALERTS__ENABLED", "false");

        let (alerts, _http) = apply_alert_env_overrides(alerts, http, &env);

        assert!(!alerts.is_active());
    }

    #[test]
    fn build_fleet_halted_alert_is_scheduled_task_failure() {
        let alert = build_fleet_halted_alert(&sample_halt(), "myapp", "production");
        assert_eq!(alert.condition, AlertCondition::ScheduledTaskFailure);
        assert_eq!(alert.title, "Fleet rollout halted");
        assert_eq!(
            alert.dedup_key,
            "scheduled_task_failure:deploy-fleet-halted:myapp:production"
        );
        assert!(
            alert.summary.contains("web-b") && alert.summary.contains("migrate"),
            "the alert must name the failing host and step: {}",
            alert.summary
        );
        assert_eq!(
            alert.where_to_look, "autumn deploy status",
            "review finding on #2267: must not point at the /actuator/tasks default"
        );
    }

    #[test]
    fn build_fleet_halted_alert_is_scoped_to_profile_for_dedup() {
        // Review finding on #2267: a halt on staging and a halt on
        // production must never merge into one incident, even sharing one
        // PagerDuty routing key.
        let staging = build_fleet_halted_alert(&sample_halt(), "myapp", "staging");
        let production = build_fleet_halted_alert(&sample_halt(), "myapp", "production");

        assert_ne!(staging.dedup_key, production.dedup_key);
    }

    #[test]
    fn build_fleet_halted_alert_is_scoped_to_app_name_for_dedup() {
        // Review finding on #2267: two different apps sharing one alert
        // destination must never fold their `prod` halts into one incident.
        let app_one = build_fleet_halted_alert(&sample_halt(), "app-one", "production");
        let app_two = build_fleet_halted_alert(&sample_halt(), "app-two", "production");

        assert_ne!(app_one.dedup_key, app_two.dedup_key);
    }

    #[test]
    fn build_fleet_halted_alert_carries_only_host_names_and_static_labels() {
        // This check matches `FleetHalted`'s own secrets check. This
        // alert comes only from its fields, so it can carry no more.
        let alert = build_fleet_halted_alert(&sample_halt(), "myapp", "production");
        let rendered = format!("{alert:?}");
        for secret in [
            "postgres://",
            "topsecret",
            "AUTUMN_SECURITY__SIGNING_SECRET",
            "systemd-run",
        ] {
            assert!(
                !rendered.contains(secret),
                "a fleet-halted alert must never carry `{secret}`: {rendered}"
            );
        }
    }

    #[test]
    fn deliver_fleet_halted_alert_reaches_configured_channel() {
        let capture = Arc::new(std::sync::Mutex::new(Vec::new()));
        let channel = Arc::new(CapturingChannel {
            received: Arc::clone(&capture),
        });
        let channels: Vec<Arc<dyn AlertChannel>> = vec![channel];

        deliver_alert(
            &channels,
            &build_fleet_halted_alert(&sample_halt(), "myapp", "production"),
        );

        let delivered = capture.lock().expect("lock").clone();
        assert_eq!(delivered.len(), 1, "exactly one alert must be delivered");
        assert_eq!(delivered[0].condition, AlertCondition::ScheduledTaskFailure);
    }

    #[test]
    fn deliver_alert_is_noop_without_channels() {
        // No `[alerts]` set means no channels. This must not panic. It
        // must deliver nothing and change no behavior.
        deliver_alert(
            &[],
            &build_fleet_halted_alert(&sample_halt(), "myapp", "production"),
        );
    }

    #[test]
    fn build_drift_alert_is_scheduled_task_failure_scoped_to_profile() {
        let report = fleet::DriftReport {
            releases: vec![
                ("web-a".to_owned(), fleet::ReleaseId::Known("r1".to_owned())),
                ("web-b".to_owned(), fleet::ReleaseId::Known("r2".to_owned())),
            ],
            version_drift: true,
            state_drift: vec![("web-b".to_owned(), fleet::DRIFT_HOST_NOT_DEPLOYED)],
        };

        let alert = build_drift_alert(&report, "myapp", "production");

        assert_eq!(alert.condition, AlertCondition::ScheduledTaskFailure);
        assert_eq!(alert.title, "Fleet drift detected");
        assert_eq!(
            alert.dedup_key,
            "scheduled_task_failure:deploy-drift:myapp:production"
        );
        assert!(
            alert.summary.contains("release"),
            "version drift must be named in the summary: {}",
            alert.summary
        );
        assert_eq!(
            alert.where_to_look, "autumn deploy status",
            "review finding on #2267: must not point at the /actuator/tasks default"
        );
    }

    #[test]
    fn build_drift_alert_is_scoped_to_profile_for_dedup() {
        // Drift on staging and drift on production must stay two alerts.
        let report = fleet::DriftReport {
            releases: vec![],
            version_drift: false,
            state_drift: vec![("web-a".to_owned(), fleet::DRIFT_LIVE_SLOT_MARKER)],
        };

        let staging = build_drift_alert(&report, "myapp", "staging");
        let production = build_drift_alert(&report, "myapp", "production");

        assert_ne!(staging.dedup_key, production.dedup_key);
    }

    #[test]
    fn build_drift_alert_is_scoped_to_app_name_for_dedup() {
        // Review finding on #2267: two different apps sharing one alert
        // destination must never fold their `prod` drift into one incident.
        let report = fleet::DriftReport {
            releases: vec![],
            version_drift: false,
            state_drift: vec![("web-a".to_owned(), fleet::DRIFT_LIVE_SLOT_MARKER)],
        };

        let app_one = build_drift_alert(&report, "app-one", "production");
        let app_two = build_drift_alert(&report, "app-two", "production");

        assert_ne!(app_one.dedup_key, app_two.dedup_key);
    }

    #[test]
    fn deliver_drift_alert_reaches_configured_channel() {
        let capture = Arc::new(std::sync::Mutex::new(Vec::new()));
        let channel = Arc::new(CapturingChannel {
            received: Arc::clone(&capture),
        });
        let channels: Vec<Arc<dyn AlertChannel>> = vec![channel];
        let report = fleet::DriftReport {
            releases: vec![],
            version_drift: false,
            state_drift: vec![("web-a".to_owned(), fleet::DRIFT_LIVE_SLOT_MARKER)],
        };

        deliver_alert(&channels, &build_drift_alert(&report, "myapp", "staging"));

        let delivered = capture.lock().expect("lock").clone();
        assert_eq!(delivered.len(), 1);
        assert_eq!(
            delivered[0].dedup_key,
            "scheduled_task_failure:deploy-drift:myapp:staging"
        );
    }

    #[test]
    fn fleet_of_one_matches_todays_single_host_sequence() {
        // #1621 (AC-1, T1.6 / plan P1). The hard invariant: a one-host fleet runs
        // the SAME ops, in the same order, with the same rendered shell, as the
        // pre-fleet single-host path — proven differentially against the unchanged
        // per-host builders, not against a remembered vector.
        let fleet = fleet_of(&["203.0.113.10"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "203.0.113.10");
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect("a scripted one-host fleet deploys cleanly");

        // (a) the exact protected label vector, behind the read-only prologue.
        let expected_labels: Vec<&'static str> = READ_ONLY_PROBES
            .iter()
            .copied()
            .chain(REDEPLOY_RUN_LABELS)
            .collect();
        assert_eq!(
            recorder.run_labels_for("203.0.113.10"),
            expected_labels,
            "a one-host fleet must run today's exact zero-downtime sequence"
        );

        // (b) and byte-for-byte the same calls (shells, upload paths, modes) as the
        // single-host builders produce — the differential form of AC-1.
        let observed = recorder.calls_for("203.0.113.10");
        let (probes, mutating) = observed.split_at(READ_ONLY_PROBES.len());
        assert_eq!(
            probes
                .iter()
                .filter_map(exec::test_support::RecordedCall::run_label)
                .collect::<Vec<_>>(),
            READ_ONLY_PROBES.to_vec(),
            "the rollout prologue must be read-only probes only"
        );
        assert_eq!(
            mutating,
            fixture
                .todays_calls(
                    &fleet.hosts[0],
                    fleet::HostMode::Redeploy,
                    exec::MigrateStep::Run
                )
                .as_slice(),
            "a one-host fleet's ops must be byte-identical to today's single-host ops"
        );
    }

    #[test]
    fn fleet_of_one_first_deploy_matches_todays_single_host_sequence() {
        // #1621 (AC-1, T1.6): the same differential proof on the first-deploy path.
        // Since #1607 (AC-3) that path carries the migrate op too, so a one-entry
        // `hosts` list is byte-identical to the single-host first deploy INCLUDING
        // its pre-start migration.
        let fleet = fleet_of(&["203.0.113.10"]);
        let recorder = fleet::test_support::FleetRecorder::new()
            .script(
                "203.0.113.10",
                "proxy-compat-probe",
                compatible_deploy_help(),
            )
            .script("203.0.113.10", "detect-current", first_deploy_probe())
            .script("203.0.113.10", "probe-release-dir", "absent");
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect("a scripted one-host first deploy runs cleanly");

        let observed = recorder.calls_for("203.0.113.10");
        let (_, mutating) = observed.split_at(READ_ONLY_PROBES.len());
        assert_eq!(
            mutating,
            fixture
                .todays_calls(
                    &fleet.hosts[0],
                    fleet::HostMode::First,
                    exec::MigrateStep::Run
                )
                .as_slice(),
            "a one-host first deploy must be byte-identical to today's single-host first deploy"
        );
        assert!(
            recorder.run_labels_for("203.0.113.10").contains(&"migrate"),
            "the first-deploy path migrates before the release takes traffic (#1607)"
        );
    }

    #[test]
    fn rolling_order_replaces_hosts_strictly_in_sequence() {
        // #1621 (AC-2, T1.11). The whole safety claim of a rolling deploy is an
        // ORDERING claim: host k+1 is not touched until host k has cut over, so the
        // rest of the fleet keeps serving throughout. Asserted on the fleet-wide
        // tape, which is the only structure that can express it.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect("a scripted three-host fleet rolls out cleanly");

        // (a) each host runs its OWN complete redeploy vector; only the first
        // carries the fleet's single migration.
        for (index, host) in hosts.iter().enumerate() {
            let expected: Vec<&'static str> = READ_ONLY_PROBES
                .iter()
                .copied()
                .chain(
                    REDEPLOY_RUN_LABELS
                        .iter()
                        .copied()
                        .filter(|l| index == 0 || *l != "migrate"),
                )
                .collect();
            assert_eq!(
                recorder.run_labels_for(host),
                expected,
                "{host} must run the full per-host sequence ({}the migration)",
                if index == 0 { "with " } else { "without " }
            );
        }

        // (b) strict sequencing: host k+1's first MUTATING op comes after host k's
        // proxy-flip. (Read-only probes all run up front, before any host is
        // touched — that is the all-hosts preflight probe, not a mutation.)
        for pair in hosts.windows(2) {
            let (previous, next) = (pair[0], pair[1]);
            let flip = recorder
                .index_of(previous, "proxy-flip")
                .unwrap_or_else(|| panic!("{previous} must cut over"));
            let first_mutation = recorder
                .first_mutating(next, &READ_ONLY_PROBES)
                .unwrap_or_else(|| panic!("{next} must be deployed"));
            assert!(
                flip < first_mutation,
                "{next} must not be touched until {previous} has cut over: \
                 {previous}'s proxy-flip at {flip}, {next}'s first mutation at {first_mutation}"
            );
        }
    }

    #[test]
    fn unreadable_marker_on_any_host_aborts_before_any_mutation() {
        // #1621 (AC-7, T1.17). Every per-host fail-closed refusal is evaluated for
        // ALL hosts BEFORE the first host is touched. Host 3's `shared/proxy-options`
        // marker is present but unparseable (#2074), so the whole rollout is
        // refused — with hosts 1 and 2 untouched, still serving their old releases.
        let fleet = fleet_of(&["web-a", "web-b", "web-c"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in ["web-a", "web-b"] {
            recorder = script_redeploy(recorder, host);
        }
        recorder = recorder
            .script("web-c", "proxy-compat-probe", compatible_deploy_help())
            .script("web-c", "detect-current", unreadable_proxy_options_probe())
            .script("web-c", "probe-release-dir", "absent");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("an unprovable proxy-options marker must refuse the rollout");
        let message = err.to_string();
        assert!(
            message.contains("web-c"),
            "the refusal must name the offending HOST, got: {message}"
        );
        assert!(
            message.contains("proxy-options") && message.contains("#2074"),
            "the refusal must keep the single-host #2074 message, got: {message}"
        );

        let mutating = recorder.mutating(&READ_ONLY_PROBES);
        assert!(
            mutating.is_empty(),
            "a refused rollout must mutate NOTHING anywhere in the fleet, got: {mutating:?}"
        );
    }

    #[test]
    fn existing_release_dir_on_any_host_refuses_the_rollout() {
        // #1621 (AC-3, T1.19). The release id has one-second granularity, so a fast
        // retry can reuse it. Re-uploading into a dir `shared/previous-release`
        // still points at would make the "previous release" hold the NEW binary and
        // roll FORWARD. Refuse before touching anything, naming the host.
        let fleet = fleet_of(&["web-a", "web-b", "web-c"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in ["web-a", "web-c"] {
            recorder = script_redeploy(recorder, host);
        }
        recorder = recorder
            .script("web-b", "proxy-compat-probe", compatible_deploy_help())
            .script("web-b", "detect-current", redeploy_probe())
            .script("web-b", "probe-release-dir", "present");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("an existing release dir must refuse the rollout");
        let message = err.to_string();
        assert!(
            message.contains("web-b") && message.contains(FLEET_RELEASE_ID),
            "the refusal must name the host and the colliding release, got: {message}"
        );

        let mutating = recorder.mutating(&READ_ONLY_PROBES);
        assert!(
            mutating.is_empty(),
            "a refused rollout must mutate NOTHING anywhere in the fleet, got: {mutating:?}"
        );
    }

    #[test]
    fn a_failed_host_halts_the_rollout_and_leaves_later_hosts_untouched() {
        // #1621 (AC-3). Host 2's readiness gate fails, a pre-boundary failure, so its
        // candidate is torn down by the per-host auto-rollback and its old release keeps
        // serving. The rollout then halts: host 3 is never touched. Host 1 is left on
        // the new release and named, so the operator can reverse it.
        //
        // Slice 4 pins this against the halt-and-freeze seam (`auto_rollback: false`,
        // the internal form of `--no-rollback`): freezing is exactly the "stop and let
        // me look" behaviour, so it must keep reporting partial state truthfully. The
        // default path, which compensates web-a instead of leaving it forward, is
        // `a_pre_boundary_failure_rolls_the_already_cut_over_hosts_back`.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        recorder = recorder.fail("web-b", "readiness-gate");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input_frozen(&fleet), |cfg| {
            Ok(recorder.executor(cfg))
        })
        .expect_err("a mid-rollout failure must halt the rollout");

        let halt = fleet_halt_of(&err);
        assert!(
            halt.degraded.is_empty() && halt.manual.is_empty(),
            "a clean pre-boundary halt needs no degraded/manual rows: {:?} / {:?}",
            halt.degraded,
            halt.manual
        );
        assert_eq!(
            halt.failed_host, "web-b",
            "the halt must name the failing host"
        );
        assert_eq!(
            halt.failed_step, "readiness-gate",
            "the halt must name the failing step"
        );
        assert_eq!(
            halt.rolled_back,
            vec!["web-b".to_owned()],
            "a pre-boundary failure rolls the failing host's candidate back"
        );
        assert!(
            halt.torn_down.is_empty(),
            "a redeploy host is rolled back, not torn down: {:?}",
            halt.torn_down
        );
        assert_eq!(
            halt.still_on_new,
            vec!["web-a".to_owned()],
            "the already-cut-over hosts must be named so they can be compensated"
        );

        // Host 1 completed its cutover.
        assert!(
            recorder.run_labels_for("web-a").contains(&"prune"),
            "web-a must have completed its cutover"
        );
        // Host 2 stopped at the readiness gate and tore its candidate down.
        let web_b = recorder.run_labels_for("web-b");
        assert!(
            web_b.contains(&"readiness-gate")
                && !web_b.contains(&"proxy-flip")
                && web_b.contains(&"teardown-candidate-unit")
                && web_b.contains(&"teardown-candidate-dir"),
            "web-b must fail at the gate, never flip, and tear its candidate down: {web_b:?}"
        );
        // Host 3 was probed in the all-hosts prologue and then never touched.
        let web_c: Vec<_> = recorder
            .mutating(&READ_ONLY_PROBES)
            .into_iter()
            .filter(|(host, _)| host == "web-c")
            .collect();
        assert!(
            web_c.is_empty(),
            "the rollout must halt: web-c must be mutated in no way, got: {web_c:?}"
        );
    }

    // ── Fleet compensation (issue #1621, slice 4, §4.6-4.7) ──────────────────

    #[test]
    fn a_pre_boundary_failure_rolls_the_already_cut_over_hosts_back() {
        // #1621 (AC-3, T1.13 case a). Host 2's readiness gate fails BEFORE its flip,
        // so its own auto-rollback tears the candidate down and its old release
        // keeps serving — but host 1 has already cut over. Left alone, the fleet
        // runs two versions at rest, which is the exact failure AC-3 forbids. So the
        // rollout compensates host 1 with the UNCHANGED on-demand rollback
        // primitives, and host 3 — never reached — stays untouched.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        recorder =
            script_compensation(recorder, "web-a", "present").fail("web-b", "readiness-gate");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a mid-rollout failure must halt the rollout");

        // Host 1 ran its full cutover and then the full rollback sequence — the same
        // ops `autumn deploy rollback` runs, in the same order, nothing invented.
        assert_eq!(
            recorder.run_labels_for("web-a"),
            redeploy_then_compensated(true),
            "web-a must be rolled back with the on-demand rollback primitives"
        );
        assert!(
            recorder
                .mutating(&READ_ONLY_PROBES)
                .iter()
                .all(|(host, _)| host != "web-c"),
            "web-c was never reached, so compensation must not touch it either"
        );

        let halt = fleet_halt_of(&err);
        assert_eq!(
            halt.rolled_back,
            vec!["web-a".to_owned(), "web-b".to_owned()],
            "both the compensated host and the self-torn-down host are back on their \
             previous release"
        );
        assert!(
            halt.still_on_new.is_empty() && halt.torn_down.is_empty() && halt.manual.is_empty(),
            "the fleet converged: nothing left forward, nothing manual — got {:?} / {:?} / {:?}",
            halt.still_on_new,
            halt.torn_down,
            halt.manual
        );
    }

    #[test]
    fn a_post_boundary_functional_failure_compensates_newest_first_including_itself() {
        // #1621 (AC-3, T1.13 case b). Host 2's ssh transport drops during `drain-old`
        // — AFTER its flip, so traffic already moved and no teardown ran. That host
        // IS on the new release, so the compensation set includes it, and the order
        // is strictly newest-cutover-first: undoing from the newest end shrinks the
        // mixed window instead of widening it.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        recorder = script_compensation(recorder, "web-a", "present");
        recorder =
            script_compensation(recorder, "web-b", "present").transport_fail("web-b", "drain-old");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a post-boundary failure must halt the rollout");

        // Reverse order, asserted on the fleet-wide tape: `restart-previous` belongs
        // only to `rollback_ops`, so it is the unambiguous marker of each host's
        // compensation.
        let web_b = recorder
            .index_of("web-b", "restart-previous")
            .expect("web-b must be compensated — it is live on the new release");
        let web_a = recorder
            .index_of("web-a", "restart-previous")
            .expect("web-a must be compensated");
        assert!(
            web_b < web_a,
            "compensation must run in REVERSE rollout order: web-b's rollback at \
             {web_b}, web-a's at {web_a}"
        );
        assert!(
            recorder.index_of("web-c", "restart-previous").is_none(),
            "web-c never cut over, so it must not be rolled back"
        );

        let halt = fleet_halt_of(&err);
        assert_eq!(halt.failed_host, "web-b");
        assert_eq!(
            halt.failed_step, "ssh-transport",
            "a dropped transport attributes to the transport, never to a fabricated \
             step label"
        );
        assert_eq!(
            halt.rolled_back,
            vec!["web-a".to_owned(), "web-b".to_owned()],
            "the post-boundary host is compensated TOO — it is on the new release"
        );
        assert!(
            halt.still_on_new.is_empty(),
            "the fleet must converge on one version: {:?}",
            halt.still_on_new
        );
    }

    #[test]
    fn a_completed_first_deploy_is_compensated_by_teardown_not_rollback() {
        // #1621 (AC-3, T1.13 case c). A first-deploy host has no
        // `shared/previous-release` marker, so there is nothing to roll back TO:
        // `resolve_rollback_target` would fail. Its honest compensation is the
        // first-deploy teardown, which returns it to nothing-installed — the state
        // that makes the next `deploy up` correctly take the First path again. A
        // half-installed host an LB may already be probing is worse than a clean
        // absence.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_first_deploy(recorder, "web-a");
        recorder = script_redeploy(recorder, "web-b").fail("web-b", "readiness-gate");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a mid-rollout failure must halt the rollout");

        let web_a = recorder.run_labels_for("web-a");
        for teardown in [
            "teardown-candidate-unit",
            "teardown-candidate-dir",
            "teardown-current-symlink",
            "teardown-slot-markers",
            // Issue #2270: the proxy route must go too, or the public port keeps
            // answering 502 with nothing live behind it.
            "proxy-deregister",
        ] {
            assert!(
                web_a.contains(&teardown),
                "a compensated first deploy must run `{teardown}`: {web_a:?}"
            );
        }
        assert!(
            !web_a.contains(&"resolve-previous") && !web_a.contains(&"restart-previous"),
            "a first-deploy host has no previous release, so it must never be sent \
             through the rollback primitives: {web_a:?}"
        );

        let halt = fleet_halt_of(&err);
        assert_eq!(
            halt.torn_down,
            vec!["web-a".to_owned()],
            "the compensated first deploy is reported as torn down, not rolled back"
        );
        assert_eq!(
            halt.rolled_back,
            vec!["web-b".to_owned()],
            "the failing redeploy host's own candidate teardown still stands"
        );
        assert!(
            halt.still_on_new.is_empty(),
            "nothing may be left on the new release"
        );
    }

    #[test]
    fn a_completed_first_deploy_compensation_removes_the_proxy_route() {
        // Issue #2270: a completed first deploy that the fleet compensates has a
        // LIVE proxy route (unlike the pre-go-live path, which never reaches
        // `proxy-route`). The compensating teardown must remove it, socket-pinned
        // like every other kamal-proxy invocation — as its OWN step, AFTER the
        // app teardown (including the advisory `teardown-last-deploy` write) has
        // fully succeeded, so a transport failure on the route step alone can
        // never be confused with one on an earlier, not-yet-attempted step.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_first_deploy(recorder, "web-a");
        recorder = script_redeploy(recorder, "web-b").fail("web-b", "readiness-gate");
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a mid-rollout failure must halt the rollout");

        let calls = recorder.calls_for("web-a");
        let labels: Vec<&str> = calls
            .iter()
            .filter_map(|call| match call {
                exec::test_support::RecordedCall::Run { label, .. } => Some(*label),
                exec::test_support::RecordedCall::Upload { .. } => None,
            })
            .collect();
        let deregister_at = labels
            .iter()
            .position(|l| *l == "proxy-deregister")
            .expect("the compensated first deploy must deregister the proxy route");
        let last_deploy_at = labels
            .iter()
            .position(|l| *l == "teardown-last-deploy")
            .expect("the teardown must still record its result");
        assert!(
            last_deploy_at < deregister_at,
            "the app teardown, marker write included, must fully finish BEFORE the \
             separate route-removal step starts: {labels:?}"
        );

        let shell = calls
            .iter()
            .find_map(|call| match call {
                exec::test_support::RecordedCall::Run { label, shell }
                    if *label == "proxy-deregister" =>
                {
                    Some(shell.as_str())
                }
                _ => None,
            })
            .expect("proxy-deregister ran");
        assert_eq!(shell, "env -u XDG_RUNTIME_DIR kamal-proxy remove 'myapp'");
    }

    #[test]
    fn a_failed_deregister_reports_its_own_outcome_not_a_generic_compensation_failure() {
        // Issue #2270: when the proxy-deregister op itself fails, every op before
        // it in `first_deploy_teardown_ops` already ran — the app is genuinely
        // gone, only the route is stuck. This must NOT read as
        // `CompensationFailed` ("still serving, roll it back"): that is both
        // untrue (nothing is serving) and impossible (a first deploy has no
        // previous release `autumn deploy rollback` could target).
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_first_deploy(recorder, "web-a").fail("web-a", "proxy-deregister");
        recorder = script_redeploy(recorder, "web-b").fail("web-b", "readiness-gate");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a mid-rollout failure must halt the rollout");

        let halt = fleet_halt_of(&err);
        assert_eq!(
            halt.torn_down,
            vec!["web-a".to_owned()],
            "the app is gone, so this host is torn down, not still forward"
        );
        assert!(
            !halt.still_on_new.contains(&"web-a".to_owned()),
            "a failed deregister must never be told to `rollback` a host with \
             nothing installed: {:?}",
            halt.still_on_new
        );
        assert!(
            !halt.manual.iter().any(|(host, _)| host == "web-a"),
            "this is not a declined-automatically case: {:?}",
            halt.manual
        );
        // Codex review: this must be named in its OWN field too, not just the
        // console table, so an alert built from `FleetHalt` can tell a clean
        // compensation apart from one whose route may still 502.
        assert_eq!(
            halt.route_removal_failed,
            vec![("web-a".to_owned(), "proxy-deregister")],
            "the route-removal failure must be preserved in a dedicated field: {:?}",
            halt.route_removal_failed
        );

        // The marker write is part of the (separate, already-run) app-teardown
        // call, so it lands regardless of the later deregister failure — no
        // special-casing needed here, unlike the earlier design this replaced.
        let calls = recorder.calls_for("web-a");
        let last_deploy_writes: Vec<&str> = calls
            .iter()
            .filter_map(|call| match call {
                exec::test_support::RecordedCall::Run { label, shell }
                    if *label == "teardown-last-deploy" =>
                {
                    Some(shell.as_str())
                }
                _ => None,
            })
            .collect();
        let last = *last_deploy_writes
            .last()
            .expect("the marker must still be recorded despite the deregister failure");
        assert!(
            last.contains("'torn down'") && !last.contains("'deployed'"),
            "a fully torn-down host must not report a successful deploy: {last}"
        );
    }

    #[test]
    fn a_dropped_transport_on_deregister_still_reads_as_torn_down() {
        // Issue #2270 (Codex review): a transport failure (the local `ssh`
        // launch itself dying) carries NO op label — `failed_step_label` always
        // reports it as `"ssh-transport"`, never `"proxy-deregister"`. Splitting
        // the route removal into its OWN call (rather than string-matching a
        // label inside one shared op list) means this still can only mean "the
        // app teardown already succeeded and the separate route call failed",
        // whatever shape that failure takes.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder =
            script_first_deploy(recorder, "web-a").transport_fail("web-a", "proxy-deregister");
        recorder = script_redeploy(recorder, "web-b").fail("web-b", "readiness-gate");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a mid-rollout failure must halt the rollout");

        let halt = fleet_halt_of(&err);
        assert_eq!(
            halt.torn_down,
            vec!["web-a".to_owned()],
            "a dropped transport on the route step alone must not read as still forward"
        );
        assert!(
            !halt.still_on_new.contains(&"web-a".to_owned()),
            "must never suggest `rollback` a host with nothing installed: {:?}",
            halt.still_on_new
        );
    }

    #[test]
    fn a_compensated_first_deploy_stops_reporting_a_successful_last_deploy() {
        // #1621 (AC-6, audit gap G3). `CompensatedTeardown` returns web-a to
        // nothing-installed, but its first deploy had already written
        // `shared/last-deploy = deployed <ts>` via `record-proxy-options`. Left alone,
        // `deploy status` would show `last deploy: deployed <ts>` for a host carrying no
        // release at all — the worst possible moment for a wrong value, since the
        // operator is inspecting the fleet precisely because the rollout halted. The
        // teardown's last op rewrites the marker to `torn down`, so the column reports
        // what actually happened.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_first_deploy(recorder, "web-a");
        recorder = script_redeploy(recorder, "web-b").fail("web-b", "readiness-gate");
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a mid-rollout failure must halt the rollout");

        let calls = recorder.calls_for("web-a");
        let last_deploy_writes: Vec<(&'static str, &str)> = calls
            .iter()
            .filter_map(|call| match call {
                exec::test_support::RecordedCall::Run { label, shell }
                    if shell.contains("shared/last-deploy") =>
                {
                    Some((*label, shell.as_str()))
                }
                _ => None,
            })
            .collect();

        let (last_label, last_shell) = *last_deploy_writes
            .last()
            .expect("the compensated host writes the last-deploy marker at least once");
        assert_eq!(
            last_label, "teardown-last-deploy",
            "the TEARDOWN must have the last word on this host's last-deploy marker, \
             got: {last_deploy_writes:?}"
        );
        assert!(
            last_shell.contains("'torn down'") && !last_shell.contains("'deployed'"),
            "a torn-down host must not report a successful deploy: {last_shell}"
        );
        // Non-vacuous: the first deploy really did claim `deployed` before the
        // compensation ran, so this is a correction, not an absence.
        assert!(
            last_deploy_writes
                .iter()
                .any(|(label, shell)| *label == "record-proxy-options"
                    && shell.contains("'deployed'")),
            "the first deploy must have recorded `deployed` first: {last_deploy_writes:?}"
        );
    }

    #[test]
    fn a_failed_compensation_does_not_stop_the_earlier_hosts() {
        // #1621 (AC-3, T1.13 case d). Host 3 fails post-boundary; compensation runs
        // c → b → a and host 2's rollback fails at `restart-previous`. Stopping there
        // would leave MORE hosts on the new release — a BIGGER mixed fleet — so the
        // driver continues to host 1 and reports host 2 honestly. This is the one
        // place the repo's `let _ = run_one(..)` teardown idiom must NOT be reused:
        // a swallowed compensation failure is how a fleet silently stays mixed.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        recorder = script_compensation(recorder, "web-a", "present");
        recorder =
            script_compensation(recorder, "web-b", "present").fail("web-b", "restart-previous");
        recorder =
            script_compensation(recorder, "web-c", "present").transport_fail("web-c", "drain-old");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a post-boundary failure must halt the rollout");

        // Host 2's rollback failed at or before the flip, so its restarted slot was
        // disabled again and it is still serving the NEW release.
        let web_b = recorder.run_labels_for("web-b");
        assert!(
            web_b.contains(&"restart-previous")
                && !web_b
                    .iter()
                    .skip_while(|l| **l != "restart-previous")
                    .any(|l| *l == "commit-markers")
                && web_b.contains(&"teardown-rollback-slot"),
            "web-b's rollback must fail before its flip and disable the slot it \
             restarted: {web_b:?}"
        );
        // …and host 1 is still compensated afterwards.
        let web_a = recorder
            .index_of("web-a", "restart-previous")
            .expect("web-a must still be compensated after web-b's rollback failed");
        let web_b_attempt = recorder
            .index_of("web-b", "restart-previous")
            .expect("web-b's rollback was attempted");
        assert!(
            web_b_attempt < web_a,
            "the failed rollback must not stop the earlier host: web-b at \
             {web_b_attempt}, web-a at {web_a}"
        );

        let halt = fleet_halt_of(&err);
        assert_eq!(
            halt.rolled_back,
            vec!["web-a".to_owned(), "web-c".to_owned()],
            "every host whose compensation SUCCEEDED is reported as rolled back"
        );
        assert_eq!(
            halt.still_on_new,
            vec!["web-b".to_owned()],
            "a host whose compensation failed is still on the new release and must be \
             named as such — reporting the attempt instead of the result is how an \
             operator believes a mixed fleet converged"
        );
    }

    #[test]
    fn a_missing_rollback_target_dir_declines_the_rollback() {
        // #1621 (AC-3, T1.13 case e / §4.7). `prune` runs per host, so hosts with
        // divergent deploy history legitimately retain different release sets: the
        // previous-release marker can name a dir this host no longer has. Flipping
        // at it anyway starts a unit whose ExecStart points nowhere, passes systemd,
        // and fails the readiness gate POST-boundary with no teardown — one broken
        // host becomes two. So the precheck declines, and the host is reported.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in ["web-a", "web-b"] {
            recorder = script_redeploy(recorder, host);
        }
        recorder = script_compensation(recorder, "web-a", "absent").fail("web-b", "readiness-gate");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a mid-rollout failure must halt the rollout");

        let web_a = recorder.run_labels_for("web-a");
        assert!(
            web_a.contains(&"probe-rollback-target"),
            "the precheck must actually run: {web_a:?}"
        );
        assert!(
            !web_a.contains(&"restart-previous") && !web_a.contains(&"drain-rolled-back-slot"),
            "a declined rollback must run NO rollback ops: {web_a:?}"
        );
        assert_eq!(
            web_a.iter().filter(|label| **label == "proxy-flip").count(),
            1,
            "the declined host must keep exactly its cutover flip — zero further \
             flips: {web_a:?}"
        );

        let halt = fleet_halt_of(&err);
        assert_eq!(
            halt.manual,
            vec![("web-a".to_owned(), fleet::MANUAL_ROLLBACK_TARGET_MISSING)],
            "the declined host must be reported with its reason"
        );
        assert_eq!(
            halt.still_on_new,
            vec!["web-a".to_owned()],
            "a host that was NOT rolled back is still on the new release"
        );
        assert_eq!(
            halt.rolled_back,
            vec!["web-b".to_owned()],
            "the failing host's own teardown still stands"
        );
    }

    #[test]
    fn a_commit_markers_failure_is_never_auto_rolled_back() {
        // #1621 (§4.6, T1.15). `commit-markers` writes previous-release + `current` +
        // live-slot as ONE remote transaction. A failure inside it can leave any
        // subset applied, so `resolve_rollback_target` may name the WRONG release —
        // rolling back could move that host FORWARD, or onto a release it never
        // served. Fail closed: halt, do not touch that host, print the by-hand
        // recovery. Earlier hosts are still compensated.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in ["web-a", "web-b"] {
            recorder = script_redeploy(recorder, host);
        }
        recorder =
            script_compensation(recorder, "web-a", "present").fail("web-b", "commit-markers");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("an ambiguous-marker failure must halt the rollout");

        let web_b = recorder.run_labels_for("web-b");
        for rollback_op in [
            "resolve-previous",
            "probe-rollback-target",
            "restart-previous",
            "drain-rolled-back-slot",
        ] {
            assert!(
                !web_b.contains(&rollback_op),
                "an ambiguous-marker host must see ZERO rollback-flavoured ops, got \
                 `{rollback_op}`: {web_b:?}"
            );
        }
        assert_eq!(
            recorder.run_labels_for("web-a"),
            redeploy_then_compensated(true),
            "the earlier host is still compensated"
        );

        let halt = fleet_halt_of(&err);
        assert_eq!(halt.failed_step, "commit-markers");
        assert_eq!(
            halt.manual,
            vec![("web-b".to_owned(), fleet::MANUAL_AMBIGUOUS_MARKERS)],
            "the ambiguous host must be reported as needing a human"
        );
        assert_eq!(
            halt.still_on_new,
            vec!["web-b".to_owned()],
            "it was not rolled back, so it is still on the new release"
        );
        assert_eq!(halt.rolled_back, vec!["web-a".to_owned()]);
    }

    #[test]
    fn a_transport_failure_at_commit_markers_is_never_auto_rolled_back() {
        // #1621 (§4.6, T1.15). The guard above must key on the OP that was running,
        // not on the error shape that carried the failure. `DeployExecError::Spawn`
        // carries no label of its own (`failed_step_label` synthesizes
        // "ssh-transport"), so a dropped transport during `commit-markers` used to
        // classify as Functional and auto-roll-back a host whose marker triple was
        // never written — landing it on whatever `shared/previous-release` still
        // named, which can be a release older than the one every other compensated
        // host returns to, and reporting it as "previous release restored".
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in ["web-a", "web-b"] {
            recorder = script_redeploy(recorder, host);
        }
        recorder = script_compensation(recorder, "web-a", "present")
            .transport_fail("web-b", "commit-markers");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("an ambiguous-marker failure must halt the rollout");

        let web_b = recorder.run_labels_for("web-b");
        for rollback_op in [
            "resolve-previous",
            "probe-rollback-target",
            "restart-previous",
            "drain-rolled-back-slot",
        ] {
            assert!(
                !web_b.contains(&rollback_op),
                "a host whose `commit-markers` failed must see ZERO rollback-flavoured \
                 ops whatever the error shape, got `{rollback_op}`: {web_b:?}"
            );
        }
        assert_eq!(
            recorder.run_labels_for("web-a"),
            redeploy_then_compensated(true),
            "the earlier host is still compensated"
        );

        let halt = fleet_halt_of(&err);
        assert_eq!(
            halt.manual,
            vec![("web-b".to_owned(), fleet::MANUAL_AMBIGUOUS_MARKERS)],
            "the host with an unprovable marker triple must be reported as needing a human"
        );
        assert_eq!(
            halt.still_on_new,
            vec!["web-b".to_owned()],
            "it was not rolled back, so it is still on the new release"
        );
        assert_eq!(halt.rolled_back, vec!["web-a".to_owned()]);
    }

    #[test]
    fn a_housekeeping_failure_degrades_the_host_and_continues_the_rollout() {
        // #1621 (§4.6, T1.15). `prune` runs AFTER the flip: the proxy is already
        // serving the new release, so a failed `rm -rf` of old release dirs affects
        // no traffic at all. Rolling three hosts back over it would be a
        // self-inflicted outage. The rollout warns, marks the host degraded, and
        // CONTINUES — and the deploy SUCCEEDS, because every host really is serving
        // the new release.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        recorder = recorder.fail("web-b", "prune");
        let fixture = FleetFixture::new();

        run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect("a post-cutover housekeeping failure must not fail the rollout");

        assert_eq!(
            recorder.run_labels_for("web-c"),
            READ_ONLY_PROBES
                .iter()
                .copied()
                .chain(
                    REDEPLOY_RUN_LABELS
                        .iter()
                        .copied()
                        .filter(|label| *label != "migrate")
                )
                .collect::<Vec<_>>(),
            "the rollout must CONTINUE past a degraded host"
        );
        let web_b = recorder.run_labels_for("web-b");
        assert!(
            web_b.contains(&"prune")
                && !web_b.contains(&"teardown-candidate-unit")
                && !web_b.contains(&"restart-previous"),
            "a degraded host is live and healthy: nothing may be torn down or rolled \
             back on it: {web_b:?}"
        );
        assert!(
            recorder.positions_of("resolve-previous").is_empty(),
            "a rollout that only degraded must compensate NOTHING anywhere"
        );
    }

    /// How the `drain-old-retry` probe on `web-b` answers in the #2279 tests.
    enum DrainRetry {
        Stdout(&'static str),
        CommandFails,
        TransportFails,
    }

    /// A three-host rollout where `web-b`'s `drain-old` fails and its retry
    /// answers `retry`. Every host can be compensated, unless `frozen`.
    fn drain_old_failure_run(
        retry: &DrainRetry,
        frozen: bool,
    ) -> (fleet::test_support::FleetRecorder, Result<(), DeployError>) {
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_compensation(script_redeploy(recorder, host), host, "present");
        }
        recorder = recorder.fail("web-b", "drain-old");
        recorder = match retry {
            DrainRetry::Stdout(stdout) => recorder.script("web-b", "drain-old-retry", *stdout),
            DrainRetry::CommandFails => recorder.fail("web-b", "drain-old-retry"),
            DrainRetry::TransportFails => recorder.transport_fail("web-b", "drain-old-retry"),
        };
        let fixture = FleetFixture::new();
        let input = if frozen {
            fixture.input_frozen(&fleet)
        } else {
            fixture.input(&fleet)
        };
        let result = run_up_with(&input, |cfg| Ok(recorder.executor(cfg)));
        (recorder, result)
    }

    /// Check that `web-b` ran exactly one retry, right after the failed
    /// `drain-old`, against the same unit.
    fn assert_one_retry_of_the_drained_unit(recorder: &fleet::test_support::FleetRecorder) {
        let web_b = recorder.run_labels_for("web-b");
        assert_eq!(
            web_b.iter().filter(|l| **l == "drain-old-retry").count(),
            1,
            "retry one time only: {web_b:?}"
        );
        assert!(
            web_b
                .windows(2)
                .any(|w| w == ["drain-old", "drain-old-retry"]),
            "the retry runs right after the failed drain: {web_b:?}"
        );
        let shell_of = |label: &str| {
            recorder
                .calls_for("web-b")
                .into_iter()
                .find_map(|call| match call {
                    exec::test_support::RecordedCall::Run { label: l, shell } if l == label => {
                        Some(shell)
                    }
                    _ => None,
                })
                .expect("the op ran")
        };
        let drained = shell_of("drain-old");
        let unit = drained.rsplit(' ').next().expect("drain-old names a unit");
        assert!(
            shell_of("drain-old-retry").contains(&format!("unit='{unit}'")),
            "the retry must target the old slot `{unit}`, never the new one"
        );
    }

    #[test]
    fn a_drain_old_failure_whose_old_slot_may_still_run_halts_the_rollout() {
        // #2279: the old slot runs job workers and the scheduler. If it can run,
        // scheduled tasks and jobs run two times. The rollout must not report
        // success.
        for retry in [
            DrainRetry::Stdout("not-stopped"),
            DrainRetry::Stdout("bash: -c: line 0"),
            DrainRetry::CommandFails,
            DrainRetry::TransportFails,
        ] {
            let (recorder, result) = drain_old_failure_run(&retry, false);
            let err = result.expect_err("an old slot that may still run must halt the rollout");

            assert_one_retry_of_the_drained_unit(&recorder);
            assert!(
                !recorder.run_labels_for("web-b").contains(&"prune"),
                "nothing more of the deploy runs on the halted host"
            );
            assert_eq!(
                recorder.run_labels_for("web-c"),
                READ_ONLY_PROBES.to_vec(),
                "the host after the halt must not be touched"
            );

            let halt = fleet_halt_of(&err);
            assert_eq!(halt.failed_host, "web-b");
            assert_eq!(halt.failed_step, "drain-old");
            assert_eq!(
                halt.rolled_back,
                vec!["web-a".to_owned(), "web-b".to_owned()],
                "both cut-over hosts are compensated, so each runs ONE slot again"
            );
            assert!(halt.still_on_new.is_empty(), "{:?}", halt.still_on_new);
            assert!(
                halt.degraded.is_empty(),
                "a live old slot is not housekeeping debris: {:?}",
                halt.degraded
            );
            assert_eq!(
                halt.risk(),
                None,
                "compensation left one slot running, so the risk is gone"
            );
        }
    }

    #[test]
    fn a_frozen_drain_old_halt_leaves_the_hosts_and_names_the_risk() {
        // #2279 with `--no-rollback`: nothing is compensated, so the old slot may
        // still run at exit. The halt and its alert must name that risk.
        let (recorder, result) = drain_old_failure_run(&DrainRetry::Stdout("not-stopped"), true);
        let err = result.expect_err("a frozen halt is still a failure");

        assert!(
            recorder.positions_of("resolve-previous").is_empty(),
            "a frozen halt compensates nothing"
        );
        let halt = fleet_halt_of(&err);
        assert_eq!(halt.failed_step, "drain-old");
        assert!(halt.rolled_back.is_empty(), "{:?}", halt.rolled_back);
        assert_eq!(
            halt.still_on_new,
            vec!["web-a".to_owned(), "web-b".to_owned()]
        );
        assert_eq!(halt.risk(), Some(fleet::OLD_SLOT_MAY_RUN_NOTE));
        let alert = build_fleet_halted_alert(halt, "myapp", "prod");
        assert_eq!(
            alert.details.get("risk").map(String::as_str),
            Some(fleet::OLD_SLOT_MAY_RUN_NOTE),
            "the alert must name the risk, not only the step"
        );
    }

    #[test]
    fn a_drain_old_failure_whose_old_slot_is_proven_stopped_still_degrades() {
        // #2279: a transient failure that the retry clears is housekeeping. The
        // rollout continues, as it did before.
        let (recorder, result) = drain_old_failure_run(&DrainRetry::Stdout("stopped"), false);
        result.expect("a proven-stopped old slot must not fail the rollout");

        assert_one_retry_of_the_drained_unit(&recorder);
        assert!(
            !recorder
                .run_labels_for("web-b")
                .contains(&"restart-previous"),
            "the host stays on the new release"
        );
        assert_eq!(
            recorder.run_labels_for("web-c"),
            READ_ONLY_PROBES
                .iter()
                .copied()
                .chain(
                    REDEPLOY_RUN_LABELS
                        .iter()
                        .copied()
                        .filter(|label| *label != "migrate")
                )
                .collect::<Vec<_>>(),
            "the rollout must continue past the degraded host"
        );
        assert!(
            recorder.positions_of("resolve-previous").is_empty(),
            "nothing is compensated"
        );
    }

    #[test]
    fn a_single_host_drain_old_failure_keeps_todays_error_and_does_not_retry() {
        // #2279 keeps AC-1: N = 1 already fails the deploy, so it gets no retry.
        let fleet = fleet_of(&["203.0.113.10"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "203.0.113.10")
            .fail("203.0.113.10", "drain-old");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a single-host drain failure must fail the deploy");

        assert!(matches!(err, DeployError::Exec(_)), "{err:?}");
        assert_eq!(
            recorder.run_labels_for("203.0.113.10").last(),
            Some(&"drain-old"),
            "N = 1 stops at the failed drain and does not retry"
        );
    }

    #[test]
    fn only_a_drain_old_halt_carries_a_risk() {
        assert_eq!(sample_halt().risk(), None, "a `migrate` halt adds no risk");
        let alert = build_fleet_halted_alert(&sample_halt(), "myapp", "production");
        assert!(
            !alert.details.contains_key("risk"),
            "other halts keep today's alert details"
        );
    }

    #[test]
    fn compensation_never_touches_the_schema() {
        // #1621 (AC-3, T1.12). Auto-rollback is BINARY-ONLY. `rollback_ops` and
        // `first_deploy_teardown_ops` contain no `migrate` op by construction, and
        // that must stay true as they evolve: `rolling_deploy_blocked` grades
        // `up.sql` only, so an automatic `migrate down` would run exactly the SQL
        // nothing reviews, unattended, mid-flip. The error text says so too, because
        // an operator watching binaries go back will otherwise assume the schema did.
        let hosts = ["web-a", "web-b"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        recorder = script_compensation(recorder, "web-a", "present");
        recorder =
            script_compensation(recorder, "web-b", "present").transport_fail("web-b", "drain-old");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a post-boundary failure must halt the rollout");

        // Exactly one `migrate` in the WHOLE run — the fleet's single scheduled one,
        // on the first host's cutover — and none of it after compensation began.
        let migrations = recorder.positions_of("migrate");
        assert_eq!(
            migrations.len(),
            1,
            "the fleet migrates once and compensation adds none: {migrations:?}"
        );
        let compensation_started = recorder
            .positions_of("resolve-previous")
            .first()
            .copied()
            .expect("compensation ran");
        assert!(
            migrations[0] < compensation_started,
            "the only migration must predate compensation: migrate at {}, compensation \
             from {compensation_started}",
            migrations[0]
        );
        assert!(
            err.to_string().contains("NOT rolled back"),
            "the halt must state that the schema did not come back with the binaries: {err}"
        );
    }

    /// The `DeployError::Exec` message of a failed single-host deploy.
    fn single_host_exec_message(err: &DeployError) -> &str {
        match err {
            DeployError::Exec(message) => message,
            other => panic!("N = 1 must never produce fleet vocabulary, got: {other:?}"),
        }
    }

    /// The executor error a one-host deploy returns when `failed_step` fails
    /// before the cutover.
    fn pre_cutover_error(mode: fleet::HostMode, failed_step: &'static str) -> String {
        let source = Box::new(exec::DeployExecError::CommandFailed {
            label: failed_step,
            message: "scripted failure".to_owned(),
        });
        match mode {
            fleet::HostMode::Redeploy => exec::DeployExecError::CandidateRolledBack {
                failed_step,
                source,
            },
            fleet::HostMode::First => exec::DeployExecError::FirstDeployTornDown {
                failed_step,
                source,
            },
        }
        .to_string()
    }

    /// Run a one-host deploy in `mode` that fails at `failed_step`. Returns the
    /// error message and the labels the host ran.
    fn failed_single_host_deploy(
        mode: fleet::HostMode,
        failed_step: &'static str,
    ) -> (String, Vec<&'static str>) {
        let host = "203.0.113.10";
        let recorder = fleet::test_support::FleetRecorder::new();
        let recorder = match mode {
            fleet::HostMode::Redeploy => script_redeploy(recorder, host),
            fleet::HostMode::First => script_first_deploy(recorder, host),
        }
        .fail(host, failed_step);
        let fleet = fleet_of(&[host]);
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("the scripted failure must fail the deploy");
        (
            single_host_exec_message(&err).to_owned(),
            recorder.run_labels_for(host),
        )
    }

    #[test]
    fn a_single_host_redeploy_rolled_back_after_migrate_names_the_schema() {
        // #2276: the candidate is torn down and the previous release serves, but the
        // migration stays applied. The error must say so.
        let (message, labels) =
            failed_single_host_deploy(fleet::HostMode::Redeploy, "readiness-gate");

        assert_eq!(
            message,
            format!(
                "{}\n\u{26A0}\u{FE0F}  {}",
                pre_cutover_error(fleet::HostMode::Redeploy, "readiness-gate"),
                fleet::SINGLE_HOST_SCHEMA_AHEAD_NOTE
            ),
            "the executor error stays first; the schema note follows it"
        );
        assert!(
            labels.contains(&"migrate") && !labels.contains(&"proxy-flip"),
            "the deploy must migrate, then stop at the gate: {labels:?}"
        );
    }

    #[test]
    fn a_single_host_marker_repair_failure_keeps_todays_error() {
        // #2276: the live-slot marker repair runs before `migrate`. If it fails,
        // the schema did not move, so the error gets no schema note.
        let host = "203.0.113.10";
        // The marker says blue (3001), but the proxy serves green (3002).
        let drifted = "redeploy:blue\t3001\n\
             ---autumn-kamal-proxy-list---\n\
             Service   Host          Target            State    TLS\n\
             myapp     example.com   127.0.0.1:3002   running  no\n\
             ---autumn-kamal-proxy-unit---\n--http-port 3000\n"
            .to_owned();
        let recorder = fleet::test_support::FleetRecorder::new()
            .script(host, "proxy-compat-probe", compatible_deploy_help())
            .script(host, "detect-current", drifted)
            .script(host, "probe-release-dir", "absent")
            .fail_on_occurrence(host, exec::LIVE_SLOT_REPAIR_LABEL, 1);
        let fleet = fleet_of(&[host]);
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("the failed repair must fail the deploy");

        let labels = recorder.run_labels_for(host);
        assert!(
            !labels.contains(&"migrate"),
            "the repair runs before `migrate`: {labels:?}"
        );
        assert_eq!(
            single_host_exec_message(&err),
            pre_cutover_error(fleet::HostMode::Redeploy, exec::LIVE_SLOT_REPAIR_LABEL),
        );
    }

    #[test]
    fn a_single_host_first_deploy_torn_down_after_migrate_names_the_schema() {
        // #2276: a first deploy migrates, then fails its gate. Nothing serves. The
        // note must not claim a previous release.
        let (message, labels) = failed_single_host_deploy(fleet::HostMode::First, "readiness-gate");

        assert_eq!(
            message,
            format!(
                "{}\n\u{26A0}\u{FE0F}  {}",
                pre_cutover_error(fleet::HostMode::First, "readiness-gate"),
                fleet::SINGLE_HOST_FIRST_DEPLOY_SCHEMA_NOTE
            ),
        );
        assert!(
            labels.contains(&"migrate"),
            "the first deploy must migrate before the gate: {labels:?}"
        );
    }

    #[test]
    fn a_single_host_failure_before_migrate_keeps_todays_error() {
        // #2276: the deploy stopped before `migrate`, so the schema did not move.
        for mode in [fleet::HostMode::Redeploy, fleet::HostMode::First] {
            let (message, labels) = failed_single_host_deploy(mode, "daemon-reload");

            assert_eq!(
                message,
                pre_cutover_error(mode, "daemon-reload"),
                "{mode:?}: a failure before `migrate` keeps today's error verbatim"
            );
            assert!(
                !labels.contains(&"migrate"),
                "{mode:?}: the scripted failure must land before `migrate`: {labels:?}"
            );
        }
    }

    #[test]
    fn a_single_host_failure_keeps_todays_error_and_compensates_nothing() {
        // #1621 (AC-1). N = 1 is exempt from the whole fleet vocabulary: a
        // single-host deploy that fails must return the pre-#1621 error verbatim —
        // no degrade-and-continue, no compensation, no state table. `prune` is the
        // sharpest case: in a FLEET it degrades and the deploy succeeds, while for
        // one host it must stay exactly today's failure. (The #2276 note is only
        // for a host whose binaries went back.)
        let fleet = fleet_of(&["203.0.113.10"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "203.0.113.10")
            .fail("203.0.113.10", "prune");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a single-host post-boundary failure must still fail the deploy");

        match &err {
            DeployError::Exec(message) => assert_eq!(
                *message,
                exec::DeployExecError::CommandFailed {
                    label: "prune",
                    message: "scripted failure".to_owned(),
                }
                .to_string(),
                "the single-host path must surface the raw executor error verbatim"
            ),
            other => panic!("N = 1 must never produce fleet vocabulary, got: {other:?}"),
        }
        assert_eq!(
            recorder.run_labels_for("203.0.113.10"),
            READ_ONLY_PROBES
                .iter()
                .copied()
                .chain(REDEPLOY_RUN_LABELS)
                .collect::<Vec<_>>(),
            "the one host runs today's exact sequence and nothing more — no \
             compensation, no extra probe"
        );
    }

    // ── Fleet-wide fail-closed refusals (issue #1621, slice 5, §4.8) ─────────

    /// A resolved fleet with `[deploy.tls]` enabled for a public hostname — the
    /// shape §4.8 refuses for more than one host.
    fn tls_fleet_of(hosts: &[&str]) -> ResolvedFleet {
        ResolvedFleet::resolve(
            &DeployConfig {
                hosts: hosts.iter().map(|h| (*h).to_owned()).collect(),
                tls: autumn_web::config::DeployTlsConfig {
                    enabled: true,
                    host: Some("shop.example.com".to_owned()),
                },
                ..DeployConfig::default()
            },
            "myapp",
        )
        .expect("a well-formed TLS fleet resolves")
    }

    #[test]
    fn the_fleet_refusals_name_their_config_key_and_spare_a_single_host() {
        // #1621 (§4.8, T1.22). Three topologies that cannot be deployed safely to
        // more than one host at all. Each refusal is a PURE predicate over the
        // CONFIGURED host count, so it is decided before any executor exists — and
        // each names the config key the operator must change plus the tracking
        // issue, matching `reject_sqlite_sharding_topology`'s house style.
        let sqlite = refuse_sqlite_fleet(3, true).expect_err("a sqlite fleet must be refused");
        assert!(
            sqlite.contains("sqlite") && sqlite.contains("#1621"),
            "the sqlite refusal must name the backend and the issue: {sqlite}"
        );
        assert!(
            sqlite.contains("[database]"),
            "the sqlite refusal must name the config section to change: {sqlite}"
        );

        let media = refuse_media_fleet(3, true).expect_err("a media fleet must be refused");
        assert!(
            media.contains("[media.mediamtx]") && media.contains("#1621"),
            "the media refusal must name the config key and the issue: {media}"
        );

        let tls = refuse_tls_fleet(3, true).expect_err("a TLS fleet must be refused");
        assert!(
            tls.contains("[deploy.tls]") && tls.contains("#1621"),
            "the TLS refusal must name the config key and the issue: {tls}"
        );
        assert!(
            tls.contains("load balancer"),
            "the TLS refusal must point at LB-terminated TLS: {tls}"
        );

        // None of the three constrains a single-host deploy — that is exactly
        // today's supported topology (AC-1).
        assert!(refuse_sqlite_fleet(1, true).is_ok());
        assert!(refuse_media_fleet(1, true).is_ok());
        assert!(refuse_tls_fleet(1, true).is_ok());
        // Nor a fleet that does not have the offending feature turned on.
        assert!(refuse_sqlite_fleet(3, false).is_ok());
        assert!(refuse_media_fleet(3, false).is_ok());
        assert!(refuse_tls_fleet(3, false).is_ok());
    }

    #[test]
    fn writable_db_is_sqlite_reads_the_url_the_deploy_would_ship() {
        // The refusal grades the SAME url `build_env_file` writes to every host, so
        // it must follow the primary/compat/shard resolution rather than peeking at
        // one field. Reduced to a bool here so the URL never reaches the driver.
        use autumn_web::config::DatabaseConfig;
        let sqlite = DatabaseConfig {
            url: Some("sqlite://app.db".to_owned()),
            ..DatabaseConfig::default()
        };
        assert!(writable_db_is_sqlite(&sqlite));

        let postgres = DatabaseConfig {
            url: Some("postgres://user:pw@db.internal/app".to_owned()),
            ..DatabaseConfig::default()
        };
        assert!(!writable_db_is_sqlite(&postgres));
        assert!(!writable_db_is_sqlite(&DatabaseConfig::default()));
    }

    #[test]
    fn a_sqlite_fleet_is_refused_before_any_remote_command() {
        // #1621 (T1.22). `build_env_file` ships a byte-identical database URL to
        // every host, so a `sqlite://` fleet is N independent database FILES — no
        // shared schema, no advisory lock, and every host serving a different
        // dataset behind one load balancer. Refused with ZERO remote commands: not
        // even the read-only probes run.
        let fleet = fleet_of(&["web-a", "web-b", "web-c"]);
        let recorder = fleet::test_support::FleetRecorder::new();
        let fixture = FleetFixture::new();
        let input = FleetUpInput {
            profile: "prod",
            app_name: "myapp",
            db: FleetDatabaseFacts {
                sqlite: true,
                ..FleetDatabaseFacts::default()
            },
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a sqlite fleet must be refused");

        match &err {
            DeployError::Config(message) => assert!(
                message.contains("sqlite") && message.contains("#1621"),
                "the refusal must name the backend and the issue: {message}"
            ),
            other => panic!("expected a config refusal, got: {other:?}"),
        }
        assert!(
            recorder.mutating(&[]).is_empty(),
            "a refused fleet must run NO remote command at all, probes included: {:?}",
            recorder.mutating(&[])
        );
    }

    #[test]
    fn a_media_fleet_is_refused_before_any_remote_command() {
        // #1621 (T1.22). `provision_media_host` has no teardown or rollback path by
        // design, so fanning it out gives N MediaMTX daemons on identical ports with
        // divergent recording sets and nothing to undo them with when the app
        // rollout is compensated. Refused in the prologue — which is also what makes
        // the driver's single unguarded `executors[0]` media call correct.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let recorder = fleet::test_support::FleetRecorder::new();
        let mut fixture = FleetFixture::new();
        fixture.media_cfg.enabled = true;
        let input = fixture.input(&fleet);

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a media-enabled fleet must be refused");

        match &err {
            DeployError::Config(message) => assert!(
                message.contains("[media.mediamtx]") && message.contains("#1621"),
                "the refusal must name the config key and the issue: {message}"
            ),
            other => panic!("expected a config refusal, got: {other:?}"),
        }
        assert!(
            recorder.mutating(&[]).is_empty(),
            "a refused fleet must run NO remote command at all, probes included: {:?}",
            recorder.mutating(&[])
        );
    }

    #[test]
    fn a_tls_fleet_is_refused_before_any_remote_command() {
        // #1621 (T1.22). kamal-proxy is PER HOST, so N hosts would each attempt ACME
        // for the same `[deploy.tls] host` from behind the operator's load balancer:
        // only one can answer a challenge and the rest burn Let's Encrypt rate
        // limits. Behind a load balancer, TLS terminates at the load balancer.
        let fleet = tls_fleet_of(&["web-a", "web-b"]);
        let recorder = fleet::test_support::FleetRecorder::new();
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input(&fleet), |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a TLS-enabled fleet must be refused");

        match &err {
            DeployError::Config(message) => assert!(
                message.contains("[deploy.tls]") && message.contains("load balancer"),
                "the refusal must name the config key and point at LB-terminated TLS: \
                 {message}"
            ),
            other => panic!("expected a config refusal, got: {other:?}"),
        }
        assert!(
            recorder.mutating(&[]).is_empty(),
            "a refused fleet must run NO remote command at all, probes included: {:?}",
            recorder.mutating(&[])
        );
    }

    #[test]
    fn up_refuses_the_whole_fleet_when_one_host_fails_preflight() {
        // #2269 (#1621 AC-7 follow-up). `run_up_with` assumes checks are
        // already graded; it never re-checks them. The real gate is
        // `refuse_if_preflight_failed`, called by `run_up` before any
        // executor is built. This test drives that gate directly, then
        // calls `run_up_with` only on success. Mirrors
        // `preflight_failure_aborts_before_any_executor_call` (exec.rs) one
        // level up.
        //
        // This alone cannot prove `run_up` still calls the gate before the
        // hand-off — `and_then` short-circuits regardless. See
        // `up_calls_the_preflight_gate_before_handing_off_to_run_up_with`
        // right below, which asserts that ordering in `run_up`'s own source.
        let fleet = fleet_of(&["web-a", "web-b", "web-c"]);
        let checks = vec![
            PreflightCheck::pass("signing_secret", "ok"),
            PreflightCheck::fail("ssh_reachability", "unreachable", "check the network")
                .scoped(Some("web-b".to_owned())),
        ];
        let recorder = fleet::test_support::FleetRecorder::new();
        let fixture = FleetFixture::new();
        let executor_builds = std::cell::Cell::new(0_usize);

        let err = refuse_if_preflight_failed(&checks)
            .and_then(|()| {
                run_up_with(&fixture.input(&fleet), |cfg| {
                    executor_builds.set(executor_builds.get() + 1);
                    Ok(recorder.executor(cfg))
                })
            })
            .expect_err("a failing host must refuse the whole rollout");

        assert!(
            matches!(err, DeployError::PreflightFailed(1)),
            "expected PreflightFailed(1), got {err:?}"
        );
        assert_eq!(
            executor_builds.get(),
            0,
            "no executor may be built for any host when preflight fails"
        );
        assert!(
            recorder.mutating(&[]).is_empty(),
            "a refused fleet must run NO remote command at all, probes included: {:?}",
            recorder.mutating(&[])
        );
    }

    #[test]
    fn up_calls_the_preflight_gate_before_handing_off_to_run_up_with() {
        // #2269. The test above proves the GATE refuses correctly, but it
        // composes `refuse_if_preflight_failed` and `run_up_with` by hand — it
        // cannot prove `run_up` itself still calls them in that order. This
        // checks the SOURCE order inside `run_up`, mirroring
        // `media_provisioning_is_deferred_past_app_cutover_in_up`: a refactor
        // that moved the gate after the `run_up_with` hand-off, or dropped it,
        // fails this test even though the gate function still works on its
        // own.
        let src = include_str!("deploy.rs");
        let up_body = src
            .split("fn run_up(")
            .nth(1)
            .and_then(|s| s.split("\nfn run_rollback(").next())
            .expect("run_up body present");

        let gate_at = up_body
            .find("refuse_if_preflight_failed(&checks)")
            .expect("the preflight gate call present on the up path");
        let handoff_at = up_body
            .find("run_up_with(")
            .expect("the run_up_with hand-off present on the up path");

        assert!(
            gate_at < handoff_at,
            "run_up must call the preflight gate BEFORE handing off to run_up_with",
        );
    }

    #[test]
    fn the_refusals_grade_the_configured_topology_not_the_narrowed_rollout() {
        // #1621 (§4.8). `--only` narrows which hosts a run TOUCHES; it does not
        // change the topology. A three-host sqlite fleet is just as broken when one
        // host is deployed, so the refusal is keyed on the CONFIGURED count and
        // `--only` can never be used to sneak past it.
        let fleet = fleet_of(&["web-b"]);
        let recorder = fleet::test_support::FleetRecorder::new();
        let fixture = FleetFixture::new();
        let input = FleetUpInput {
            profile: "prod",
            app_name: "myapp",
            configured_host_count: 3,
            db: FleetDatabaseFacts {
                sqlite: true,
                ..FleetDatabaseFacts::default()
            },
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg)))
            .expect_err("`--only` must not defeat a topology refusal");
        assert!(
            matches!(&err, DeployError::Config(m) if m.contains("sqlite")),
            "expected the sqlite refusal, got: {err:?}"
        );
    }

    #[test]
    fn auto_migrate_warns_for_a_fleet_and_stays_silent_for_one_host() {
        // #1621 (§4.8, last paragraph). A WARNING, not a refusal: with
        // `auto_migrate` on, every host applies migrations at BOOT, so the hosts
        // race each other mid-rollout and a checksum mismatch exits the process
        // under `Restart=on-failure` — a crash loop. Real hazard, not a certainty,
        // so it is said loudly and the deploy proceeds.
        let warning = fleet_auto_migrate_warning(3, Some(true), false)
            .expect("a fleet with auto_migrate on must be warned");
        assert!(
            warning.contains("auto_migrate") && warning.contains("#1621"),
            "the warning must name the key and the issue: {warning}"
        );
        assert!(
            warning.contains("boot") && warning.contains("crash loop"),
            "the warning must name the mechanism (boot races) and the symptom: {warning}"
        );

        // The back-compat alias is honoured, and `auto_migrate` supersedes it — the
        // runtime's own resolution rule.
        assert!(fleet_auto_migrate_warning(3, None, true).is_some());
        assert!(
            fleet_auto_migrate_warning(3, Some(false), true).is_none(),
            "an explicit `auto_migrate = false` wins over the alias"
        );

        // Silent for a single host (that is today's supported shape) and silent when
        // the app does not auto-migrate at all.
        assert!(fleet_auto_migrate_warning(1, Some(true), true).is_none());
        assert!(fleet_auto_migrate_warning(3, None, false).is_none());
    }

    #[test]
    fn per_host_job_and_scheduler_backends_warn_for_a_fleet_and_stay_silent_for_one_host() {
        // #1621. `[jobs] backend` defaults to `local`, an in-process queue, and
        // `[scheduler] backend` to `in_process`, a per-process timer. On one host that
        // is correct and is what every unconfigured app runs; on N hosts it silently
        // means N independent queues and N schedulers — enqueued work runs only on the
        // host that took the request, pending work dies with every `drain-old`,
        // `unique`/`concurrency` stop being enforced fleet-wide, and every cron fires N
        // times. A warning, never a refusal: these are the defaults, so refusing would
        // break every existing single-host user's scale-up (same rule as
        // `FLEET_AUTO_MIGRATE_WARNING`).
        let warning = fleet_shared_backend_warning(3, "local", true)
            .expect("a fleet on the in-process defaults must be warned");
        assert!(
            warning.contains("[jobs] backend")
                && warning.contains("[scheduler] backend")
                && warning.contains("#1621"),
            "the warning must name both keys and the issue: {warning}"
        );
        assert!(
            warning.to_lowercase().contains("per host") && warning.contains("drain"),
            "the warning must name the mechanism (a queue per host, drained away): {warning}"
        );

        // Each backend alone still warns, naming only the key that applies.
        let jobs_only = fleet_shared_backend_warning(2, "local", false)
            .expect("a per-host job queue alone must warn");
        assert!(
            jobs_only.contains("[jobs] backend") && !jobs_only.contains("[scheduler] backend"),
            "a durable scheduler must not be named as a problem: {jobs_only}"
        );
        let scheduler_only = fleet_shared_backend_warning(2, "postgres", true)
            .expect("a per-host scheduler alone must warn");
        assert!(
            scheduler_only.contains("[scheduler] backend")
                && !scheduler_only.contains("[jobs] backend"),
            "a durable job backend must not be named as a problem: {scheduler_only}"
        );

        // Silent for a single host — the in-process defaults are exactly right
        // there, and a warning on every `autumn deploy up` would be noise.
        assert!(fleet_shared_backend_warning(1, "local", true).is_none());
        // Silent for durable backends, whatever their spelling/case.
        assert!(fleet_shared_backend_warning(5, "postgres", false).is_none());
        assert!(fleet_shared_backend_warning(5, " Redis ", false).is_none());
    }

    // ── `--only` (issue #1621, slice 5, §3.2) ────────────────────────────────

    #[test]
    fn only_selects_in_declaration_order_and_rejects_an_unknown_host() {
        // #1621 (§3.2). `[deploy] hosts` order IS the rollout order, so the
        // selection is filtered from the CONFIGURED list rather than built from the
        // flag order: `--only web-c --only web-a` must not silently reverse a
        // rolling deploy. An unknown name is a hard error naming itself — guessing
        // (prefix, DNS) could deploy the wrong machine, and deploying nothing
        // silently would be worse.
        let configured: Vec<String> = ["web-a", "web-b", "web-c"]
            .iter()
            .map(|h| (*h).to_owned())
            .collect();

        assert_eq!(
            select_hosts(&configured, &[]).expect("an empty selection is the whole fleet"),
            configured,
            "no `--only` must select the whole fleet, in order"
        );
        assert_eq!(
            select_hosts(&configured, &["web-c".to_owned(), "web-a".to_owned()])
                .expect("a valid selection resolves"),
            vec!["web-a".to_owned(), "web-c".to_owned()],
            "the selection must keep DECLARATION order, not flag order"
        );
        assert_eq!(
            select_hosts(&configured, &["web-b".to_owned(), "web-b".to_owned()])
                .expect("a repeated name is not an error"),
            vec!["web-b".to_owned()],
            "a repeated `--only` selects that host once"
        );

        let err = select_hosts(&configured, &["web-9".to_owned()])
            .expect_err("an unknown host must be refused");
        assert!(
            err.contains("web-9") && err.contains("--only"),
            "the error must quote the unmatched value and the flag: {err}"
        );
        for host in &configured {
            assert!(
                err.contains(host.as_str()),
                "the error must list the configured hosts so the operator can fix the \
                 typo: {err}"
            );
        }
    }

    #[test]
    fn only_restricts_the_rollout_and_moves_the_migration_with_it() {
        // #1621 (§3.2). `--only web-b` on a three-host fleet touches web-b and nothing
        // else — not even the read-only probes run against the skipped hosts, which is
        // deliberate: an excluded host's drifted marker must not refuse a repair deploy
        // aimed at a different host. Migrate placement is computed over the selected
        // hosts, so web-b, the first redeploy in this rollout, migrates; over the full
        // fleet web-a would have. That is the honest reading of "exactly once" for a
        // narrowed rollout — the schema is fleet-wide, and the hosts left out are not
        // being deployed at all.
        let selected = select_hosts(
            &["web-a", "web-b", "web-c"]
                .iter()
                .map(|h| (*h).to_owned())
                .collect::<Vec<_>>(),
            &["web-b".to_owned()],
        )
        .expect("web-b is in the configured fleet");
        let fleet = ResolvedFleet::from_targets(&resolved_defaults(), &selected);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "web-b");
        let fixture = FleetFixture::new();
        let input = FleetUpInput {
            profile: "prod",
            app_name: "myapp",
            configured_host_count: 3,
            ..fixture.input(&fleet)
        };

        run_up_with(&input, |cfg| Ok(recorder.executor(cfg)))
            .expect("a narrowed rollout deploys the selected host");

        assert_eq!(
            recorder.run_labels_for("web-b"),
            READ_ONLY_PROBES
                .iter()
                .copied()
                .chain(REDEPLOY_RUN_LABELS)
                .collect::<Vec<_>>(),
            "the selected host runs the full redeploy, migration included"
        );
        for skipped in ["web-a", "web-c"] {
            assert!(
                recorder.calls_for(skipped).is_empty(),
                "`--only` must not touch {skipped} at all — not even a read-only probe"
            );
        }
    }

    #[test]
    fn a_narrowed_rollout_keeps_fleet_semantics_rather_than_the_single_host_path() {
        // #1621 (AC-1 boundary). The byte-identical pre-#1621 path is for a config
        // that declares ONE host. A three-host fleet narrowed to one is NOT that: the
        // other two hosts exist and are on another release, so the run keeps the
        // fleet vocabulary, the state table and the compensation semantics. Proven
        // by the error TYPE: the single-host path returns the raw executor error,
        // the fleet path a `FleetHalted` report.
        let fleet = fleet_of(&["web-b"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "web-b")
            .fail("web-b", "readiness-gate");
        let fixture = FleetFixture::new();
        let input = FleetUpInput {
            profile: "prod",
            app_name: "myapp",
            configured_host_count: 3,
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg)))
            .expect_err("the selected host's failure must fail the deploy");

        let halt = fleet_halt_of(&err);
        assert_eq!(halt.failed_host, "web-b");
        assert_eq!(halt.failed_step, "readiness-gate");
    }

    #[test]
    fn a_narrowed_probe_refusal_still_names_its_host() {
        // #1621 (AC-1 boundary, audit gap G10). "Is this really a single-host
        // deploy?" has ONE answer, `is_single_host_deploy`, and every site asks it
        // the same way. `probe_host_for_up` used to ask `fleet.is_single()` alone,
        // so a three-host fleet narrowed to one lost the `host {x}: ` prefix on a
        // probe-phase refusal — an unattributed error during a repair operation on
        // a fleet whose other hosts are on another release.
        let narrowed = fleet_of(&["web-b"]);
        let recorder = fleet::test_support::FleetRecorder::new()
            .script("web-b", "proxy-compat-probe", compatible_deploy_help())
            .script("web-b", "detect-current", redeploy_probe())
            .script("web-b", "probe-release-dir", "present");
        let fixture = FleetFixture::new();
        let input = FleetUpInput {
            profile: "prod",
            app_name: "myapp",
            configured_host_count: 3,
            ..fixture.input(&narrowed)
        };

        let narrowed_message = run_up_with(&input, |cfg| Ok(recorder.executor(cfg)))
            .expect_err("an existing release dir must refuse the rollout")
            .to_string();
        assert!(
            narrowed_message.contains("host web-b: release directory"),
            "a narrowed run keeps fleet attribution on probe refusals, got: \
             {narrowed_message}"
        );

        // …and a GENUINE one-host config is byte-identical to the pre-#1621 text:
        // no prefix, nothing else changed (AC-1).
        let single = fleet_of(&["web-b"]);
        let single_recorder = fleet::test_support::FleetRecorder::new()
            .script("web-b", "proxy-compat-probe", compatible_deploy_help())
            .script("web-b", "detect-current", redeploy_probe())
            .script("web-b", "probe-release-dir", "present");
        let single_message = run_up_with(&fixture.input(&single), |cfg| {
            Ok(single_recorder.executor(cfg))
        })
        .expect_err("an existing release dir must refuse the rollout")
        .to_string();
        assert!(
            !single_message.contains("host web-b: "),
            "a genuine single-host refusal must keep the unattributed pre-#1621 \
             text, got: {single_message}"
        );
        assert_eq!(
            narrowed_message.replace("host web-b: ", ""),
            single_message,
            "the two must differ ONLY by the attribution prefix"
        );
    }

    #[test]
    fn a_narrowed_preflight_still_scopes_its_reachability_row() {
        // #1621 (AC-1 boundary, audit gap G10). The same predicate governs the
        // preflight report: `deploy up --only web-2` on a three-host config is not
        // the single-host path, so its `ssh_reachability` row still names the host
        // it graded. A genuine one-host config stays unscoped (AC-1).
        let config = preflight_config();
        let narrowed = ResolvedFleet::resolve(&fleet_cfg(&["web-2.example.test"]), "myapp")
            .expect("a narrowed fleet resolves");

        let scoped = collect_fleet_preflight(&config, &narrowed, 3);
        assert_eq!(
            scoped
                .iter()
                .filter(|check| check.name == SSH_REACHABILITY_CHECK)
                .map(|check| check.scope.as_deref())
                .collect::<Vec<_>>(),
            vec![Some("web-2.example.test")],
            "a narrowed run must keep host attribution: {:?}",
            scoped
                .iter()
                .map(|c| (c.name, &c.scope))
                .collect::<Vec<_>>()
        );

        let genuine = collect_fleet_preflight(&config, &narrowed, 1);
        assert!(
            genuine.iter().all(|check| check.scope.is_none()),
            "a genuine one-host config must stay unscoped (AC-1): {:?}",
            genuine
                .iter()
                .map(|c| (c.name, &c.scope))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn no_rollback_freezes_the_fleet_instead_of_compensating() {
        // #1621 (§4.7). `--no-rollback` is halt-and-FREEZE: the rollout stops and
        // reports, and every host is left exactly as it is for inspection. web-b
        // fails post-boundary (a dropped transport at `drain-old`, which carries no
        // op label and so classifies as FUNCTIONAL), so both web-a and web-b are on
        // the new release — and, unlike the default path, they STAY there.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        recorder = recorder.transport_fail("web-b", "drain-old");
        let fixture = FleetFixture::new();

        let err = run_up_with(&fixture.input_frozen(&fleet), |cfg| {
            Ok(recorder.executor(cfg))
        })
        .expect_err("a post-boundary failure must fail the deploy");

        let halt = fleet_halt_of(&err);
        assert_eq!(
            halt.still_on_new,
            vec!["web-a".to_owned(), "web-b".to_owned()],
            "a frozen fleet reports every host left on the new release"
        );
        assert!(
            halt.rolled_back.is_empty() && halt.torn_down.is_empty(),
            "freezing compensates NOTHING: {:?} / {:?}",
            halt.rolled_back,
            halt.torn_down
        );
        // The observable proof: web-a flipped exactly once (its cutover). A
        // compensating rollback would flip it a second time.
        assert_eq!(
            recorder
                .positions_of("proxy-flip")
                .iter()
                .filter(|_| true)
                .count(),
            2,
            "exactly two flips happened (web-a's and web-b's cutovers) — no host was \
             flipped back"
        );
        assert!(
            !recorder
                .run_labels_for("web-a")
                .contains(&"restart-previous"),
            "a frozen rollout must not roll web-a back"
        );

        // And the flag is actually wired to the seam this test drives.
        assert!(
            include_str!("deploy.rs").contains("auto_rollback: !options.no_rollback"),
            "`--no-rollback` must map to the `auto_rollback` driver seam"
        );
    }

    // ── Fleet-wide `deploy rollback` (issue #1621, slice 5, §3.2) ────────────

    /// Script one host's previous-release marker for a fleet-wide rollback.
    fn script_previous_release(
        recorder: fleet::test_support::FleetRecorder,
        host: &str,
    ) -> fleet::test_support::FleetRecorder {
        recorder.script(
            host,
            "resolve-previous",
            format!("prev:{PREVIOUS_RELEASE_DIR}\tblue\t3001"),
        )
    }

    /// Drive a fleet-wide rollback against a scripted recorder.
    fn drive_fleet_rollback(
        fleet: &ResolvedFleet,
        recorder: &fleet::test_support::FleetRecorder,
    ) -> Result<(), DeployError> {
        let proxy = proxy::KamalProxyController::new(60);
        run_fleet_rollback_with(&[], fleet, &proxy, FLEET_PUBLIC_PORT, |cfg| {
            Ok(recorder.executor(cfg))
        })
    }

    // ── `deploy status` (issue #1621, AC-6) ──────────────────────────────────

    /// Full five-section probe stdout: redeploy on blue, proxy serving blue,
    /// public port 3000, TLS off, on `release`.
    fn status_probe(release: &str) -> String {
        format!(
            "redeploy:blue\t3001\n\
             ---autumn-kamal-proxy-list---\n\
             Service   Host          Target            State    TLS\n\
             myapp     example.com   127.0.0.1:3001    running  no\n\
             ---autumn-kamal-proxy-unit---\n--http-port 3000\n\
             ---autumn-kamal-proxy-options---\n0\t\n\
             ---autumn-current-release---\n/srv/autumn/myapp/releases/{release}"
        )
    }

    /// Script a host's two read-only status probes.
    /// The shared maintenance flag path a #1621 slot unit points
    /// `AUTUMN_MAINTENANCE_FLAG_FILE` at for the `myapp` fleet fixtures — the
    /// fourth `probe-host-status` section resolves to it on a healthy host.
    const STATUS_SHARED_FLAG: &str = "/srv/autumn/myapp/shared/autumn-maintenance.json";

    fn script_status(
        recorder: fleet::test_support::FleetRecorder,
        host: &str,
        release: &str,
        ready: &str,
        maintenance: bool,
    ) -> fleet::test_support::FleetRecorder {
        recorder
            .script(host, "detect-current", status_probe(release))
            .script(
                host,
                "probe-host-status",
                format!(
                    "{ready}\n---autumn-host-status---\n{flag}\n---autumn-host-status---\n\
                     deployed\t2026-07-14T12:00:03Z\n---autumn-host-status---\n\
                     {STATUS_SHARED_FLAG}\n{flag}",
                    flag = if maintenance { "maintenance-on" } else { "" }
                ),
            )
    }

    /// `script_status`, but with an explicit last-deploy marker body (AC-6's third
    /// fact) — `""` scripts a host whose marker is absent/unreadable.
    fn script_status_last_deploy(
        recorder: fleet::test_support::FleetRecorder,
        host: &str,
        release: &str,
        last_deploy: &str,
    ) -> fleet::test_support::FleetRecorder {
        recorder
            .script(host, "detect-current", status_probe(release))
            .script(
                host,
                "probe-host-status",
                format!(
                    "200\n---autumn-host-status---\n\n---autumn-host-status---\n{last_deploy}\n\
                     ---autumn-host-status---\n{STATUS_SHARED_FLAG}\n"
                ),
            )
    }

    fn drive_status(
        fleet: &ResolvedFleet,
        recorder: &fleet::test_support::FleetRecorder,
    ) -> Result<Vec<fleet::HostStatus>, DeployError> {
        collect_fleet_status(fleet, FLEET_PUBLIC_PORT, |cfg| Ok(recorder.executor(cfg)))
    }

    #[test]
    fn fleet_status_reports_every_host_read_only_and_in_declaration_order() {
        // #1621 (AC-6): `deploy status` is the surface an operator reaches for
        // mid-incident, so it (a) touches nothing, (b) reports EVERY host, and (c)
        // keeps declaration order — the same order a rollout would replace them in.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_status(recorder, host, "20260714T120000Z", "200", false);
        }

        let statuses =
            drive_status(&fleet, &recorder).expect("a read-only status never fails the command");

        assert_eq!(
            statuses.iter().map(|s| s.host.as_str()).collect::<Vec<_>>(),
            hosts.to_vec(),
            "status must keep `[deploy] hosts` order"
        );
        for host in hosts {
            assert_eq!(
                recorder.run_labels_for(host),
                vec!["detect-current", "probe-host-status"],
                "{host}: status must run ONLY the two read-only probes"
            );
        }
        assert!(
            recorder
                .mutating(&["detect-current", "probe-host-status"])
                .is_empty(),
            "`deploy status` must never mutate a host"
        );
        let report = fleet::fleet_drift(&statuses);
        assert!(!report.drifted(), "a converged fleet reports no drift");
    }

    #[test]
    fn fleet_status_reports_an_unreachable_host_as_a_row_not_an_abort() {
        // A dropped SSH transport on host 2 must NOT abort the report: the fleet's
        // state is exactly what the operator is trying to learn, and hosts 1 and 3
        // still have answers. The unreachable host is a row with an unknown release,
        // and contributes NO drift (a network outage is not a deploy defect).
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_status(recorder, "web-a", "r1", "200", false);
        recorder = script_status(recorder, "web-b", "r1", "200", false)
            .transport_fail("web-b", "detect-current");
        recorder = script_status(recorder, "web-c", "r1", "200", false);

        let statuses = drive_status(&fleet, &recorder).expect("status reports");
        assert_eq!(statuses.len(), 3, "every host gets a row");
        assert!(!statuses[1].reachable, "host 2 is reported unreachable");
        assert!(statuses[0].reachable && statuses[2].reachable);
        let report = fleet::fleet_drift(&statuses);
        assert!(
            !report.version_drift && report.state_drift.is_empty(),
            "an unreachable host must not manufacture drift: {report:?}"
        );
        assert_eq!(report.unknown_releases(), vec!["web-b"]);
    }

    #[test]
    fn fleet_status_surfaces_version_drift_across_mixed_releases() {
        // #1621 (T1.20 at the driver level): two hosts on different releases is the
        // mixed fleet a rolling deploy exists to avoid, and `--strict` is what makes
        // it alertable from cron.
        let hosts = ["web-a", "web-b"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_status(recorder, "web-a", "20260714T120000Z", "200", false);
        recorder = script_status(recorder, "web-b", "20260714T130000Z", "200", true);

        let statuses = drive_status(&fleet, &recorder).expect("status reports");
        let report = fleet::fleet_drift(&statuses);
        assert!(report.version_drift, "different releases are drift");
        assert_eq!(
            statuses[1].maintenance,
            exec::MaintenanceStatus::On,
            "the flag file is read per host"
        );
        assert!(
            statuses[1].ready_code == Some(200),
            "maintenance does NOT change readiness — the two are orthogonal"
        );

        let json = fleet_status_json(&statuses, &report);
        assert_eq!(json["version_drift"], serde_json::json!(true));
        assert_eq!(
            json["hosts"][0]["release"],
            serde_json::json!("20260714T120000Z")
        );
        assert_eq!(json["hosts"][1]["maintenance"], serde_json::json!(true));
        assert_eq!(json["hosts"][1]["ready"], serde_json::json!(200));
    }

    #[test]
    fn status_reports_the_last_deploy_result_per_host() {
        // #1621 AC-6, third per-host fact. Its motivating case: a rollout halts,
        // compensation succeeds, and ten minutes later every host reads back
        // `deployed / R1 / ready 200 / no drift` — a healthy converged fleet with
        // no trace that the last deploy failed and was compensated. `last deploy`
        // is what distinguishes those two fleets.
        let fleet = fleet_of(&["web-a", "web-b", "web-c"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder =
            script_status_last_deploy(recorder, "web-a", "r1", "rolled back\t2026-07-14T12:31:10Z");
        recorder =
            script_status_last_deploy(recorder, "web-b", "r1", "deployed\t2026-07-14T12:00:03Z");
        // A host that has never completed a cutover (or whose marker is
        // unreadable) reports the honest absence, never a fabricated result.
        recorder = script_status_last_deploy(recorder, "web-c", "r1", "");

        let statuses = drive_status(&fleet, &recorder).expect("status reports");
        assert_eq!(
            statuses[0].last_deploy.as_ref().map(|l| l.result.as_str()),
            Some("rolled back"),
        );
        assert_eq!(
            statuses[0]
                .last_deploy
                .as_ref()
                .and_then(|l| l.at.as_deref()),
            Some("2026-07-14T12:31:10Z"),
        );
        assert_eq!(
            statuses[1].last_deploy.as_ref().map(|l| l.result.as_str()),
            Some("deployed"),
        );
        assert_eq!(statuses[2].last_deploy, None);

        let report = fleet::fleet_drift(&statuses);
        // Reported, NOT counted as drift: the fleet is genuinely converged on r1,
        // and turning a past rollback into a standing alert would page forever.
        assert!(!report.drifted(), "a past rollback is not fleet drift");

        let rendered = fleet::fleet_status_lines(&statuses, &report).join("\n");
        assert!(
            rendered.contains("last deploy: rolled back 2026-07-14T12:31:10Z")
                && rendered.contains("last deploy: deployed 2026-07-14T12:00:03Z")
                && rendered.contains("last deploy: ?"),
            "every host's last-deploy cell must be rendered:\n{rendered}"
        );
        // The column's LIMITS are printed where it is read, not only in the guide:
        // a pre-cutover failure never rewrites the marker, so this is the host's
        // own last completed action rather than a verdict on the last rollout.
        assert!(
            rendered.contains(fleet::LAST_DEPLOY_SCOPE_NOTE),
            "the status table must state what `last deploy` does and does not know:\n{rendered}"
        );

        // And the machine-readable surface carries it as a documented object.
        let json = fleet_status_json(&statuses, &report);
        assert_eq!(
            json["hosts"][0]["last_deploy"],
            serde_json::json!({ "result": "rolled back", "at": "2026-07-14T12:31:10Z" }),
        );
        assert_eq!(json["hosts"][2]["last_deploy"], serde_json::Value::Null);
    }

    #[test]
    fn status_never_renders_a_green_marker_for_an_unready_host() {
        // #2273, end to end from the probe: curl's `000` (no answer) and a 503
        // both render `⚠️`, and neither is drift.
        let fleet = fleet_of(&["web-a", "web-b", "web-c"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_status(recorder, "web-a", "r1", "200", false);
        recorder = script_status(recorder, "web-b", "r1", "503", false);
        recorder = script_status(recorder, "web-c", "r1", "000", false);

        let statuses = drive_status(&fleet, &recorder).expect("status reports");
        let report = fleet::fleet_drift(&statuses);
        assert!(!report.drifted(), "{:?}", report.state_drift);
        let rendered = fleet::fleet_status_lines(&statuses, &report).join("\n");
        let row = |host: &str| {
            rendered
                .lines()
                .find(|line| line.contains(host))
                .expect("every host has a row")
        };
        assert!(row("web-a").starts_with("  \u{2705}"), "{rendered}");
        for host in ["web-b", "web-c"] {
            assert!(row(host).starts_with("  \u{26A0}"), "{rendered}");
        }
    }

    #[test]
    fn fleet_status_json_shape_is_stable_and_carries_no_secret() {
        // The repo's own skills are a first-class consumer of `--json`, so the field
        // names are a contract. Nothing here is derived from a shell line or a driver
        // error, so no secret can reach it.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        recorder = script_status(recorder, "web-a", "r1", "200", false);
        recorder = script_status(recorder, "web-b", "r1", "503", false);
        let statuses = drive_status(&fleet, &recorder).expect("status reports");
        let json = fleet_status_json(&statuses, &fleet::fleet_drift(&statuses));

        let host = &json["hosts"][0];
        for field in [
            "host",
            "reachable",
            "mode",
            "release",
            "live_slot",
            "ready",
            "maintenance",
            "proxy_port",
            "last_deploy",
            "drift",
        ] {
            assert!(
                host.get(field).is_some(),
                "the documented per-host field `{field}` must be present: {json}"
            );
        }
        for field in ["hosts", "version_drift", "state_drift", "drifted"] {
            assert!(
                json.get(field).is_some(),
                "the documented top-level field `{field}` must be present: {json}"
            );
        }
        assert_eq!(host["host"], serde_json::json!("web-a"));
        assert_eq!(host["mode"], serde_json::json!("deployed"));
        assert_eq!(json["hosts"][1]["ready"], serde_json::json!(503));
        let rendered = json.to_string();
        for secret in ["AUTUMN_SECURITY__SIGNING_SECRET", "postgres://", "curl"] {
            assert!(
                !rendered.contains(secret),
                "the status JSON must never carry `{secret}`: {rendered}"
            );
        }
    }

    // ── `deploy maintenance on|off` fan-out (issue #1621, AC-5) ──────────────

    /// The remote paths a maintenance `on` writes on one host, per amendment A2.
    const MAINTENANCE_SHARED_PATH: &str = "/srv/autumn/myapp/shared/autumn-maintenance.json";
    const MAINTENANCE_LEGACY_PATH: &str =
        "/srv/autumn/myapp/releases/r1/tmp/autumn-maintenance.json";
    /// The flag path a pre-#1621 unit resolves to when it is running a DIFFERENT
    /// release than the one `current` names — the round-3 disagreement.
    const MAINTENANCE_LIVE_UNIT_PATH: &str =
        "/srv/autumn/myapp/releases/r2/tmp/autumn-maintenance.json";

    fn drive_maintenance(
        fleet: &ResolvedFleet,
        recorder: &fleet::test_support::FleetRecorder,
        verb: DeployAction,
        args: Option<&MaintenanceOnArgs>,
    ) -> Result<(), DeployError> {
        let port = StatusPort {
            port: FLEET_PUBLIC_PORT,
            degraded: None,
        };
        run_fleet_maintenance_with(fleet, &port, "prod", verb, args, |cfg| {
            Ok(recorder.executor(cfg))
        })
    }

    /// Script one host for the maintenance fan-out: the shared deploy probe, plus
    /// the flag path that host's LIVE slot unit resolves to (`""` scripts a unit
    /// that could not be read).
    fn script_maintenance(
        recorder: fleet::test_support::FleetRecorder,
        host: &str,
        release: &str,
        unit_flag: &str,
    ) -> fleet::test_support::FleetRecorder {
        recorder
            .script(host, "detect-current", status_probe(release))
            .script(
                host,
                "detect-maintenance-flag",
                if unit_flag.is_empty() {
                    String::new()
                } else {
                    format!("{unit_flag}\n")
                },
            )
    }

    /// The remote paths `host` was asked to upload to, in order.
    fn upload_paths(recorder: &fleet::test_support::FleetRecorder, host: &str) -> Vec<String> {
        recorder
            .calls_for(host)
            .iter()
            .filter_map(|call| match call {
                exec::test_support::RecordedCall::Upload { remote_path, .. } => {
                    Some(remote_path.clone())
                }
                exec::test_support::RecordedCall::Run { .. } => None,
            })
            .collect()
    }

    #[test]
    fn fleet_maintenance_on_writes_both_flag_paths_on_every_host() {
        // #1621 (AC-5, amendment A2): a host deployed BEFORE this release runs a slot
        // unit with no `AUTUMN_MAINTENANCE_FLAG_FILE`, so its runtime still polls the
        // cwd-relative `{release_dir}/tmp/…`. Writing only the shared path would make
        // `deploy maintenance on` silently do nothing on exactly the hosts an operator
        // is most likely to be maintaining. So both paths are written: the shared one
        // is authoritative for redeployed hosts, the release-scoped one keeps the
        // not-yet-redeployed ones working.
        let hosts = ["web-a", "web-b"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_maintenance(recorder, host, "r1", MAINTENANCE_LEGACY_PATH);
        }

        let args = MaintenanceOnArgs {
            message: Some("Upgrading the database".to_owned()),
            readonly: true,
            ..MaintenanceOnArgs::default()
        };
        drive_maintenance(&fleet, &recorder, DeployAction::MaintenanceOn, Some(&args))
            .expect("every host accepts the write");

        for host in hosts {
            let paths = upload_paths(&recorder, host);
            assert!(
                paths.iter().any(|p| p == MAINTENANCE_SHARED_PATH),
                "{host} must get the shared (authoritative) flag: {paths:?}"
            );
            assert!(
                paths.iter().any(|p| p == MAINTENANCE_LEGACY_PATH),
                "{host} must also get the release-scoped flag for pre-#1621 units: {paths:?}"
            );
            // The release-scoped `tmp/` dir may not exist yet.
            assert!(
                recorder
                    .run_labels_for(host)
                    .contains(&"maintenance-prepare-live-flag-dir"),
                "{host} must create the dir holding the running unit's flag before \
                 writing into it"
            );
        }
    }

    #[test]
    fn fleet_maintenance_flag_is_written_0600_and_never_echoes_the_bypass_token() {
        // #1621. The flag body embeds `--bypass-header NAME:VALUE`
        // — a credential that lets a request skip the 503 gate for the whole
        // maintenance window — plus the `--allow-ips` list. Both the remote file
        // and the local staging copy inherit the op's mode, so 0644 exposed the
        // token to every local account on every fleet host AND in the operator's
        // own `/tmp`. The file is written and read by the same `cfg.user` that
        // `render_app_unit` emits as `User=`, so 0600 works exactly as it does for
        // the env file carrying the signing secret (`exec::env_file` / AC-5).
        let hosts = ["web-a", "web-b"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_maintenance(recorder, host, "r1", MAINTENANCE_LEGACY_PATH);
        }

        let args = MaintenanceOnArgs {
            message: Some("Upgrading the database".to_owned()),
            allow_ips: vec!["10.0.0.0/8".to_owned()],
            readonly: true,
            bypass_header: Some(("X-Dev-Bypass".to_owned(), "s3cr3t-bypass".to_owned())),
        };
        drive_maintenance(&fleet, &recorder, DeployAction::MaintenanceOn, Some(&args))
            .expect("every host accepts the write");

        for host in hosts {
            let uploads: Vec<(String, Option<u32>)> = recorder
                .calls_for(host)
                .iter()
                .filter_map(|call| match call {
                    exec::test_support::RecordedCall::Upload { remote_path, mode } => {
                        Some((remote_path.clone(), *mode))
                    }
                    exec::test_support::RecordedCall::Run { .. } => None,
                })
                .collect();
            assert_eq!(
                uploads.len(),
                2,
                "{host} writes the shared and the release-scoped flag: {uploads:?}"
            );
            for (path, mode) in &uploads {
                assert_eq!(
                    *mode,
                    Some(0o600),
                    "{host}: {path} carries the bypass token, so it must not be world-readable"
                );
            }
        }

        // The token must never ride in an op label or a rendered shell line.
        let calls_debug = format!("{:#?}", recorder.calls_for("web-a"));
        assert!(
            !calls_debug.contains("s3cr3t-bypass"),
            "the bypass token leaked into the recorded executor calls: {calls_debug}"
        );
    }

    #[test]
    fn fleet_maintenance_on_writes_shared_only_when_no_release_is_promoted() {
        // A host whose first deploy has not happened yet runs no slot unit at all, so
        // no application polls a release-local flag and the shared write IS the whole
        // job — the next deploy installs a #1621 unit that honours it. The outcome says
        // shared-only rather than pretending two files landed, and unlike the unproved
        // case (where a unit IS serving) this is a success, not a failure. Also proves
        // the fan-out works for an N==1 "fleet" (the deploy-config'd remote host, as
        // distinct from the LOCAL `autumn maintenance`).
        let fleet = fleet_of(&["web-a"]);
        let recorder = fleet::test_support::FleetRecorder::new().script(
            "web-a",
            "detect-current",
            "first\n---autumn-kamal-proxy-list---\n",
        );

        drive_maintenance(
            &fleet,
            &recorder,
            DeployAction::MaintenanceOn,
            Some(&MaintenanceOnArgs::default()),
        )
        .expect("a shared-only write is a success, not a failure");

        let paths = upload_paths(&recorder, "web-a");
        assert_eq!(
            paths,
            vec![MAINTENANCE_SHARED_PATH.to_owned()],
            "only the shared flag can be written without a resolvable release"
        );
        assert!(
            !recorder
                .run_labels_for("web-a")
                .contains(&"maintenance-prepare-live-flag-dir"),
            "no running unit means no second flag dir to prepare"
        );
    }

    #[test]
    fn fleet_maintenance_on_prepares_the_shared_flag_dir_before_uploading() {
        // #2280: `prepare-dirs` (which creates `{app_dir}/shared`) only runs during
        // a deploy, so on a never-deployed host the shared flag's parent does not
        // exist — and scp does not create destination parents, so the very first
        // `maintenance on` failed and the `AppliedSharedOnly` success path keyed on
        // exactly this host shape was unreachable. The dir is created up front,
        // BEFORE the shared write (amendment A2: the shared flag is still written
        // first, so a #1621 unit reacts within 500 ms of the write itself).
        let fleet = fleet_of(&["web-a"]);
        let recorder = fleet::test_support::FleetRecorder::new().script(
            "web-a",
            "detect-current",
            "first\n---autumn-kamal-proxy-list---\n",
        );

        drive_maintenance(
            &fleet,
            &recorder,
            DeployAction::MaintenanceOn,
            Some(&MaintenanceOnArgs::default()),
        )
        .expect("a shared-only write is a success, not a failure");

        let calls = recorder.calls_for("web-a");
        let mkdir_pos = calls
            .iter()
            .position(|call| {
                matches!(
                    call,
                    exec::test_support::RecordedCall::Run { label, shell }
                        if *label == "maintenance-prepare-shared-flag-dir"
                            && shell.contains("mkdir -p")
                            && shell.contains("/srv/autumn/myapp/shared")
                )
            })
            .expect("the shared flag's parent must be created before the upload");
        let upload_pos = calls
            .iter()
            .position(|call| {
                matches!(
                    call,
                    exec::test_support::RecordedCall::Upload { remote_path, .. }
                        if remote_path == MAINTENANCE_SHARED_PATH
                )
            })
            .expect("the shared flag is uploaded");
        assert!(
            mkdir_pos < upload_pos,
            "the shared dir is created BEFORE the shared flag is written"
        );
        assert_eq!(
            upload_paths(&recorder, "web-a"),
            vec![MAINTENANCE_SHARED_PATH.to_owned()],
            "only the shared flag can be written without a resolvable release"
        );
    }

    #[test]
    fn fleet_maintenance_writes_the_flag_the_running_unit_polls_not_the_symlink_target() {
        // #1621 review round 3. `current` and the RUNNING unit can disagree: the proxy
        // flip landed and `commit-markers` did not, so the symlink still names the OLD
        // release while the live slot unit keeps serving from another one. Deriving the
        // legacy flag path from `current` then writes a file NOTHING polls — `on`
        // reports success while the application carries on serving traffic. The write
        // path must resolve the file from the proxy-selected live slot's unit, exactly
        // as the status probe reads it, so read and write agree by construction.
        let fleet = fleet_of(&["web-a"]);
        let recorder = script_maintenance(
            fleet::test_support::FleetRecorder::new(),
            "web-a",
            "r1",
            MAINTENANCE_LIVE_UNIT_PATH,
        );

        drive_maintenance(
            &fleet,
            &recorder,
            DeployAction::MaintenanceOn,
            Some(&MaintenanceOnArgs::default()),
        )
        .expect("both writes land");

        assert_eq!(
            upload_paths(&recorder, "web-a"),
            vec![
                MAINTENANCE_SHARED_PATH.to_owned(),
                MAINTENANCE_LIVE_UNIT_PATH.to_owned(),
            ],
            "the shared flag first (A2), then the file the RUNNING unit polls — and \
             never the stale `current` target"
        );
    }

    #[test]
    fn fleet_maintenance_on_fails_closed_when_the_running_units_flag_is_unproved() {
        // The live slot's unit could not be read, so which file the application polls
        // is NOT proved. The shared (authoritative) write still happens — a #1621 unit
        // reacts to it within 500 ms — but the host must not be reported as maintained:
        // a pre-#1621 unit ignores the shared flag entirely, so claiming success here
        // is exactly the lie the round-3 finding is about.
        let fleet = fleet_of(&["web-a"]);
        let recorder =
            script_maintenance(fleet::test_support::FleetRecorder::new(), "web-a", "r1", "");

        let err = drive_maintenance(
            &fleet,
            &recorder,
            DeployAction::MaintenanceOn,
            Some(&MaintenanceOnArgs::default()),
        )
        .expect_err("an unproved live-unit flag must not exit 0");
        assert!(
            err.to_string().contains("1 of 1"),
            "the host counts as failed in the aggregate: {err}"
        );
        assert_eq!(
            upload_paths(&recorder, "web-a"),
            vec![MAINTENANCE_SHARED_PATH.to_owned()],
            "the shared flag is still written first; nothing is GUESSED for the rest"
        );
    }

    #[test]
    fn fleet_maintenance_off_never_claims_to_clear_a_flag_it_cannot_locate() {
        // The mirror of the `on` case: `off` that cannot prove which file the running
        // unit polls must not report the host as un-maintained, and must not pretend to
        // have removed a release-local flag whose path it only guessed from `current`.
        let fleet = fleet_of(&["web-a"]);
        let recorder =
            script_maintenance(fleet::test_support::FleetRecorder::new(), "web-a", "r1", "");

        drive_maintenance(&fleet, &recorder, DeployAction::MaintenanceOff, None)
            .expect_err("an unproved live-unit flag must not exit 0");

        let shell = recorder
            .calls_for("web-a")
            .iter()
            .find_map(|call| match call {
                exec::test_support::RecordedCall::Run { label, shell }
                    if *label == "maintenance-clear" =>
                {
                    Some(shell.clone())
                }
                _ => None,
            })
            .expect("the shared flag is still cleared");
        assert!(
            shell.contains(MAINTENANCE_SHARED_PATH),
            "the shared flag is still removed: {shell}"
        );
        assert!(
            !shell.contains(MAINTENANCE_LEGACY_PATH),
            "a path derived from `current` must not be removed on a hunch: {shell}"
        );
    }

    #[test]
    fn fleet_maintenance_row_says_the_running_units_flag_was_not_changed() {
        // The row for a partially-changed host must say BOTH true things: the shared
        // flag did change (so an operator reversing by hand knows), and the file the
        // running unit polls did NOT (so nobody reads the row as "this host is
        // maintained").
        let rendered = fleet::fleet_maintenance_summary_lines(
            &["web-a".to_owned()],
            &[fleet::MaintenanceOutcome::LiveUnitUnchanged {
                failed_step: "detect-maintenance-flag",
            }],
            true,
        )
        .join("\n");
        assert!(
            rendered.contains("detect-maintenance-flag"),
            "the row names the step that could not be proved:\n{rendered}"
        );
        assert!(
            rendered.contains("shared flag") && rendered.contains("RUNNING"),
            "the row must distinguish the shared flag from the running unit's:\n{rendered}"
        );
    }

    #[test]
    fn fleet_maintenance_serializes_the_framework_wire_format() {
        // The flag file's shape is `autumn_web::maintenance::MaintenanceConfig` — the
        // struct the RUNTIME deserializes. The CLI serialises that type rather than
        // hand-rolling JSON, so the two can never drift.
        let args = MaintenanceOnArgs {
            message: Some("Upgrading".to_owned()),
            allow_ips: vec!["10.0.0.0/8".to_owned()],
            readonly: true,
            bypass_header: Some(("X-Bypass".to_owned(), "tok".to_owned())),
        };
        let body = maintenance_flag_body(&args);
        let parsed: autumn_web::maintenance::MaintenanceConfig =
            serde_json::from_str(&body).expect("the body must be a MaintenanceConfig");
        assert_eq!(parsed.message.as_deref(), Some("Upgrading"));
        assert!(parsed.readonly);
        assert_eq!(parsed.allow_ips, vec!["10.0.0.0/8"]);
        assert_eq!(
            parsed
                .bypass_header
                .as_ref()
                .map(|(n, v)| (n.as_str(), v.as_str())),
            Some(("X-Bypass", "tok"))
        );
    }

    #[test]
    fn fleet_maintenance_off_removes_both_flag_paths() {
        let hosts = ["web-a", "web-b"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_maintenance(recorder, host, "r1", MAINTENANCE_LEGACY_PATH);
        }

        drive_maintenance(&fleet, &recorder, DeployAction::MaintenanceOff, None)
            .expect("every host clears cleanly");

        for host in hosts {
            let shell = recorder
                .calls_for(host)
                .iter()
                .find_map(|call| match call {
                    exec::test_support::RecordedCall::Run { label, shell }
                        if *label == "maintenance-clear" =>
                    {
                        Some(shell.clone())
                    }
                    _ => None,
                })
                .unwrap_or_else(|| panic!("{host} must run the clear op"));
            assert!(
                shell.contains(MAINTENANCE_SHARED_PATH) && shell.contains(MAINTENANCE_LEGACY_PATH),
                "{host} must clear BOTH paths: {shell}"
            );
            assert!(
                shell.contains("rm -f"),
                "clearing an absent flag must not be an error: {shell}"
            );
            assert!(
                upload_paths(&recorder, host).is_empty(),
                "`off` writes nothing"
            );
        }
    }

    #[test]
    fn fleet_maintenance_attempts_every_host_and_reports_the_ones_that_failed() {
        // #1621 (T1.21, plan §6.2): control-plane fan-out is best-effort-and-aggregate,
        // the OPPOSITE of the rollout driver. `maintenance on` that succeeded on 2 of 3
        // hosts must NOT be rolled back — that would push users back into the very live
        // window the operator is trying to close — and it must NOT stop at host 2,
        // because host 3 is still serving. Every host is attempted, all three are named
        // with their state, and the command exits non-zero.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_maintenance(recorder, host, "r1", MAINTENANCE_LEGACY_PATH);
        }
        recorder = recorder.fail_upload("web-b", MAINTENANCE_SHARED_PATH);

        let err = drive_maintenance(
            &fleet,
            &recorder,
            DeployAction::MaintenanceOn,
            Some(&MaintenanceOnArgs::default()),
        )
        .expect_err("a failed host must exit non-zero");
        let message = err.to_string();
        assert!(
            message.contains("1 of 3"),
            "the error must count the failures against the fleet: {message}"
        );

        // Hosts 1 and 3 were still attempted AND still wrote — the point of
        // best-effort-and-aggregate.
        for host in ["web-a", "web-c"] {
            assert!(
                upload_paths(&recorder, host)
                    .iter()
                    .any(|p| p == MAINTENANCE_SHARED_PATH),
                "{host} must still be attempted (and changed) after web-b failed"
            );
        }
        assert!(
            upload_paths(&recorder, "web-b")
                .iter()
                .any(|p| p == MAINTENANCE_SHARED_PATH),
            "the failing host is attempted too, not skipped"
        );
        // Nothing about the failure leaks a shell line or a remote message.
        for noise in ["scripted upload failure", "rm -f", "printf"] {
            assert!(
                !message.contains(noise),
                "the aggregate error must carry no remote detail: {message}"
            );
        }
    }

    #[test]
    fn fleet_maintenance_rows_name_every_host_and_the_orthogonality_note() {
        // Every host is named with what happened to it, so an operator who has to
        // reverse a partial change knows which hosts changed. And the output states —
        // every time — that maintenance mode does not drain a host from the LB, because
        // the opposite assumption causes an outage.
        let rendered = fleet::fleet_maintenance_summary_lines(
            &["web-a".to_owned(), "web-b".to_owned(), "web-c".to_owned()],
            &[
                fleet::MaintenanceOutcome::Applied,
                fleet::MaintenanceOutcome::Failed {
                    failed_step: "maintenance-write-shared",
                },
                fleet::MaintenanceOutcome::AppliedSharedOnly,
            ],
            true,
        )
        .join("\n");
        for host in ["web-a", "web-b", "web-c"] {
            assert!(rendered.contains(host), "every host is named:\n{rendered}");
        }
        assert!(
            rendered.contains(fleet::MAINTENANCE_DOES_NOT_DRAIN_NOTE),
            "the orthogonality note must be printed:\n{rendered}"
        );
        assert!(
            rendered.contains("maintenance-write-shared"),
            "a failure names its step label:\n{rendered}"
        );
        assert!(
            rendered.contains("Changed anyway: web-a, web-c"),
            "the hosts that DID change must be named so they can be reversed:\n{rendered}"
        );
    }

    #[test]
    fn fleet_rollback_rolls_back_every_host_newest_first() {
        // #1621 (§3.2). `deploy rollback` on a `[deploy] hosts` config rolls back the
        // WHOLE fleet, in strict REVERSE declaration order: the hosts that cut over
        // last have been on the new release for the shortest time, so undoing them
        // first shrinks the mixed window from the newest end — the same order fleet
        // compensation uses.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_previous_release(recorder, host);
        }

        drive_fleet_rollback(&fleet, &recorder).expect("every host rolls back cleanly");

        for host in hosts {
            assert_eq!(
                recorder.run_labels_for(host),
                FLEET_ROLLBACK_RUN_LABELS.to_vec(),
                "{host} must run the UNCHANGED on-demand rollback sequence"
            );
        }
        let flips: Vec<usize> = hosts
            .iter()
            .map(|host| {
                recorder
                    .index_of(host, "proxy-flip")
                    .unwrap_or_else(|| panic!("{host} must flip back"))
            })
            .collect();
        assert!(
            flips[2] < flips[1] && flips[1] < flips[0],
            "hosts must roll back newest-first (web-c, web-b, web-a), got positions {flips:?}"
        );
    }

    #[test]
    fn fleet_rollback_rolls_the_reachable_hosts_back_past_a_dead_peer() {
        // #1621 (§3.2 vs AC-7). `deploy up` refuses the whole rollout when any host
        // fails preflight — a rollout is a change, and starting one it cannot finish
        // is how a fleet ends up mixed. A ROLLBACK is the opposite: it is recovery,
        // and the host that stopped answering SSH is very often the reason the
        // operator is rolling back. Hard-gating there leaves the healthy majority on
        // the bad release — MORE hosts on the release being abandoned, which is the
        // outcome the best-effort-continue contract exists to prevent.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in ["web-a", "web-c"] {
            recorder = script_previous_release(recorder, host);
        }
        // web-b never answered the preflight TCP probe. It is NOT scripted at all, so
        // the strict recorder panics if the rollback so much as probes it.
        let checks = vec![
            PreflightCheck::fail(
                "ssh_reachability",
                "cannot reach web-b:22",
                "check the host",
            )
            .scoped(Some("web-b".to_owned())),
            PreflightCheck::pass("migrate_check", "ok"),
        ];
        let proxy = proxy::KamalProxyController::new(60);

        let err = run_fleet_rollback_with(&checks, &fleet, &proxy, FLEET_PUBLIC_PORT, |cfg| {
            Ok(recorder.executor(cfg))
        })
        .expect_err("a fleet that did not fully converge must exit non-zero");

        assert!(
            matches!(
                &err,
                DeployError::FleetRollbackFailed {
                    not_rolled_back: 1,
                    total: 3
                }
            ),
            "the unreachable host is reported as NOT rolled back, got: {err:?}"
        );
        for host in ["web-a", "web-c"] {
            assert_eq!(
                recorder.run_labels_for(host),
                FLEET_ROLLBACK_RUN_LABELS.to_vec(),
                "{host} is reachable and must be rolled back despite web-b being dead"
            );
        }
        assert!(
            recorder.run_labels_for("web-b").is_empty(),
            "an unreachable host must not be touched at all: {:?}",
            recorder.run_labels_for("web-b")
        );
    }

    #[test]
    fn a_rollback_still_hard_gates_on_a_project_wide_preflight_failure() {
        // …and the downgrade above is narrow by construction: only a PER-HOST
        // reachability row is survivable. A project-wide grader describes the release
        // being rolled back TO, not one host's reachability, so it keeps the
        // pre-#1621 hard gate — as does every check of a single-host rollback, whose
        // rows are unscoped.
        let reachable_fleet = vec![
            PreflightCheck::fail(
                "ssh_reachability",
                "cannot reach web-b:22",
                "check the host",
            )
            .scoped(Some("web-b".to_owned())),
        ];
        assert_eq!(
            blocking_rollback_failures(&reachable_fleet, true),
            0,
            "a per-host reachability failure must not block the reachable hosts"
        );

        let mut project_wide = reachable_fleet;
        project_wide.push(PreflightCheck::fail(
            "migrate_check",
            "migrations do not compile",
            "fix them",
        ));
        assert_eq!(
            blocking_rollback_failures(&project_wide, true),
            1,
            "a project-wide grader still aborts the whole command"
        );

        // The single-host path is untouched: every failure blocks it (pre-#1621
        // behavior verbatim).
        let single = vec![PreflightCheck::fail(
            "ssh_reachability",
            "cannot reach web-a:22",
            "check the host",
        )];
        assert_eq!(
            blocking_rollback_failures(&single, false),
            1,
            "a single-host rollback must keep aborting before touching the server"
        );
        // …including when the row IS scoped. A `--only`-narrowed rollback scopes its
        // reachability row for attribution (#1621 audit gap G10) but still runs the
        // single-host path, which has no skip-and-report step — so downgrading the
        // row there would send it straight into an SSH the preflight already knows
        // will fail. The gate keys on the PATH, never on the scope alone.
        let narrowed = vec![
            PreflightCheck::fail(
                "ssh_reachability",
                "cannot reach web-b:22",
                "check the host",
            )
            .scoped(Some("web-b".to_owned())),
        ];
        assert_eq!(
            blocking_rollback_failures(&narrowed, false),
            1,
            "a narrowed single-host rollback must still abort before touching the server"
        );
    }

    #[test]
    fn fleet_rollback_skips_a_host_with_no_previous_release_and_rolls_the_rest_back() {
        // #1621 (§3.2). A host that has never been redeployed — a first deploy clears
        // the marker, and a host just added to the fleet never had one — has nothing to
        // roll back to. That is a reported skip rather than a failed rollback, and it
        // must not stop the other hosts: halting there would leave them on the release
        // the operator is trying to leave. It does still make the command exit non-zero.
        // The contract of a fleet rollback is that the fleet returns to its previous
        // release, and a fleet where one host cannot follow the others is mixed —
        // reporting that as success is how a mixed fleet survives an incident unnoticed.
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in ["web-a", "web-c"] {
            recorder = script_previous_release(recorder, host);
        }
        // web-b's marker is absent: the probe answers `none`.
        recorder = recorder.script("web-b", "resolve-previous", "none");

        let err = drive_fleet_rollback(&fleet, &recorder)
            .expect_err("a fleet that did not fully converge must exit non-zero");
        assert!(
            matches!(
                &err,
                DeployError::FleetRollbackFailed {
                    not_rolled_back: 1,
                    total: 3
                }
            ),
            "exactly one host must be reported as un-rolled-back, got: {err:?}"
        );
        assert!(
            err.to_string().contains("no previous release"),
            "the error must explain the skipped case, not just count it: {err}"
        );

        assert_eq!(
            recorder.run_labels_for("web-b"),
            vec!["resolve-previous"],
            "a host with no previous release must be probed and then left ALONE"
        );
        for host in ["web-a", "web-c"] {
            assert_eq!(
                recorder.run_labels_for(host),
                FLEET_ROLLBACK_RUN_LABELS.to_vec(),
                "{host} must still roll back — a skip is not a halt"
            );
        }
    }

    #[test]
    fn fleet_rollback_continues_past_a_failed_host_and_exits_non_zero() {
        // #1621 (§3.2). Best-effort continue, never swallowed: web-c's rollback
        // fails at its readiness gate, and web-b and web-a are still rolled back —
        // stopping would leave MORE hosts on the release being abandoned. The
        // command still exits non-zero, with counts only (never a driver message).
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_previous_release(recorder, host);
        }
        recorder = recorder.fail("web-c", "readiness-gate");

        let err = drive_fleet_rollback(&fleet, &recorder)
            .expect_err("a failed host must fail the fleet rollback");

        match &err {
            DeployError::FleetRollbackFailed {
                not_rolled_back,
                total,
            } => {
                assert_eq!((*not_rolled_back, *total), (1, 3));
            }
            other => panic!("expected a fleet-rollback failure, got: {other:?}"),
        }
        for host in ["web-a", "web-b"] {
            assert!(
                recorder.run_labels_for(host).contains(&"proxy-flip"),
                "{host} must still be rolled back after web-c failed"
            );
        }
        let rendered = format!("{err}\n{err:?}");
        for secret in [
            "postgres://",
            "topsecret",
            "AUTUMN_SECURITY__SIGNING_SECRET",
        ] {
            assert!(
                !rendered.contains(secret),
                "the fleet-rollback error must never carry `{secret}`: {rendered}"
            );
        }
    }

    #[test]
    fn a_fleet_rollback_that_rolled_nothing_back_is_an_error() {
        // #1621 (§3.2). Every host reports no previous release, so nothing happened
        // at all. Exiting zero would tell the operator their fleet was rolled back
        // when it was not — the one outcome worse than failing.
        let hosts = ["web-a", "web-b"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = recorder.script(host, "resolve-previous", "none");
        }

        let err = drive_fleet_rollback(&fleet, &recorder)
            .expect_err("a rollback that rolled nothing back must not report success");
        assert!(
            matches!(
                &err,
                DeployError::FleetRollbackFailed {
                    not_rolled_back: 2,
                    total: 2
                }
            ),
            "expected all-hosts-unrolled, got: {err:?}"
        );
    }

    #[test]
    fn operator_facing_fleet_error_text_carries_no_line_continuation_gutter() {
        // #1621. These messages are `\`-continued multi-line
        // literals; a missing continuation backslash bakes the source indentation
        // into the message as a long run of spaces mid-sentence. `DriftDetected`
        // has no placeholders, so its Display output is the literal byte-for-byte.
        assert_eq!(
            DeployError::DriftDetected.to_string(),
            "fleet drift detected \u{2014} the status table above names each host and reason \
             (`--strict` exits non-zero on drift so it can be alerted on)",
        );
        assert_eq!(
            DeployError::FleetMaintenanceFailed {
                verb: "on",
                failed: 1,
                total: 3,
            }
            .to_string(),
            "fleet maintenance on incomplete: 1 of 3 host(s) failed \u{2014} the table above \
             names the hosts that DID change, so they can be reversed by hand if the fleet \
             must stay consistent",
        );
        for rendered in [
            DeployError::DriftDetected.to_string(),
            DeployError::FleetMaintenanceFailed {
                verb: "off",
                failed: 2,
                total: 5,
            }
            .to_string(),
        ] {
            assert!(
                !rendered.contains("   "),
                "a run of spaces mid-sentence means a `\\` continuation was dropped: {rendered}",
            );
        }
    }

    // ── post-cutover bake (issue #3069) ──────────────────────────────────────

    /// 20 s at 10 s: a baseline and two samples. The limit is 1.44 % 5xx.
    fn bake_policy() -> bake::BakePolicy {
        bake::BakePolicy {
            duration_secs: 20,
            interval_secs: 10,
            min_requests: 20,
            max_error_ppm: 14_400,
            latency: Vec::new(),
            source: "test".to_owned(),
            warnings: Vec::new(),
        }
    }

    /// A bake sample's stdout: `ok` 2xx and `errors` 5xx responses, then the
    /// systemd restart count.
    fn bake_metrics(ok: u64, errors: u64) -> String {
        format!(
            r#"{{"http":{{"latency_ms":{{"p50":1,"p95":2,"p99":3}},
            "by_status":{{"2xx":{ok},"3xx":0,"4xx":0,"5xx":{errors}}}}}}}
{}
0
"#,
            bake::RESTARTS_MARKER
        )
    }

    /// Script one host's bake samples, in order.
    fn script_bake(
        mut recorder: fleet::test_support::FleetRecorder,
        host: &str,
        samples: &[(u64, u64)],
    ) -> fleet::test_support::FleetRecorder {
        for (index, (ok, errors)) in samples.iter().enumerate() {
            recorder = recorder.script_occurrence(
                host,
                bake::SAMPLE_LABEL,
                index + 1,
                bake_metrics(*ok, *errors),
            );
        }
        recorder
    }

    const HEALTHY_BAKE: [(u64, u64); 3] = [(10, 0), (110, 0), (210, 1)];
    /// The injected spike: 40 new 5xx in the second window.
    const SPIKED_BAKE: [(u64, u64); 3] = [(10, 0), (110, 0), (170, 40)];

    #[test]
    fn an_error_spike_during_the_bake_rolls_a_single_host_back() {
        let fleet = fleet_of(&["web-a"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "web-a");
        let recorder = script_compensation(recorder, "web-a", "present");
        let recorder = script_bake(recorder, "web-a", &SPIKED_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a breached bake must fail the deploy");

        let DeployError::BakeFailed {
            host,
            reason,
            result,
            schema_note,
        } = &err
        else {
            panic!("expected BakeFailed, got {err:?}");
        };
        assert_eq!(host, "web-a");
        // 200 new responses, less the bake's own 2 metric requests.
        assert!(reason.contains("40 of 198 responses were 5xx"), "{reason}");
        assert_eq!(*result, BAKE_ROLLED_BACK);
        // A one-host deploy runs the migration, so the schema stays ahead.
        assert_eq!(*schema_note, Some(fleet::SINGLE_HOST_SCHEMA_AHEAD_NOTE));
        assert!(err.to_string().contains("was NOT rolled back"), "{err}");

        // The bake runs after the cutover, and the rollback after the bake.
        let flip = recorder.index_of("web-a", "proxy-flip").expect("cut over");
        let first_sample = recorder
            .index_of("web-a", bake::SAMPLE_LABEL)
            .expect("the bake sampled");
        let restart = recorder
            .index_of("web-a", "restart-previous")
            .expect("the host must be rolled back");
        assert!(flip < first_sample && first_sample < restart);
        let labels = recorder.run_labels_for("web-a");
        assert_eq!(
            labels.iter().filter(|l| **l == bake::SAMPLE_LABEL).count(),
            3,
            "the bake stops at the breach: {labels:?}"
        );
    }

    #[test]
    fn a_bake_rollback_during_a_port_move_derives_the_legacy_port_from_the_old_port() {
        // The proxy is installed on port 80 and the new config asks for 3000, so
        // the cutover runs on the old port and the move follows it. The marker
        // has the legacy two-field form, so the rollback derives the previous
        // slot's port. It must use the old port (blue = 81), not the new one
        // (blue = 3001), where nothing listens.
        let fleet = fleet_of(&["web-a"]);
        let probe = "redeploy:blue\t81\n\
             ---autumn-kamal-proxy-list---\n\
             ---autumn-kamal-proxy-unit---\n--http-port 80\n"
            .to_owned();
        let recorder = fleet::test_support::FleetRecorder::new()
            .script("web-a", "proxy-compat-probe", compatible_deploy_help())
            .script("web-a", "detect-current", probe)
            .script("web-a", "probe-release-dir", "absent")
            .script(
                "web-a",
                "resolve-previous",
                format!("prev:{PREVIOUS_RELEASE_DIR}\tblue"),
            )
            .script("web-a", "probe-rollback-target", "present");
        let recorder = script_bake(recorder, "web-a", &SPIKED_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a breached bake must fail the deploy");
        let DeployError::BakeFailed { result, .. } = &err else {
            panic!("expected BakeFailed, got {err:?}");
        };
        assert_eq!(*result, BAKE_ROLLED_BACK);

        let restart = recorder
            .index_of("web-a", "restart-previous")
            .expect("rolled back");
        let rollback: Vec<String> = recorder.calls_for("web-a")[restart..]
            .iter()
            .filter_map(|call| match call {
                exec::test_support::RecordedCall::Run { shell, .. } => Some(shell.clone()),
                exec::test_support::RecordedCall::Upload { .. } => None,
            })
            .collect();
        assert!(
            rollback.iter().any(|shell| shell.contains(":81")),
            "the rollback must target blue on the old port: {rollback:#?}"
        );
        assert!(
            rollback.iter().all(|shell| !shell.contains(":3001")),
            "the rollback must not derive the port from the new server.port: {rollback:#?}"
        );
    }

    #[test]
    fn a_healthy_bake_completes_the_deploy() {
        let fleet = fleet_of(&["web-a"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "web-a");
        let recorder = script_bake(recorder, "web-a", &HEALTHY_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect("a healthy bake passes");

        assert!(recorder.index_of("web-a", "restart-previous").is_none());
        let samples = recorder
            .run_labels_for("web-a")
            .into_iter()
            .filter(|l| *l == bake::SAMPLE_LABEL)
            .count();
        assert_eq!(samples, 3);
    }

    #[test]
    fn the_bake_samples_the_new_release_on_its_slot_port() {
        // The live slot is blue (3001), so the new release is on green (3002).
        let fleet = fleet_of(&["web-a"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "web-a");
        let recorder = script_bake(recorder, "web-a", &HEALTHY_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            metrics_path: "/ops/metrics",
            ..fixture.input(&fleet)
        };
        run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect("passes");
        let shell = recorder
            .calls_for("web-a")
            .into_iter()
            .find_map(|call| match call {
                exec::test_support::RecordedCall::Run { label, shell }
                    if label == bake::SAMPLE_LABEL =>
                {
                    Some(shell)
                }
                _ => None,
            })
            .expect("a sample");
        assert!(
            shell.contains("'http://127.0.0.1:3002/ops/metrics'"),
            "{shell}"
        );
        assert!(shell.contains("-H 'Host: app.example.com'"), "{shell}");
        assert!(shell.contains("'myapp-green.service'"), "{shell}");
    }

    #[test]
    fn a_bake_breach_halts_the_fleet_and_rolls_back_every_host_on_the_new_release() {
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        recorder = script_compensation(recorder, "web-a", "present");
        recorder = script_compensation(recorder, "web-b", "present");
        recorder = script_bake(recorder, "web-a", &HEALTHY_BAKE);
        recorder = script_bake(recorder, "web-b", &SPIKED_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg)))
            .expect_err("a breached bake must halt the rollout");

        let halt = fleet_halt_of(&err);
        assert_eq!(halt.failed_host, "web-b");
        assert_eq!(halt.failed_step, bake::BAKE_LABEL);
        assert_eq!(
            halt.rolled_back,
            vec!["web-a".to_owned(), "web-b".to_owned()]
        );
        assert!(halt.still_on_new.is_empty(), "{:?}", halt.still_on_new);
        let web_b = recorder
            .index_of("web-b", "restart-previous")
            .expect("web-b");
        let web_a = recorder
            .index_of("web-a", "restart-previous")
            .expect("web-a");
        assert!(web_b < web_a, "newest first");
        assert!(
            recorder
                .run_labels_for("web-c")
                .iter()
                .all(|l| !l.starts_with("start-")),
            "web-c must not be touched"
        );
    }

    #[test]
    fn no_rollback_leaves_a_failed_bake_live_and_says_so() {
        let fleet = fleet_of(&["web-a"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "web-a");
        let recorder = script_bake(recorder, "web-a", &SPIKED_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input_frozen(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect_err("fails");

        assert!(
            matches!(err, DeployError::BakeFailed { result, .. } if result == BAKE_FROZEN),
            "{err:?}"
        );
        assert!(recorder.index_of("web-a", "restart-previous").is_none());
    }

    #[test]
    fn a_failed_automatic_rollback_after_the_bake_is_reported() {
        let fleet = fleet_of(&["web-a"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "web-a");
        // The rollback starts, then its restart fails.
        let recorder =
            script_compensation(recorder, "web-a", "present").fail("web-a", "restart-previous");
        let recorder = script_bake(recorder, "web-a", &SPIKED_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect_err("fails");

        assert!(
            matches!(err, DeployError::BakeFailed { result, schema_note: None, .. } if result == BAKE_ROLLBACK_FAILED),
            "{err:?}"
        );
    }

    #[test]
    fn an_unsafe_rollback_after_the_bake_is_refused_and_reported() {
        let fleet = fleet_of(&["web-a"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "web-a");
        // The previous release dir is gone, so the rollback refuses.
        let recorder = script_compensation(recorder, "web-a", "absent");
        let recorder = script_bake(recorder, "web-a", &SPIKED_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect_err("fails");

        assert!(
            matches!(err, DeployError::BakeFailed { result, .. } if result == BAKE_ROLLBACK_REFUSED),
            "{err:?}"
        );
        assert!(recorder.index_of("web-a", "restart-previous").is_none());
    }

    #[test]
    fn no_rollback_freezes_a_fleet_whose_bake_failed() {
        let hosts = ["web-a", "web-b", "web-c"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        recorder = script_bake(recorder, "web-a", &HEALTHY_BAKE);
        recorder = script_bake(recorder, "web-b", &SPIKED_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input_frozen(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect_err("halts");

        let halt = fleet_halt_of(&err);
        assert_eq!(halt.failed_host, "web-b");
        assert_eq!(halt.failed_step, bake::BAKE_LABEL);
        assert!(halt.rolled_back.is_empty(), "{:?}", halt.rolled_back);
        assert_eq!(
            halt.still_on_new,
            vec!["web-a".to_owned(), "web-b".to_owned()]
        );
        assert!(recorder.positions_of("restart-previous").is_empty());
    }

    #[test]
    fn a_host_degraded_by_a_port_rebind_still_bakes() {
        // web-a's port move rolls back, so web-a is Degraded on the new release.
        // Its bake must still run; here the bake fails and the fleet halts.
        let fleet = fleet_of(&["web-a", "web-b"]);
        let probe_a = "redeploy:blue\t81\n\
             ---autumn-kamal-proxy-list---\n\
             ---autumn-kamal-proxy-unit---\n--http-port 80\n"
            .to_owned();
        let recorder = fleet::test_support::FleetRecorder::new()
            .script("web-a", "proxy-compat-probe", compatible_deploy_help())
            .script("web-a", "detect-current", probe_a)
            .script("web-a", "probe-release-dir", "absent")
            .fail_on_occurrence("web-a", "proxy-restart-if-changed", 2);
        let recorder = script_compensation(recorder, "web-a", "present");
        let recorder = script_bake(recorder, "web-a", &SPIKED_BAKE);
        let recorder = script_redeploy(recorder, "web-b");
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect_err("halts");

        let halt = fleet_halt_of(&err);
        assert_eq!(halt.failed_host, "web-a");
        assert_eq!(halt.failed_step, bake::BAKE_LABEL);
        assert!(recorder.index_of("web-a", bake::SAMPLE_LABEL).is_some());
        assert!(
            recorder
                .run_labels_for("web-b")
                .iter()
                .all(|l| !l.starts_with("start-"))
        );
    }

    #[test]
    fn a_degraded_host_still_bakes() {
        // web-a cuts over, but its housekeeping step fails: it is Degraded and
        // serves the new release. Its bake must still run, and here it fails.
        let hosts = ["web-a", "web-b"];
        let fleet = fleet_of(&hosts);
        let mut recorder = fleet::test_support::FleetRecorder::new();
        for host in hosts {
            recorder = script_redeploy(recorder, host);
        }
        recorder =
            script_compensation(recorder, "web-a", "present").fail("web-a", "record-proxy-options");
        recorder = script_bake(recorder, "web-a", &SPIKED_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect_err("halts");

        let halt = fleet_halt_of(&err);
        assert_eq!(halt.failed_host, "web-a");
        assert_eq!(halt.failed_step, bake::BAKE_LABEL);
        assert_eq!(halt.rolled_back, vec!["web-a".to_owned()]);
        assert!(
            halt.degraded
                .iter()
                .any(|(h, l)| h == "web-a" && *l == "record-proxy-options"),
            "the debris is still reported: {:?}",
            halt.degraded
        );
        assert!(
            recorder
                .run_labels_for("web-b")
                .iter()
                .all(|l| !l.starts_with("start-"))
        );
    }

    #[test]
    fn a_first_deploy_skips_the_bake() {
        let fleet = fleet_of(&["web-a"]);
        let recorder = script_first_deploy(fleet::test_support::FleetRecorder::new(), "web-a");
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect("first deploy passes");

        assert!(recorder.index_of("web-a", bake::SAMPLE_LABEL).is_none());
    }

    #[test]
    fn the_bake_in_prod_needs_a_trusted_host() {
        let mut config = AutumnConfig {
            profile: Some("prod".to_owned()),
            ..AutumnConfig::default()
        };
        assert!(matches!(
            resolve_bake_policy(&config, Some(30)),
            Err(DeployError::Config(message)) if message.contains("[security.trusted_hosts]")
        ));
        // No bake, no check.
        assert!(resolve_bake_policy(&config, None).expect("off").is_none());
        config.security.trusted_hosts.hosts = vec!["app.example.com".to_owned()];
        assert!(
            resolve_bake_policy(&config, Some(30))
                .expect("ok")
                .is_some()
        );
        config.security.trusted_hosts.hosts = vec!["*".to_owned()];
        assert!(
            resolve_bake_policy(&config, Some(30))
                .expect("ok")
                .is_some()
        );
    }

    #[test]
    fn a_degraded_single_host_bakes_and_reports_the_bake() {
        let fleet = fleet_of(&["web-a"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "web-a")
            .fail("web-a", "record-proxy-options");
        let recorder = script_compensation(recorder, "web-a", "present");
        let recorder = script_bake(recorder, "web-a", &SPIKED_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect_err("fails");

        assert!(
            matches!(err, DeployError::BakeFailed { result, .. } if result == BAKE_ROLLED_BACK),
            "{err:?}"
        );
        assert!(recorder.index_of("web-a", "restart-previous").is_some());
    }

    #[test]
    fn a_degraded_single_host_with_a_good_bake_keeps_the_housekeeping_error() {
        let fleet = fleet_of(&["web-a"]);
        let recorder = script_redeploy(fleet::test_support::FleetRecorder::new(), "web-a")
            .fail("web-a", "record-proxy-options");
        let recorder = script_bake(recorder, "web-a", &HEALTHY_BAKE);
        let fixture = FleetFixture::new();
        let policy = bake_policy();
        let input = FleetUpInput {
            bake: Some(&policy),
            ..fixture.input(&fleet)
        };

        let err = run_up_with(&input, |cfg| Ok(recorder.executor(cfg))).expect_err("fails");

        assert!(matches!(err, DeployError::Exec(_)), "{err:?}");
        assert!(recorder.index_of("web-a", bake::SAMPLE_LABEL).is_some());
        assert!(recorder.index_of("web-a", "restart-previous").is_none());
    }

    #[test]
    fn the_bake_policy_comes_from_config_slos_and_the_flag() {
        let mut config = AutumnConfig::default();
        assert!(resolve_bake_policy(&config, None).expect("ok").is_none());
        let policy = resolve_bake_policy(&config, Some(30))
            .expect("ok")
            .expect("on");
        assert_eq!(policy.duration_secs, 30);
        assert_eq!(policy.max_error_ppm, bake::DEFAULT_MAX_ERROR_PPM);

        config.slo = vec![autumn_web::slo::SloConfig {
            name: "availability".to_owned(),
            objective: 99.9,
            sli: autumn_web::slo::SliKind::Availability,
            route: None,
            threshold_ms: None,
            description: None,
        }];
        let policy = resolve_bake_policy(&config, Some(30))
            .expect("ok")
            .expect("on");
        assert_eq!(policy.max_error_ppm, 14_400);

        // A bad SLO is a config error only when the bake is on.
        config.slo[0].objective = 100.0;
        assert!(resolve_bake_policy(&config, None).expect("off").is_none());
        assert!(matches!(
            resolve_bake_policy(&config, Some(30)),
            Err(DeployError::Config(message)) if message.contains("[[slo]] availability")
        ));
    }
}