anodizer 0.16.1

A Rust-native release automation tool inspired by GoReleaser
Documentation
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
//! `anodize tag rollback` — delete anodize-managed tags at a SHA and
//! revert (or reset to) the bump commit they point at.
//!
//! Failure-recovery counterpart to `anodize tag`: when a downstream
//! `anodize release` poisons a tag (publish failure, mcp 422, etc.) the
//! operator is left with a tag pointing at a bumped-but-broken commit.
//! This subcommand deletes the tag locally + on origin, then either
//! `git revert`s the bump commit (default, history-preserving) or
//! `git reset --hard`s past it (opt-in, history-rewriting).
//!
//! Safety rails:
//! - Tag name regex filter — only anodize-shaped tags are touched
//!   (`vX.Y.Z[-pre][+build]` for lockstep, `<crate>-vX.Y.Z[...]` for
//!   per-crate). Non-matching tags are skipped with a reason printed.
//! - Hard-fail when non-anodize commits sit between the target SHA and
//!   HEAD in `--mode=revert` (protects against rolling back a bump
//!   after unrelated work landed on top). Use `--mode=reset` to force.

use anodizer_core::git;
use anodizer_core::log::{StageLogger, Verbosity};
use anyhow::{Result, bail};
use regex::Regex;
use std::sync::LazyLock;

/// A published-state guard refusal: the rollback was declined BY DESIGN
/// because destroying the tag(s) could only orphan live published state
/// (a one-way-door registry already holds the version). Distinct from a
/// mechanical rollback failure (git error, unreachable network probe,
/// unmappable config): a refusal is final protection with a known next
/// step, not breakage. Callers that drive rollback programmatically
/// (the release failure policy) downcast to this type to render the
/// refusal as protective status output instead of a failure warning.
#[derive(Debug)]
pub struct RollbackRefusal {
    /// Why the rollback was refused — the burn evidence, one line per
    /// affected tag/version.
    pub reason: String,
    /// What the operator should do instead (fix forward / `--force`).
    pub next_step: String,
}

impl std::fmt::Display for RollbackRefusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "refusing to roll back — {}\nnext step: {}",
            self.reason, self.next_step
        )
    }
}

impl std::error::Error for RollbackRefusal {}

/// Canonical fix-forward guidance shared by every refusal site: the
/// version is burned, so the only clean path is the NEXT version;
/// `--force` remains the explicit override.
fn refusal_next_step() -> String {
    "fix the failure and cut the NEXT version (auto-tag mints it from the next push). \
     To override anyway: `anodizer tag rollback --force`."
        .to_string()
}

/// Scope filter for which tag shape(s) to operate on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
    /// Both lockstep (`vX.Y.Z`) and per-crate (`<crate>-vX.Y.Z`) tags.
    All,
    /// Only lockstep tags (`vX.Y.Z`).
    Lockstep,
    /// Only per-crate tags (`<crate>-vX.Y.Z`).
    PerCrate,
}

impl std::str::FromStr for Scope {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "all" => Ok(Scope::All),
            "lockstep" => Ok(Scope::Lockstep),
            "per-crate" | "percrate" => Ok(Scope::PerCrate),
            other => Err(format!(
                "invalid --scope value: {other:?} (expected all | lockstep | per-crate)"
            )),
        }
    }
}

/// Rollback strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// `git revert --no-edit <sha>` — preserves history. Default.
    Revert,
    /// `git reset --hard <sha>~1` — rewrites history; requires
    /// `--force-with-lease` to push. Opt-in only.
    Reset,
}

impl std::str::FromStr for Mode {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "revert" => Ok(Mode::Revert),
            "reset" => Ok(Mode::Reset),
            other => Err(format!(
                "invalid --mode value: {other:?} (expected revert | reset)"
            )),
        }
    }
}

pub struct RollbackOpts {
    /// Target SHA. `None` resolves to `HEAD`.
    pub sha: Option<String>,
    pub dry_run: bool,
    pub no_push: bool,
    /// `--force`: override the published-state guard. Without it,
    /// rollback refuses when the tag's run summary shows a one-way-door
    /// (Submitter) publisher landed — the version is burned at a
    /// registry that never accepts the same version twice — when the
    /// crates.io index shows the tag's crate@version live (GLOBAL state:
    /// a prior run may have published it; an unreachable index fails
    /// closed) — or, when no summary exists, when the tag's GitHub
    /// release is published (non-draft).
    pub force: bool,
    pub scope: Scope,
    pub mode: Mode,
    /// Branch to push the revert commit to. `None` triggers
    /// auto-resolution via [`git::get_current_branch_in`]; a hard
    /// failure surfaces when HEAD is detached and no local branch
    /// points at it (the operator must pass `--branch` explicitly).
    pub branch: Option<String>,
    pub verbose: bool,
    pub debug: bool,
    pub quiet: bool,
}

/// Strict semver-ish per-crate tag pattern: `<crate>-v<MAJOR>.<MINOR>.<PATCH>[-pre][+build]`.
/// The crate-name portion accepts ASCII letters, `_` and `-` as the
/// first char (cargo crate names must start with a letter — digits are
/// rejected), then letters/digits/`_`/`-` for the remainder; the
/// suffix is then asserted to be anodize's `v<semver>` form so a tag like
/// `foo-bar` (no `-v` suffix) doesn't accidentally match.
///
/// Compiled once at first use (the pattern is a compile-time literal) so
/// the classifier doesn't recompile it per tag — same caching idea as
/// `is_branchlike` in `core/git/commits.rs`.
///
/// Drift-risk pair with `core::git::is_branchlike`: that predicate matches
/// the same two anodize tag shapes but with deliberately looser, prefix-only
/// regexes (it answers "is this NOT a tag?" for branch fallback, so it must
/// not over-strict). These rollback patterns are fully anchored and strict
/// on purpose. Keep the two shape definitions in sync when the tag grammar
/// changes — they are intentionally separate, not accidentally duplicated.
static PER_CRATE_TAG_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^[A-Za-z_][A-Za-z0-9_-]*-v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$")
        .expect("static regex compiles")
});

/// Lockstep tag pattern: `v<MAJOR>.<MINOR>.<PATCH>[-pre][+build]`. Compiled
/// once at first use (see [`PER_CRATE_TAG_RE`]).
static LOCKSTEP_TAG_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^v\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$")
        .expect("static regex compiles")
});

/// Classification used to filter tags against the requested `--scope`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TagKind {
    Lockstep,
    PerCrate,
}

/// Classify a tag against anodize's naming conventions. Returns `None`
/// when the tag doesn't match either shape (in which case the rollback
/// command leaves it alone).
fn classify_tag(tag: &str) -> Option<TagKind> {
    // Lockstep first — `vX.Y.Z` would also fail the per-crate regex's
    // `<crate>-` prefix requirement, but the explicit ordering keeps the
    // intent obvious to a reader.
    if LOCKSTEP_TAG_RE.is_match(tag) {
        Some(TagKind::Lockstep)
    } else if PER_CRATE_TAG_RE.is_match(tag) {
        Some(TagKind::PerCrate)
    } else {
        None
    }
}

/// Apply the `--scope` filter on top of the classification.
fn scope_includes(scope: Scope, kind: TagKind) -> bool {
    matches!(
        (scope, kind),
        (Scope::All, _)
            | (Scope::Lockstep, TagKind::Lockstep)
            | (Scope::PerCrate, TagKind::PerCrate)
    )
}

/// Build the rollback commit subject line. The tags list goes in the
/// body so a long per-crate batch doesn't blow past 72 chars. When
/// `dry_run` is true, the tag list is prefixed with "WOULD be" to
/// signal that the preview commit message describes pending (not
/// actually applied) state — otherwise a `--dry-run` printout reads
/// identically to a real-run one and fools the operator.
fn build_revert_message(target_sha: &str, deleted_tags: &[String], dry_run: bool) -> String {
    let primary = deleted_tags
        .iter()
        .find(|t| LOCKSTEP_TAG_RE.is_match(t))
        .cloned()
        .unwrap_or_else(|| {
            deleted_tags
                .first()
                .cloned()
                .unwrap_or_else(|| "release".to_string())
        });
    let short = if target_sha.len() > 7 {
        &target_sha[..7]
    } else {
        target_sha
    };
    let mut body = format!(
        "{} {primary} [skip ci]\n\nReverts {short}.",
        rollback_subject_prefix()
    );
    if !deleted_tags.is_empty() {
        let label = if dry_run {
            "Tags that WOULD be deleted"
        } else {
            "Tags deleted"
        };
        body.push_str(&format!("\n{label}: {}", deleted_tags.join(", ")));
    }
    body
}

/// Subject prefix of anodize's own rollback commits
/// (`chore(release): rollback …`), composed from the shared
/// release-machinery prefix so the writer ([`build_revert_message`]) and
/// the safety-check matcher below can never drift apart.
fn rollback_subject_prefix() -> String {
    format!("{}rollback", git::RELEASE_COMMIT_PREFIX)
}

/// Prefix that a plain `git revert` of an anodize release-machinery commit
/// produces (the amend-failure window, where the custom rollback subject
/// was never applied). Used by the rollback safety check to recognise its
/// own prior revert commit (so re-runs are idempotent) without absorbing
/// unrelated `Revert "<...>"` commits that GitHub's "Revert this PR"
/// button emits with arbitrary upstream subjects. Composed from the shared
/// prefix the bump/rollback writers stamp.
static ANODIZE_REVERT_SUBJECT_PREFIX: LazyLock<String> =
    LazyLock::new(|| format!("Revert \"{}", git::RELEASE_COMMIT_PREFIX));

pub fn run(opts: RollbackOpts) -> Result<()> {
    run_with_gh(opts, std::path::Path::new("gh"))
}

/// Path-taking sibling of [`run`]: `gh_binary` is the `gh` CLI used by
/// the published-state guard's GitHub-release fallback probe.
/// Production passes `Path::new("gh")` (PATH lookup); tests point at a
/// stub script so no global PATH mutation is needed (same seam
/// convention as `core::git::gh_api_get_with_binary`).
fn run_with_gh(opts: RollbackOpts, gh_binary: &std::path::Path) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let log = StageLogger::new(
        "tag-rollback",
        Verbosity::from_flags(opts.quiet, opts.verbose, opts.debug),
    );

    let raw_target = opts.sha.as_deref().unwrap_or("HEAD");
    let target_sha = git::rev_parse_in(&cwd, raw_target)?;
    log.kv(
        "target",
        &format!("{} ({})", raw_target, short(&target_sha)),
        "target".len(),
    );

    let all_tags_at_sha = git::get_tags_at_sha_in(&cwd, &target_sha)?;
    if all_tags_at_sha.is_empty() {
        log.warn(&format!("no tags found at {}", short(&target_sha)));
        bail!(
            "refusing to roll back: no tags point at {} — pass the bumped commit's SHA explicitly",
            short(&target_sha)
        );
    }

    let mut deletable: Vec<String> = Vec::new();
    for tag in &all_tags_at_sha {
        match classify_tag(tag) {
            None => log.status(&format!("skipped {tag} (not anodize-shaped)")),
            Some(kind) if !scope_includes(opts.scope, kind) => log.status(&format!(
                "skipped {tag} (scope filter --scope={:?})",
                opts.scope
            )),
            Some(_) => deletable.push(tag.clone()),
        }
    }

    if deletable.is_empty() {
        log.warn(&format!(
            "no anodize-managed tags at {} match --scope={:?}",
            short(&target_sha),
            opts.scope
        ));
        return Ok(());
    }

    // Published-state guard, BEFORE any mutation (including dry-run,
    // so the preview reports the same refusal the real run would).
    // A one-way-door (Submitter) publisher that landed for one of these
    // tags burned the version: registries like crates.io / chocolatey /
    // winget / snapcraft never accept the same version twice, so
    // deleting the tag + reverting the bump can never lead to a clean
    // same-version re-cut — only to an orphaned live release.
    // Tags whose GitHub release this rollback owns (a run summary attributes
    // them to the attempt being rolled back, or --force overrode the guard).
    // Only these get their release deleted; an unattributed tag's release is
    // preserved (it may be a human's draft or a prior reversible release).
    let attributed: std::collections::HashSet<String> = if opts.force {
        log.warn("skipped the published-state guard — --force");
        deletable.iter().cloned().collect()
    } else {
        // Fail-closed config load: the config drives the dist-dir resolution
        // for run summaries and the tag→crate mapping for the crates.io index
        // probe. A missing or unparseable config would blind the probe — the
        // exact failure mode the guard exists to prevent — so it refuses
        // instead of silently narrowing the evidence (a network error already
        // refuses; a config error must not be weaker). The probe itself
        // reuses the publish stage's sparse-index client so rollback and
        // publish can never disagree about what "published on crates.io"
        // means.
        let repo_config = match crate::pipeline::load_repo_config(&cwd) {
            Ok(config) => config,
            Err(e) => bail!(
                "refusing to roll back — could not load the anodizer config: {e:#}\n\
                 The published-state guard needs the config to map the tag(s) to crates \
                 for the crates.io burn probe; without that mapping there is no proof the \
                 version(s) are safe to destroy — a prior run may have burned them on a \
                 one-way-door registry. Fix the config, or run from a checkout whose \
                 config parses (e.g. the directory that contains it). As a last resort, \
                 --force skips ALL published-state checks (run summaries, crates.io, \
                 GitHub releases), not just this config probe — use it only if you are \
                 certain nothing irreversible shipped."
            ),
        };
        // Guard probes get their own shallow retry ladder (GUARD_PROBE:
        // 3 attempts, 30s cap) instead of the run's configured publish
        // ladder: a multi-crate workspace probes many registry endpoints in
        // one pass, and a registry outage must fail the guard closed in
        // seconds-to-minutes, not burn a full ~25-minute backoff budget per
        // crate first.
        let probe_policy = anodizer_core::retry::RetryPolicy::GUARD_PROBE;
        let index_probe = |name: &str, version: &str| {
            anodizer_stage_publish::cargo::published_on_crates_io(
                name,
                version,
                &probe_policy,
                &log,
            )
        };
        let winget_token = winget_probe_token(&anodizer_core::ProcessEnvSource);
        let choco_probe = |package: &str, version: &str| {
            anodizer_stage_publish::post_publish::chocolatey::version_blocked_on_gallery(
                "https://community.chocolatey.org",
                package,
                version,
                &log,
            )
        };
        let winget_probe = |spec: &WingetProbeSpec| {
            anodizer_stage_publish::post_publish::winget::version_pr_blocking(
                "https://api.github.com",
                &spec.upstream,
                &spec.package_id,
                &spec.version,
                spec.search_in_title,
                winget_token.as_deref(),
                &log,
            )
        };
        let probes = BurnProbes {
            crates_io: &index_probe,
            chocolatey: &choco_probe,
            winget: &winget_probe,
        };
        let unsummarized = check_not_irreversibly_published(
            &cwd,
            gh_binary,
            &deletable,
            &repo_config,
            &probes,
            &log,
        )?;
        deletable
            .iter()
            .filter(|t| !unsummarized.contains(t))
            .cloned()
            .collect()
    };

    // Safety check (--mode=revert only). Non-bump commits on top of
    // the target SHA mean someone landed unrelated work since the
    // bump; reverting blindly would lose it. Tolerate only anodize's
    // OWN prior revert commit so re-runs are idempotent — a generic
    // `"Revert "<...>"` prefix would silently absorb GitHub's
    // "Revert this PR" button output (e.g. an unrelated feature
    // revert) and disable the safety net.
    if opts.mode == Mode::Revert {
        let intervening = git::commits_with_subjects_in(&cwd, &target_sha)?;
        let mut suspicious: Vec<(String, String)> = Vec::new();
        for (sha, subject) in &intervening {
            if subject.starts_with(ANODIZE_REVERT_SUBJECT_PREFIX.as_str())
                || subject.starts_with(&rollback_subject_prefix())
            {
                continue;
            }
            suspicious.push((sha.clone(), subject.clone()));
        }
        if !suspicious.is_empty() {
            let mut msg = format!(
                "cannot rollback — {} non-bump commit(s) sit between HEAD and {}:\n",
                suspicious.len(),
                short(&target_sha)
            );
            for (sha, subj) in &suspicious {
                msg.push_str(&format!("  {} {}\n", short(sha), subj));
            }
            msg.push_str("resolve manually, or use --mode=reset to force.");
            bail!("{msg}");
        }
    }

    // Local mutation runs FIRST so a failed revert / reset leaves the
    // remote tags intact. Operator can retry without staring down a
    // half-rolled-back remote (tag gone) + intact local (tag still
    // present + bump commit still HEAD). Per-tag remote delete happens
    // after the local mutation succeeds — if a single remote-delete
    // glitches, the revert is already on disk and ready to push.

    // Mode=reset short-circuits revert+push entirely. Print a loud
    // warning so the operator knows they own the force-push.
    if opts.mode == Mode::Reset {
        let parent = format!("{}~1", target_sha);
        if opts.dry_run {
            log.status(&format!(
                "(dry-run) would run: git reset --hard {} (parent of bump commit)",
                short(&target_sha)
            ));
        } else {
            git::reset_hard_in(&cwd, &parent)?;
            log.status(&format!(
                "reset HEAD to {} (parent of bump commit)",
                short(&target_sha)
            ));
        }
        delete_tags(&cwd, gh_binary, &deletable, &attributed, &opts, &log);
        log.warn(
            "--mode=reset rewrote local history. Push with \
             `git push --force-with-lease origin <branch>` when ready.",
        );
        return Ok(());
    }

    // Mode=revert: create the revert commit, PUSH it, then delete tags.
    // Push precedes the remote tag delete so a push failure (e.g. a
    // non-fast-forward) leaves the tags intact and the rollback safely
    // retryable — never a tag-deleted-but-commit-unpushed limbo. The commit
    // message lists the tags that WILL be deleted (or under --dry-run, that
    // WOULD be deleted).
    let message = build_revert_message(&target_sha, &deletable, opts.dry_run);
    if opts.dry_run {
        log.status(&format!(
            "(dry-run) would run: git revert --no-edit {} && git commit --amend -m {:?}",
            short(&target_sha),
            message
        ));
    } else {
        let identity = git::resolve_rollback_identity(&cwd);
        git::revert_commit_in(&cwd, &target_sha, Some(&message), &identity)?;
        log.status(&format!("created revert commit {}", first_line(&message)));
    }

    if opts.no_push {
        delete_tags(&cwd, gh_binary, &deletable, &attributed, &opts, &log);
        log.status("skipped branch push — --no-push");
        return Ok(());
    }
    let branch = resolve_push_branch(&cwd, &target_sha, opts.branch.as_deref())?;
    if opts.dry_run {
        log.status(&format!("(dry-run) would run: git push origin {branch}"));
        delete_tags(&cwd, gh_binary, &deletable, &attributed, &opts, &log);
    } else {
        // Push BEFORE deleting remote tags: the destructive tag delete is the
        // last step, so a push failure aborts before any tag is dropped.
        git::push_branch_in(&cwd, &branch)?;
        log.status(&format!("pushed revert to origin/{branch}"));
        delete_tags(&cwd, gh_binary, &deletable, &attributed, &opts, &log);
    }
    Ok(())
}

/// Per-tag delete pass: warn-and-continue per tag so a single
/// remote-delete glitch doesn't abandon the surrounding mutation.
/// `dry_run` short-circuits to a status line per tag; `no_push`
/// skips the remote leg.
///
/// The remote leg also deletes the GitHub release AT each tag in
/// `attributed` — the tags a run summary (or `--force`) ties to the attempt
/// being rolled back. A release the attempt owns is reversible state of the
/// aborted attempt; leaving it behind orphans it AND poisons future
/// unsummarized rollbacks, whose burn-evidence probe would read the orphan as
/// proof a prior release shipped. A tag NOT in `attributed` keeps any release
/// it carries (it may be a human's draft or a prior reversible release) — that
/// state is never destroyed. When an owned release cannot be confirmed gone,
/// the tag is KEPT (both remote and local) so the rollback stays retryable
/// rather than orphaning the release under a deleted tag.
fn delete_tags(
    cwd: &std::path::Path,
    gh_binary: &std::path::Path,
    deletable: &[String],
    attributed: &std::collections::HashSet<String>,
    opts: &RollbackOpts,
    log: &StageLogger,
) {
    for tag in deletable {
        if opts.dry_run {
            if !opts.no_push {
                if attributed.contains(tag) {
                    log.status(&format!(
                        "(dry-run) would delete the GitHub release at {tag} (if one exists)"
                    ));
                } else {
                    log.status(&format!(
                        "(dry-run) would keep any GitHub release at {tag} \
                         (not attributed to this rollback)"
                    ));
                }
            }
            log.status(&format!("(dry-run) would delete tag {tag} (remote+local)"));
            continue;
        }
        if !opts.no_push {
            match delete_release_at_tag(cwd, gh_binary, tag, attributed.contains(tag), log) {
                ReleaseCleanup::Cleared => {}
                ReleaseCleanup::Retained => {
                    log.warn(&format!(
                        "keeping tag {tag} — its GitHub release could not be removed; \
                         deleting the tag now would orphan the release under a missing tag. \
                         The rollback stays retryable: re-run once the release is gone."
                    ));
                    continue;
                }
            }
            match git::delete_remote_tag_in(cwd, tag) {
                Ok(()) => log.status(&format!("deleted remote tag {tag}")),
                Err(e) => log.warn(&format!(
                    "remote tag delete failed for {tag}: {e} (continuing)"
                )),
            }
        } else {
            log.status(&format!("skipped remote delete for {tag} — --no-push"));
        }
        match git::delete_local_tag_in(cwd, tag) {
            Ok(()) => log.status(&format!("deleted local tag {tag}")),
            Err(e) => log.warn(&format!(
                "local tag delete failed for {tag}: {e} (continuing)"
            )),
        }
    }
}

/// Whether the tag delete may proceed after the release-cleanup attempt.
enum ReleaseCleanup {
    /// No release remained that this rollback owns — none existed, it was an
    /// unattributed release deliberately left in place, or an owned one was
    /// deleted. Safe to drop the tag.
    Cleared,
    /// An owned release may still exist (its delete failed, or the lookup was
    /// inconclusive). Keep the tag so the rollback stays retryable rather than
    /// orphaning the release under a deleted tag.
    Retained,
}

/// Clean up the GitHub release at `tag` for a rollback.
///
/// `attributed` is true when a run summary ties this tag to the attempt being
/// rolled back (or `--force` overrode the guard): only then is the release
/// deleted, because only then does anodize know the release belongs to the
/// aborted attempt. For an UNATTRIBUTED tag any release is left in place — it
/// may be a human's draft notes or a prior reversible release, and rollback
/// must never destroy state it cannot attribute.
///
/// Warn-and-continue on every failure. Silently inapplicable (verbose-only
/// note) when origin is not a github.com remote. Returns
/// [`ReleaseCleanup::Retained`] when an owned release could not be confirmed
/// gone, so the caller keeps the tag instead of orphaning the release.
fn delete_release_at_tag(
    cwd: &std::path::Path,
    gh_binary: &std::path::Path,
    tag: &str,
    attributed: bool,
    log: &StageLogger,
) -> ReleaseCleanup {
    let (owner, repo) = match git::resolve_github_slug_in(None, None, cwd) {
        Ok(slug) => (slug.owner().to_string(), slug.name().to_string()),
        Err(_) => {
            log.verbose(&format!(
                "skipped GitHub release cleanup for {tag} — origin is not a github.com remote"
            ));
            return ReleaseCleanup::Cleared;
        }
    };
    let endpoint = format!("/repos/{owner}/{repo}/releases/tags/{tag}");
    let release_id = match git::gh_api_get_with_binary(gh_binary, &endpoint, None) {
        Ok(v) => v.get("id").and_then(serde_json::Value::as_u64),
        Err(e) => {
            let msg = e.to_string();
            if msg.contains("HTTP 404") || msg.contains("Not Found") {
                log.verbose(&format!(
                    "no GitHub release exists at {tag} — nothing to clean up"
                ));
                return ReleaseCleanup::Cleared;
            }
            // A non-404 lookup failure is inconclusive: an owned release might
            // still exist. Keep the tag for an attributed rollback so we never
            // orphan it; an unattributed tag's release was never ours to delete.
            log.warn(&format!(
                "could not look up the GitHub release at {tag} for cleanup: {msg} (continuing)"
            ));
            return if attributed {
                ReleaseCleanup::Retained
            } else {
                ReleaseCleanup::Cleared
            };
        }
    };
    let Some(id) = release_id else {
        if attributed {
            log.warn(&format!(
                "GitHub release lookup for {tag} returned no numeric id — keeping the tag so \
                 the rollback stays retryable (delete the release manually at \
                 https://github.com/{owner}/{repo}/releases/tag/{tag} if one exists)"
            ));
            return ReleaseCleanup::Retained;
        }
        return ReleaseCleanup::Cleared;
    };
    if !attributed {
        // A release exists but no run evidence attributes it to the attempt
        // being rolled back — never destroy unattributed state. Flag it and let
        // the tag delete proceed; the release simply becomes untagged.
        log.warn(&format!(
            "a GitHub release exists at {tag} but no run summary attributes it to this \
             rollback — leaving it in place. Delete it manually if intended: \
             https://github.com/{owner}/{repo}/releases/tag/{tag}"
        ));
        return ReleaseCleanup::Cleared;
    }
    let delete_endpoint = format!("/repos/{owner}/{repo}/releases/{id}");
    match git::gh_api_delete_with_binary(gh_binary, &delete_endpoint, None) {
        Ok(()) => {
            log.status(&format!(
                "deleted the GitHub release at {tag} (it belonged to the rolled-back attempt)"
            ));
            ReleaseCleanup::Cleared
        }
        Err(e) => {
            log.warn(&format!(
                "GitHub release delete failed for {tag}: {e:#} (keeping the tag so the \
                 rollback stays retryable — re-run once the release is gone, or delete it \
                 manually at https://github.com/{owner}/{repo}/releases/tag/{tag})"
            ));
            ReleaseCleanup::Retained
        }
    }
}

/// Resolve the branch to push the revert commit to.
///
/// Resolution order:
/// 1. `--branch` flag wins unconditionally.
/// 2. SHA-derivation: `git branch -r --contains <bump_sha>`. The bump
///    SHA is the deterministic anchor of the just-rolled-back tag,
///    so it's race-immune to the default branch moving between bump
///    and rollback. Exactly one remote branch → use it. Multiple →
///    require `--branch` to disambiguate.
/// 3. Fallback to [`git::get_current_branch_in`] for repos with no
///    remote (local-only rollback workflows).
fn resolve_push_branch(
    cwd: &std::path::Path,
    bump_sha: &str,
    explicit: Option<&str>,
) -> Result<String> {
    resolve_push_branch_with_env(cwd, bump_sha, explicit, &anodizer_core::ProcessEnvSource)
}

/// [`resolve_push_branch`] with the env source injected so the
/// detached-HEAD `GITHUB_REF_NAME` fallback can be driven from a
/// [`MapEnvSource`](anodizer_core::MapEnvSource) in tests rather than
/// mutating the real process environment.
fn resolve_push_branch_with_env<E: anodizer_core::EnvSource + ?Sized>(
    cwd: &std::path::Path,
    bump_sha: &str,
    explicit: Option<&str>,
    env: &E,
) -> Result<String> {
    if let Some(b) = explicit {
        return Ok(b.to_string());
    }
    if let Ok(branches) = git::branches_containing_sha_in(cwd, bump_sha) {
        // Drive off the slice directly so the single-branch case needs no
        // `.expect()` on a re-derived `next()`: `[only]` binds the one branch
        // by value, `[_, ..]` (2+) is the ambiguous case, `[]` falls through
        // to the HEAD-resolution fallback below.
        match branches.as_slice() {
            [only] => return Ok(only.clone()),
            [_, ..] => bail!(
                "bump commit {} is reachable from {} remote branches: {}.\n\
                 pass --branch <name> to disambiguate.",
                &bump_sha[..bump_sha.len().min(12)],
                branches.len(),
                branches.join(", ")
            ),
            [] => {}
        }
    }
    match git::get_current_branch_in_with_env(cwd, env) {
        Ok(b) => Ok(b),
        Err(_) => bail!(
            "cannot determine branch for revert push — bump commit {} is \
             not reachable from any remote branch and HEAD resolution failed.\n\
             pass --branch <name> explicitly.",
            &bump_sha[..bump_sha.len().min(12)]
        ),
    }
}

/// Registry probes the published-state guard consults, injected as seams so
/// tests can script registry state without a network (same convention as
/// `gh_binary`).
///
/// Production wiring:
/// - `crates_io` — [`anodizer_stage_publish::cargo::published_on_crates_io`]:
///   `(crate, version) -> published?`. Fail-CLOSED evidence: an `Err` refuses
///   rollback.
/// - `chocolatey` —
///   [`anodizer_stage_publish::post_publish::chocolatey::version_blocked_on_gallery`]:
///   `(package id, version) -> Some(blocking state)`. Advisory: an `Err`
///   warns and proceeds (fail open).
/// - `winget` —
///   [`anodizer_stage_publish::post_publish::winget::version_pr_blocking`]:
///   `WingetProbeSpec -> Some(blocking state)`. Advisory, fail open like
///   `chocolatey`.
struct BurnProbes<'a> {
    crates_io: &'a (dyn Fn(&str, &str) -> Result<bool> + Sync),
    chocolatey: &'a (dyn Fn(&str, &str) -> Result<Option<String>> + Sync),
    winget: &'a (dyn Fn(&WingetProbeSpec) -> Result<Option<String>> + Sync),
}

/// Coordinates of one winget burn probe, resolved from the crate's
/// `publish.winget` block the same way the publisher resolves its submission
/// target.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct WingetProbeSpec {
    /// `<owner>/<repo>` the manifest PR targets
    /// ([`anodizer_stage_publish::winget::resolve_winget_upstream`]).
    upstream: String,
    package_id: String,
    version: String,
    /// Whether the search may keep GitHub's `in:title` qualifier: true only
    /// for the default PR-title format — a custom `commit_msg_template`
    /// makes the title unpredictable, so the search widens to title+body.
    search_in_title: bool,
}

/// Ambient GitHub token for the winget burn probe, read through the injected
/// env source. The probe is a read-only public search that works
/// anonymously; the token only buys a higher rate limit.
fn winget_probe_token<E: anodizer_core::EnvSource + ?Sized>(env: &E) -> Option<String> {
    anodizer_core::git::resolve_github_token_with_env(None, &|key| env.var(key))
}

/// Concurrency bound for registry burn probes: a large workspace must not
/// open dozens of simultaneous connections against an already-struggling
/// registry.
const MAX_PROBE_WORKERS: usize = 8;

/// One pending moderated-registry probe, collected up front so the network
/// round-trips can run on the shared bounded pool.
enum ModeratedProbe {
    Chocolatey {
        tag: String,
        id: String,
        version: String,
    },
    Winget {
        tag: String,
        spec: WingetProbeSpec,
    },
}

/// Refuse rollback when any tag's configured chocolatey / winget package is
/// already visible on those registries at the tag's version. Both are true
/// one-way doors (a moderation queue submission or a merged manifest PR
/// blocks re-submitting the same version), and a burn landed by another
/// runner leaves no local summary and no GitHub release — this probe is the
/// only evidence path that can see it.
///
/// Probes run ONLY for crates whose config carries the respective publisher
/// block, and only when the package id is resolvable without a template
/// context (a templated override warns and is skipped). A chocolatey block
/// whose `source_repo` targets a non-community feed is skipped too — private
/// feeds have no community moderation queue, so the gallery page carries no
/// signal for them. The winget probe searches the same upstream repository
/// the publisher would submit to. Unlike the crates.io
/// index probe, an unreachable registry here WARNS AND PROCEEDS (fail open):
/// these endpoints are a moderation-queue HTML page and the rate-limited
/// GitHub search API — flaky enough that failing closed would dead-end
/// legitimate recoveries on transient noise, and both registries' burn is
/// additionally covered by run-summary evidence when the publish ran on this
/// runner. Positive evidence still refuses outright, exactly like a
/// crates.io hit.
fn check_not_burned_on_moderated_registries(
    tags: &[String],
    config: &anodizer_core::config::Config,
    probes: &BurnProbes<'_>,
    log: &StageLogger,
) -> Result<()> {
    // Pass 1 — resolve every deduplicated probe up front so the network
    // round-trips can run concurrently on the shared bounded pool.
    let mut pending: Vec<ModeratedProbe> = Vec::new();
    let mut probed: std::collections::HashSet<(&'static str, String, String)> =
        std::collections::HashSet::new();
    for tag in tags {
        for (c, version) in crates_versioned_by_tag(config, tag) {
            if let Some(choco_cfg) = c.publish.as_ref().and_then(|p| p.chocolatey.as_ref()) {
                if !anodizer_stage_publish::chocolatey::targets_community_gallery(choco_cfg) {
                    // Only the community gallery has a moderation queue whose
                    // pending submissions consume a version; a private feed's
                    // state says nothing about the community page.
                    log.verbose(&format!(
                        "skipped the chocolatey gallery burn probe for crate '{}' — its \
                         push target '{}' is not the community gallery",
                        c.name,
                        anodizer_stage_publish::chocolatey::push_source(choco_cfg)
                    ));
                } else {
                    match anodizer_stage_publish::chocolatey::static_package_id(&c.name, choco_cfg)
                    {
                        Some(id) => {
                            if probed.insert(("chocolatey", id.clone(), version.clone())) {
                                pending.push(ModeratedProbe::Chocolatey {
                                    tag: tag.clone(),
                                    id,
                                    version: version.clone(),
                                });
                            }
                        }
                        None => log.warn(&format!(
                            "cannot resolve the chocolatey package id for crate '{}' without a \
                             release template context; skipping its gallery burn probe \
                             (advisory evidence only)",
                            c.name
                        )),
                    }
                }
            }
            if let Some(winget_cfg) = c.publish.as_ref().and_then(|p| p.winget.as_ref()) {
                match anodizer_stage_publish::winget::static_package_identifier(&c.name, winget_cfg)
                {
                    Some(id) => {
                        let (owner, repo) =
                            anodizer_stage_publish::winget::resolve_winget_upstream(winget_cfg);
                        let upstream = format!("{owner}/{repo}");
                        if probed.insert(("winget", format!("{upstream}#{id}"), version.clone())) {
                            pending.push(ModeratedProbe::Winget {
                                tag: tag.clone(),
                                spec: WingetProbeSpec {
                                    upstream,
                                    package_id: id,
                                    version: version.clone(),
                                    search_in_title: winget_cfg.commit_msg_template.is_none(),
                                },
                            });
                        }
                    }
                    None => log.warn(&format!(
                        "cannot resolve the winget package identifier for crate '{}' \
                         without a release template context; skipping its manifest-PR burn \
                         probe (advisory evidence only)",
                        c.name
                    )),
                }
            }
        }
    }
    // Pass 2 — probe the registries concurrently. A worker panic surfaces as
    // an attributed error; per-probe failures stay wrapped so one flaky
    // endpoint cannot abort its siblings.
    let results = anodizer_core::parallel::run_parallel_chunks(
        &pending,
        MAX_PROBE_WORKERS,
        "moderated-registry burn probe",
        log,
        |probe| {
            Ok(match probe {
                ModeratedProbe::Chocolatey { id, version, .. } => (probes.chocolatey)(id, version),
                ModeratedProbe::Winget { spec, .. } => (probes.winget)(spec),
            })
        },
    )?;
    // Pass 3 — classify in the deterministic pass-1 order.
    let mut burned: Vec<String> = Vec::new();
    for (probe, result) in pending.iter().zip(results) {
        match probe {
            ModeratedProbe::Chocolatey { tag, id, version } => match result {
                Ok(Some(state)) => burned.push(format!(
                    "  {tag}: chocolatey package '{id}@{version}' — {state}"
                )),
                Ok(None) => log.status(&format!(
                    "chocolatey has never seen '{id}@{version}' — {tag} \
                     carries no chocolatey one-way door"
                )),
                Err(e) => log.warn(&format!(
                    "could not consult the chocolatey gallery for \
                     '{id}@{version}' ({e:#}); proceeding — this probe is \
                     advisory evidence, and run summaries / crates.io / \
                     GitHub releases still guard the rollback"
                )),
            },
            ModeratedProbe::Winget { tag, spec } => match result {
                Ok(Some(state)) => burned.push(format!(
                    "  {tag}: winget package '{}' at {}{state}",
                    spec.package_id, spec.version
                )),
                Ok(None) => log.status(&format!(
                    "{} carries no blocking manifest PR for '{} {}' — {tag} \
                     carries no winget one-way door",
                    spec.upstream, spec.package_id, spec.version
                )),
                Err(e) => log.warn(&format!(
                    "could not search {} for '{} {}' ({e:#}); proceeding — this \
                     probe is advisory evidence, and run summaries / crates.io / \
                     GitHub releases still guard the rollback",
                    spec.upstream, spec.package_id, spec.version
                )),
            },
        }
    }
    if !burned.is_empty() {
        return Err(RollbackRefusal {
            reason: format!(
                "these version(s) are already consumed at a moderated one-way-door registry \
                 (submitted by a prior attempt, whatever this run's summaries say):\n{}\n\
                 Those registries never accept the same version twice — a pending \
                 submission blocks a re-push just like an accepted one — so deleting the \
                 tag(s) cannot lead to a clean same-version re-cut — tags kept to protect \
                 the published state.",
                burned.join("\n")
            ),
            next_step: refusal_next_step(),
        }
        .into());
    }
    Ok(())
}

/// Refuse rollback when the version is already burned at a one-way-door
/// (Submitter group) publisher, by evidence strength:
///
/// 1. Run summaries on disk (`<dist>/run-*/summary.json`, plus
///    `<dist>/<crate>/run-*/summary.json` in per-crate workspaces)
///    whose `tag` matches a tag about to be deleted — the
///    per-publisher truth written by the release run itself, including
///    failed runs. A summary that shows a landed Submitter REFUSES.
/// 2. The crates.io sparse index, for every tag that maps (via the repo
///    config's crate tag families) to a crates.io-targeting crate. The
///    run summary answers a PER-RUN question; whether a version is
///    burned on a one-way-door registry is GLOBAL state — a PRIOR run
///    may have published it, and that run's summary lives on another
///    runner. A version live on the index REFUSES even when this run's
///    summary is clean; an unreachable index FAILS CLOSED (publication
///    state unverifiable). A tag that maps to NO crate while the config
///    publishes to crates.io also fails closed (the mapping is the
///    probe's eyes); a tag whose mapped crates simply don't target
///    crates.io carries no cargo one-way door and proceeds.
/// 3. Only for tags with no matching summary (e.g. a fresh checkout
///    that never ran the release): fall back to probing the GitHub
///    Releases API for a published (non-draft) release at the tag.
///
/// Only a tag that clears every applicable layer is rolled back;
/// reversible-only evidence (github-release assets, blobs,
/// tap/bucket/index commits) permits rollback because their state can
/// be deleted and the same version re-cut.
///
/// Alongside layer 2, the configured moderated registries (chocolatey,
/// winget) are probed as advisory evidence via
/// [`check_not_burned_on_moderated_registries`]: positive evidence refuses
/// like a crates.io hit, but an unreachable registry warns and proceeds.
///
/// `probes` carries the injected registry probes ([`BurnProbes`]) —
/// production wires the stage-publish probe functions; tests inject stubs
/// (same seam convention as `gh_binary`).
///
/// On success returns the subset of `tags` that had NO matching run summary
/// (the "unattributed" tags). The caller uses that to decide release cleanup:
/// a summarized tag's GitHub release belongs to the run being rolled back and
/// may be deleted, while an unattributed tag's release is left untouched.
fn check_not_irreversibly_published(
    cwd: &std::path::Path,
    gh_binary: &std::path::Path,
    tags: &[String],
    repo_config: &anodizer_core::config::Config,
    probes: &BurnProbes<'_>,
    log: &StageLogger,
) -> Result<Vec<String>> {
    let summaries = collect_run_summaries(&resolve_dist_dir(cwd, repo_config), log);
    let mut burned: Vec<(String, Vec<String>)> = Vec::new();
    let mut unsummarized: Vec<String> = Vec::new();
    for tag in tags {
        let matching: Vec<_> = summaries.iter().filter(|s| s.tag == *tag).collect();
        if matching.is_empty() {
            unsummarized.push(tag.clone());
            continue;
        }
        let mut names: Vec<String> = matching
            .iter()
            .flat_map(|s| s.burned_submitter_names())
            .collect();
        names.sort();
        names.dedup();
        // `irreversibly_published` is the precomputed verdict;
        // `burned_submitter_names` additionally catches summaries
        // written before the flag existed.
        if matching.iter().any(|s| s.irreversibly_published) || !names.is_empty() {
            burned.push((tag.clone(), names));
        } else {
            log.status(&format!(
                "no one-way-door publisher landed for {tag} per this run's summary"
            ));
        }
    }
    if !burned.is_empty() {
        let detail = burned
            .iter()
            .map(|(tag, names)| {
                if names.is_empty() {
                    format!("  {tag}: run summary records an irreversible publish")
                } else {
                    format!("  {tag}: version burned at {}", names.join(", "))
                }
            })
            .collect::<Vec<_>>()
            .join("\n");
        return Err(RollbackRefusal {
            reason: format!(
                "one-way-door publisher(s) already accepted these version(s):\n\
                 {detail}\n\
                 Those registries never accept the same version twice, so deleting the \
                 tag(s) and reverting the bump cannot lead to a clean same-version re-cut \
                 — tags kept to protect the published state."
            ),
            next_step: refusal_next_step(),
        }
        .into());
    }
    check_not_burned_on_crates_io(tags, &unsummarized, repo_config, probes.crates_io, log)?;
    check_not_burned_on_moderated_registries(tags, repo_config, probes, log)?;
    if unsummarized.is_empty() {
        return Ok(unsummarized);
    }
    check_no_published_releases(cwd, gh_binary, &unsummarized, log)?;
    Ok(unsummarized)
}

/// Dist-dir resolution for the published-state guard: the repo config's
/// `dist:`. Relative values anchor at `cwd`.
fn resolve_dist_dir(
    cwd: &std::path::Path,
    repo_config: &anodizer_core::config::Config,
) -> std::path::PathBuf {
    let dist = repo_config.dist.clone();
    if dist.is_absolute() {
        dist
    } else {
        cwd.join(dist)
    }
}

/// How a tag maps onto the config's crate universe for the crates.io burn
/// probe. The split lets the guard distinguish "nothing to probe because
/// none of the tag's crates target crates.io" (safe to proceed) from
/// "the tag maps to no crate at all" (the probe is blind — fail closed
/// when the config publishes to crates.io elsewhere).
struct TagCrateMapping {
    /// `(crate name, version)` pairs the tag stamps on crates.io.
    probes: Vec<(String, String)>,
    /// Crates whose tag family matched but which don't publish to
    /// crates.io (no `publish.cargo` block, or a custom `registry:`/
    /// `index:` target outside the probe's scope).
    matched_non_crates_io: usize,
}

/// Resolve the `(crate name, version)` pairs a tag stamps on crates.io, per
/// the repo config: every crate whose `publish.cargo` block targets
/// crates.io (per the publisher's own [`targets_crates_io`] judgment —
/// custom `registry:`/`index:` targets are out of the probe's scope) and
/// whose tag family prefix (from its `tag_template`, monorepo prefix
/// stripped) matches the tag. Per-crate tags (`crd-v0.5.0`) resolve to
/// their own crate — note the tag prefix is the template's, NOT the crate
/// name (cfgd's `crd-v...` family belongs to the crate `cfgd-crd`);
/// lockstep tags (every crate sharing the bare `v...` family) resolve to
/// every such crate.
///
/// Publish-time `skip:`/`if:` gating is deliberately NOT evaluated (no
/// template context exists in a rollback): a gated crate may be probed even
/// though the release never publishes it, which can only tighten the guard
/// (`--force` remains the escape hatch), never loosen it.
///
/// [`targets_crates_io`]: anodizer_stage_publish::cargo::targets_crates_io
fn crates_io_versions_for_tag(
    config: &anodizer_core::config::Config,
    tag: &str,
) -> TagCrateMapping {
    let mut mapping = TagCrateMapping {
        probes: Vec::new(),
        matched_non_crates_io: 0,
    };
    for (c, version) in crates_versioned_by_tag(config, tag) {
        match c.publish.as_ref().and_then(|p| p.cargo.as_ref()) {
            Some(cargo_cfg)
                if anodizer_stage_publish::cargo::targets_crates_io(Some(cargo_cfg)) =>
            {
                mapping.probes.push((c.name.clone(), version));
            }
            _ => mapping.matched_non_crates_io += 1,
        }
    }
    mapping
}

/// Resolve which crates a tag versions, per the repo config's crate tag
/// families: every crate whose tag family prefix (from its `tag_template`,
/// monorepo prefix stripped) matches the tag, paired with the semver the tag
/// stamps on it. Shared by every registry-specific burn probe so the tag →
/// crate judgment exists exactly once. Works across all three layouts:
/// single-crate and lockstep tags (`v0.5.0`) match every crate sharing the
/// bare family; per-crate tags (`crd-v0.5.0`) match their own crate only.
fn crates_versioned_by_tag<'c>(
    config: &'c anodizer_core::config::Config,
    tag: &str,
) -> Vec<(&'c anodizer_core::config::CrateConfig, String)> {
    let stripped = match config.monorepo_tag_prefix() {
        Some(prefix) => git::strip_monorepo_prefix(tag, prefix),
        None => tag,
    };
    let mut out = Vec::new();
    for c in config.crate_universe() {
        let prefix = git::per_crate_tag_prefix(&c.name, &c.tag_template);
        let Some(version) = stripped.strip_prefix(&prefix) else {
            continue;
        };
        if git::parse_semver(version).is_err() {
            continue;
        }
        out.push((c, version.to_string()));
    }
    out
}

/// Layer 2 of [`check_not_irreversibly_published`]: refuse rollback when
/// any tag's crates.io-targeting crate@version is live on the crates.io
/// sparse index — GLOBAL registry state, consulted regardless of what this
/// run's summaries say (a prior run may have burned the version; its
/// summary lives on another runner's disk).
///
/// - version on the index → REFUSE (burned; fix forward).
/// - index unreachable → REFUSE (fail closed: publication state is
///   unverifiable, and gambling a destructive delete on a transient outage
///   is the poison-guard anti-pattern). `--force` is the operator escape.
/// - tag maps to NO crate while the config publishes to crates.io →
///   REFUSE (fail closed: the tag→crate mapping is the probe's eyes; a
///   tag it cannot map might version a crate that IS burned).
/// - tag maps only to crates that don't target crates.io, or the config
///   publishes nothing to crates.io at all → proceed: there is no cargo
///   one-way door for this config to have burned.
///
/// Repeated `crate@version` probes are deduplicated (the same pair recurs
/// under `Scope::All` when tag families overlap, e.g. a monorepo-prefixed
/// and a bare tag resolving to the same crate).
fn check_not_burned_on_crates_io(
    tags: &[String],
    unsummarized: &[String],
    config: &anodizer_core::config::Config,
    index_probe: &(dyn Fn(&str, &str) -> Result<bool> + Sync),
    log: &StageLogger,
) -> Result<()> {
    let config_targets_crates_io = config.crate_universe().iter().any(|c| {
        c.publish
            .as_ref()
            .and_then(|p| p.cargo.as_ref())
            .is_some_and(|cfg| anodizer_stage_publish::cargo::targets_crates_io(Some(cfg)))
    });
    if !config_targets_crates_io {
        log.status(
            "no crate in the config publishes to crates.io — no cargo one-way door to probe",
        );
        return Ok(());
    }
    let mut burned: Vec<String> = Vec::new();
    let mut squat_suspect_crates: Vec<String> = Vec::new();
    let mut indeterminate: Vec<String> = Vec::new();
    let mut unmapped: Vec<String> = Vec::new();
    let mut probed: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
    // Pass 1 — resolve every tag's deduplicated `(tag, crate, version)`
    // probe set up front so the network round-trips can run concurrently.
    let mut pending: Vec<(String, String, String)> = Vec::new();
    for tag in tags {
        let mapping = crates_io_versions_for_tag(config, tag);
        if mapping.probes.is_empty() {
            if mapping.matched_non_crates_io > 0 {
                log.status(&format!(
                    "no crates.io-targeting crate is versioned by {tag} — no cargo \
                     one-way door to probe"
                ));
            } else {
                unmapped.push(format!("  {tag}"));
            }
            continue;
        }
        for (name, version) in mapping.probes {
            if !probed.insert((name.clone(), version.clone())) {
                continue;
            }
            pending.push((tag.clone(), name, version));
        }
    }
    // Pass 2 — probe the index concurrently: a 20-crate lockstep workspace
    // must not serialize 20 network ladders during a registry outage. Each
    // probe's own Result is wrapped so a failed probe (fail-closed evidence,
    // classified below) doesn't abort its in-flight siblings; a worker panic
    // surfaces as an attributed error.
    let results = anodizer_core::parallel::run_parallel_chunks(
        &pending,
        MAX_PROBE_WORKERS,
        "crates.io burn probe",
        log,
        |(_, name, version)| Ok(index_probe(name, version)),
    )?;
    // Pass 3 — classify in the deterministic pass-1 order, so the operator
    // output is stable regardless of probe completion order.
    for ((tag, name, version), result) in pending.iter().zip(results) {
        match result {
            Ok(true) => {
                if unsummarized.contains(tag) && !squat_suspect_crates.contains(name) {
                    squat_suspect_crates.push(name.clone());
                }
                burned.push(format!("  {tag}: {name}@{version}"));
            }
            Ok(false) => log.status(&format!(
                "'{name}@{version}' is not on the crates.io index — {tag} carries no \
                 cargo one-way door"
            )),
            Err(e) => indeterminate.push(format!("  {tag}: {name}@{version} ({e:#})")),
        }
    }
    if !burned.is_empty() {
        // A local run summary is per-runner and ephemeral: a fresh CI runner
        // holds no summary for a burn a prior runner landed, so its absence
        // is expected for a legitimate own-publish and is NOT evidence of
        // foreign ownership. The note leads with that likely case and offers
        // the crates.io page only so the rare squatting possibility can be
        // ruled out — it never implies the version isn't the operator's own.
        let squat_note = if squat_suspect_crates.is_empty() {
            String::new()
        } else {
            let urls = squat_suspect_crates
                .iter()
                .map(|name| format!("https://crates.io/crates/{name}"))
                .collect::<Vec<_>>()
                .join(", ");
            format!(
                "\nNo local run summary corroborates this publish — most likely a prior \
                 run of yours (on CI, summaries live on each runner's disk and don't \
                 carry over); far less likely, the name is held by someone else. Confirm \
                 ownership at {urls} before assuming either."
            )
        };
        return Err(RollbackRefusal {
            reason: format!(
                "these version(s) are live on the crates.io index (published by a prior \
                 attempt, whatever this run's summaries say):\n{}\n\
                 crates.io never accepts the same version twice, so deleting the tag(s) \
                 cannot lead to a clean same-version re-cut — tags kept to protect the \
                 published state.{squat_note}",
                burned.join("\n")
            ),
            next_step: refusal_next_step(),
        }
        .into());
    }
    if !indeterminate.is_empty() {
        bail!(
            "refusing to roll back: the crates.io index could not be reached to verify \
             whether these version(s) are already published:\n{}\n\
             Without the index there is no proof the version(s) are safe to destroy — a \
             prior run may have burned them on crates.io. Restore network access and \
             retry, or pass --force if you are certain nothing irreversible shipped.",
            indeterminate.join("\n")
        );
    }
    if !unmapped.is_empty() {
        bail!(
            "refusing to roll back — could not map these tag(s) to any crate in the \
             anodizer config:\n{}\n\
             The crates.io burn probe works by mapping each tag's family (from the crates' \
             tag_template) to the crates it versions, and this config publishes crate(s) to \
             crates.io — a tag the probe cannot map might version a crate whose version is \
             already burned there, so proceeding blind is not safe. Check that the config's \
             crates/tag_template families cover these tag(s), or pass --force if you are \
             certain nothing irreversible shipped.",
            unmapped.join("\n")
        );
    }
    Ok(())
}

/// Collect every parseable run summary under `<dist>/run-*/summary.json`
/// (single-crate / lockstep layout) and `<dist>/<crate>/run-*/summary.json`
/// (per-crate workspace layout). Unreadable or unparseable files warn
/// and are skipped — they carry no usable evidence either way.
fn collect_run_summaries(
    dist: &std::path::Path,
    log: &StageLogger,
) -> Vec<anodizer_stage_publish::run_summary::RunSummary> {
    let mut out = Vec::new();
    for path in anodizer_stage_publish::run_summary::collect_run_summary_paths(dist) {
        match std::fs::read_to_string(&path)
            .map_err(anyhow::Error::from)
            .and_then(|text| Ok(serde_json::from_str(&text)?))
        {
            Ok(summary) => out.push(summary),
            Err(e) => log.warn(&format!(
                "ignoring unreadable run summary {}: {e:#}",
                path.display()
            )),
        }
    }
    out
}

/// Outcome of probing GitHub for a release at a tag.
#[derive(Debug)]
enum ReleaseProbe {
    /// A non-draft release exists — rollback must refuse.
    Published,
    /// No release, or only a draft (drafts are reversible).
    NotBlocking,
    /// The probe could not determine release state (gh missing, auth /
    /// network error, ...). The guard FAILS CLOSED on this: with a
    /// GitHub-shaped origin and no run summary, an unanswerable probe
    /// leaves a real possibility that a published release (and burned
    /// one-way-door versions behind it) exists — proceeding would
    /// gamble irreversible state on a transient outage. `--force` is
    /// the operator escape for genuinely-offline recovery.
    Indeterminate(String),
}

/// Probe the GitHub Releases API for a release at `tag`.
///
/// `gh_binary` is the path to the `gh` CLI; production passes
/// `Path::new("gh")` (PATH lookup), tests point at a stub script so no
/// global PATH mutation is needed.
fn probe_release_for_tag(
    gh_binary: &std::path::Path,
    owner: &str,
    repo: &str,
    tag: &str,
) -> ReleaseProbe {
    let endpoint = format!("/repos/{owner}/{repo}/releases/tags/{tag}");
    match git::gh_api_get_with_binary(gh_binary, &endpoint, None) {
        // Missing `draft` counts as published: an API response that
        // omits the field gives no proof the release is reversible.
        Ok(v) => match v.get("draft").and_then(serde_json::Value::as_bool) {
            Some(true) => ReleaseProbe::NotBlocking,
            Some(false) | None => ReleaseProbe::Published,
        },
        Err(e) => {
            let msg = e.to_string();
            // gh surfaces missing releases as `HTTP 404: Not Found`.
            if msg.contains("HTTP 404") || msg.contains("Not Found") {
                ReleaseProbe::NotBlocking
            } else {
                ReleaseProbe::Indeterminate(msg)
            }
        }
    }
}

/// Refuse rollback when any tag about to be deleted carries a
/// published (non-draft) GitHub release.
///
/// Fallback layer of [`check_not_irreversibly_published`], consulted
/// only for tags with no run summary on disk: a published release is
/// the strongest remaining signal that one-way-door publishers shipped
/// alongside it.
///
/// Indeterminate probes (gh CLI missing, auth / network errors other
/// than 404) FAIL CLOSED — refuse with the probe error and point at
/// `--force`: with no summary and no probe answer there is zero
/// evidence the version is safe to destroy. An unresolvable `origin`
/// remote (none configured, or git itself erroring) also fails closed
/// for the same reason. The single fail-OPEN bound: a resolvable
/// origin that is not `github.com`-shaped (GitLab / Gitea / file path /
/// GitHub Enterprise host) warns and proceeds — the probe targets the
/// github.com Releases API, which cannot host a release for such a
/// remote, so it carries no signal either way; run-summary evidence
/// (layer 1 of the guard) remains the only signal for those hosts.
fn check_no_published_releases(
    cwd: &std::path::Path,
    gh_binary: &std::path::Path,
    tags: &[String],
    log: &StageLogger,
) -> Result<()> {
    let (owner, repo) = match git::resolve_github_slug_in(None, None, cwd) {
        Ok(slug) => (slug.owner().to_string(), slug.name().to_string()),
        Err(e) if git::has_remote_in(cwd, "origin") => {
            // The slug resolver already redacts URL credentials in its
            // parse-failure message, so `e` is safe to surface.
            log.warn(&format!(
                "skipped the published-release probe — origin is not a github.com \
                 remote ({e}); no github.com release can exist there \
                 (run-summary evidence still applies)"
            ));
            return Ok(());
        }
        Err(e) => {
            bail!(
                "refusing to roll back: could not resolve the 'origin' remote to run the \
                 published-release guard ({e}).\n\
                 No run summary covers these tag(s) and without a remote there is no \
                 evidence the version(s) are safe to destroy. Configure the 'origin' \
                 remote and retry, or pass --force if you are certain nothing \
                 irreversible shipped.",
            );
        }
    };
    let mut published: Vec<&str> = Vec::new();
    let mut indeterminate: Vec<(&str, String)> = Vec::new();
    for tag in tags {
        match probe_release_for_tag(gh_binary, &owner, &repo, tag) {
            ReleaseProbe::Published => published.push(tag),
            ReleaseProbe::NotBlocking => {}
            ReleaseProbe::Indeterminate(msg) => indeterminate.push((tag, msg)),
        }
    }
    if !indeterminate.is_empty() {
        let detail = indeterminate
            .iter()
            .map(|(tag, msg)| format!("  {tag}: {msg}"))
            .collect::<Vec<_>>()
            .join("\n");
        bail!(
            "refusing to roll back: could not determine whether published GitHub \
             release(s) exist for:\n{detail}\n\
             No run summary covers these tag(s) and the release probe is \
             unanswerable, so there is no evidence the version(s) are safe to \
             destroy. Restore gh / network access (or GITHUB_TOKEN auth) and retry, \
             or pass --force if you are certain nothing irreversible shipped.",
        );
    }
    if !published.is_empty() {
        return Err(RollbackRefusal {
            reason: format!(
                "published GitHub release(s) exist for: {} \
                 (and no run summary is available to prove nothing irreversible shipped).\n\
                 One-way-door publishers (crates.io, chocolatey, winget, snapcraft, ...) \
                 usually ship alongside a published release; if any did, the version is \
                 burned and deleting the tag(s) only orphans live published state — \
                 tags kept to protect it.\n\
                 Caveat: a release left behind by a rollback that predates automatic \
                 release cleanup may be an ORPHAN of a rolled-back attempt rather than \
                 real burn evidence — verify the release (and the one-way-door \
                 registries) before trusting it; if it is an orphan, delete it and \
                 re-run, or use --force.",
                published.join(", ")
            ),
            next_step: refusal_next_step(),
        }
        .into());
    }
    Ok(())
}

/// Trim a SHA to the canonical 7-char short form for log output.
fn short(sha: &str) -> &str {
    if sha.len() > 7 { &sha[..7] } else { sha }
}

/// First line of a multi-line commit message, for compact status lines.
fn first_line(msg: &str) -> &str {
    msg.lines().next().unwrap_or(msg)
}

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

    #[test]
    fn classifies_lockstep_release_tags() {
        assert_eq!(classify_tag("v1.2.3"), Some(TagKind::Lockstep));
        assert_eq!(classify_tag("v0.0.1"), Some(TagKind::Lockstep));
        assert_eq!(classify_tag("v10.20.30"), Some(TagKind::Lockstep));
    }

    #[test]
    fn classifies_lockstep_prerelease_and_build_tags() {
        assert_eq!(classify_tag("v1.2.3-rc.1"), Some(TagKind::Lockstep));
        assert_eq!(classify_tag("v1.2.3-beta.10"), Some(TagKind::Lockstep));
        assert_eq!(classify_tag("v1.2.3+build.42"), Some(TagKind::Lockstep));
        assert_eq!(
            classify_tag("v1.2.3-rc.1+build.42"),
            Some(TagKind::Lockstep)
        );
    }

    #[test]
    fn classifies_per_crate_tags() {
        assert_eq!(classify_tag("mycrate-v1.2.3"), Some(TagKind::PerCrate));
        assert_eq!(
            classify_tag("cfgd-operator-v0.4.0"),
            Some(TagKind::PerCrate)
        );
        assert_eq!(
            classify_tag("my_crate-v1.2.3-rc.1"),
            Some(TagKind::PerCrate)
        );
    }

    #[test]
    fn rejects_non_anodize_shaped_tags() {
        assert_eq!(classify_tag("foo-bar"), None);
        assert_eq!(classify_tag("v1.2"), None);
        assert_eq!(classify_tag("v1"), None);
        assert_eq!(classify_tag("release-1.2.3"), None);
        assert_eq!(classify_tag("tag-without-version"), None);
        assert_eq!(classify_tag(""), None);
        assert_eq!(classify_tag("v1.2.3.4"), None);
    }

    #[test]
    fn scope_lockstep_excludes_per_crate() {
        assert!(scope_includes(Scope::Lockstep, TagKind::Lockstep));
        assert!(!scope_includes(Scope::Lockstep, TagKind::PerCrate));
    }

    #[test]
    fn scope_per_crate_excludes_lockstep() {
        assert!(scope_includes(Scope::PerCrate, TagKind::PerCrate));
        assert!(!scope_includes(Scope::PerCrate, TagKind::Lockstep));
    }

    #[test]
    fn scope_all_accepts_both() {
        assert!(scope_includes(Scope::All, TagKind::Lockstep));
        assert!(scope_includes(Scope::All, TagKind::PerCrate));
    }

    #[test]
    fn scope_parser_round_trip() {
        assert_eq!("all".parse::<Scope>().unwrap(), Scope::All);
        assert_eq!("lockstep".parse::<Scope>().unwrap(), Scope::Lockstep);
        assert_eq!("per-crate".parse::<Scope>().unwrap(), Scope::PerCrate);
        assert_eq!("percrate".parse::<Scope>().unwrap(), Scope::PerCrate);
        assert!("nope".parse::<Scope>().is_err());
    }

    #[test]
    fn mode_parser_round_trip() {
        assert_eq!("revert".parse::<Mode>().unwrap(), Mode::Revert);
        assert_eq!("reset".parse::<Mode>().unwrap(), Mode::Reset);
        assert!("rewind".parse::<Mode>().is_err());
    }

    #[test]
    fn revert_message_uses_lockstep_as_subject() {
        let msg = build_revert_message(
            "abcdef1234567890",
            &[
                "mycrate-v1.0.0".into(),
                "v1.0.0".into(),
                "other-v1.0.0".into(),
            ],
            false,
        );
        assert!(msg.starts_with("chore(release): rollback v1.0.0 [skip ci]"));
        assert!(msg.contains("Reverts abcdef1."));
        assert!(msg.contains("Tags deleted: mycrate-v1.0.0, v1.0.0, other-v1.0.0"));
    }

    #[test]
    fn revert_message_falls_back_to_first_when_no_lockstep() {
        let msg = build_revert_message(
            "abcdef1234567890",
            &["mycrate-v1.0.0".into(), "other-v1.0.0".into()],
            false,
        );
        assert!(msg.starts_with("chore(release): rollback mycrate-v1.0.0 [skip ci]"));
    }

    #[test]
    fn revert_message_dry_run_marks_pending_tag_deletion() {
        let msg = build_revert_message("abcdef1234567890", &["v1.0.0".into()], true);
        assert!(
            msg.contains("Tags that WOULD be deleted: v1.0.0"),
            "dry-run preview must distinguish pending deletion: {msg}"
        );
        assert!(
            !msg.contains("\nTags deleted:"),
            "dry-run preview must NOT emit the real-run label: {msg}"
        );
    }

    #[test]
    fn per_crate_regex_rejects_leading_digit() {
        // Cargo crate names must start with a letter; the rollback
        // regex must not accept `9-foo-v1.2.3` as a per-crate tag.
        assert_eq!(classify_tag("9-foo-v1.2.3"), None);
        assert_eq!(classify_tag("0bad-v1.0.0"), None);
        // Underscore-leading is still accepted (matches cargo identifier rules).
        assert_eq!(classify_tag("_foo-v1.2.3"), Some(TagKind::PerCrate));
    }

    #[test]
    fn safety_check_prefix_admits_anodize_revert_only() {
        // anodize's own prior revert subject — admissible.
        let anodize_subject = "Revert \"chore(release): rollback v1.2.3 [skip ci]\"";
        assert!(
            anodize_subject.starts_with(ANODIZE_REVERT_SUBJECT_PREFIX.as_str()),
            "anodize-generated revert must be recognised"
        );
        // GitHub's "Revert this PR" button subject — must NOT be admitted.
        let github_subject = "Revert \"feat: add new flag\"";
        assert!(
            !github_subject.starts_with(ANODIZE_REVERT_SUBJECT_PREFIX.as_str()),
            "unrelated revert PR subjects must NOT be admitted as anodize-shaped"
        );
    }

    // -----------------------------------------------------------------
    // Fixture-repo integration tests — exercise the safety-check path
    // and dry-run no-mutation guarantee against a real tempdir git repo.
    // -----------------------------------------------------------------

    use std::path::Path;
    use std::process::Command;

    fn run_git(dir: &Path, args: &[&str]) {
        let out = anodizer_core::test_helpers::output_with_spawn_retry(
            || {
                let mut cmd = Command::new("git");
                cmd.args(args)
                    .current_dir(dir)
                    .env("GIT_AUTHOR_NAME", "test")
                    .env("GIT_AUTHOR_EMAIL", "test@test.com")
                    .env("GIT_COMMITTER_NAME", "test")
                    .env("GIT_COMMITTER_EMAIL", "test@test.com");
                cmd
            },
            "git",
        );
        assert!(
            out.status.success(),
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&out.stderr)
        );
    }

    /// Build a repo with: initial commit -> bump commit (tagged vX.Y.Z),
    /// optionally followed by extra commits to exercise the safety check.
    fn init_bump_repo(dir: &Path, extra_commits: usize) -> String {
        run_git(dir, &["init", "-b", "master"]);
        run_git(dir, &["config", "user.email", "test@test.com"]);
        run_git(dir, &["config", "user.name", "test"]);
        std::fs::write(dir.join("README"), "init").unwrap();
        run_git(dir, &["add", "."]);
        run_git(dir, &["commit", "-m", "initial"]);

        std::fs::write(dir.join("Cargo.toml"), "[package]\nversion = \"1.0.0\"\n").unwrap();
        run_git(dir, &["add", "."]);
        run_git(dir, &["commit", "-m", "chore(release): v1.0.0"]);
        run_git(dir, &["tag", "v1.0.0"]);

        let bump_sha = String::from_utf8(
            anodizer_core::test_helpers::output_with_spawn_retry(
                || {
                    let mut cmd = Command::new("git");
                    cmd.args(["rev-parse", "HEAD"]).current_dir(dir);
                    cmd
                },
                "git",
            )
            .stdout,
        )
        .unwrap()
        .trim()
        .to_string();

        for i in 0..extra_commits {
            let fname = format!("extra-{i}.txt");
            std::fs::write(dir.join(&fname), "x").unwrap();
            run_git(dir, &["add", "."]);
            run_git(dir, &["commit", "-m", &format!("feat: extra work {i}")]);
        }

        bump_sha
    }

    /// Give a fixture repo a resolvable non-github.com origin: the
    /// published-state guard's probe is inapplicable there (warn +
    /// proceed), letting tests exercise their actual subject without
    /// tripping the unresolvable-origin fail-closed refusal. The URL is
    /// never contacted — these tests run with `dry_run` / `no_push`.
    fn add_non_github_origin(dir: &Path) {
        run_git(
            dir,
            &["remote", "add", "origin", "https://gitlab.example/o/r.git"],
        );
    }

    /// Write a config with no crates.io-targeting crate, satisfying the
    /// guard's fail-closed config requirement without arming the index
    /// probe — the run-path tests below exercise git mechanics, not the
    /// probe.
    fn write_minimal_config(dir: &Path) {
        std::fs::write(dir.join(".anodizer.yaml"), "project_name: fixture\n").unwrap();
    }

    fn opts_for(dir: &Path, sha: Option<String>) -> RollbackOpts {
        let _ = dir; // cwd is process-global; the with-guard helpers below set it
        RollbackOpts {
            sha,
            dry_run: false,
            no_push: true,
            force: false,
            scope: Scope::All,
            mode: Mode::Revert,
            branch: None,
            verbose: false,
            debug: false,
            quiet: true,
        }
    }

    /// Process-wide cwd swap. Marked `serial(cwd)` — the workspace-canonical
    /// cwd serial group — so these swappers mutually exclude with every other
    /// cwd-touching test in this binary (e.g. `helpers::resolve_git_context`).
    use serial_test::serial;

    #[test]
    #[serial(cwd)]
    fn safety_check_fires_when_non_bump_commits_sit_on_top() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let bump_sha = init_bump_repo(dir, 2);
        add_non_github_origin(dir);
        write_minimal_config(dir);

        let _cwd = anodizer_core::test_helpers::CwdGuard::new(dir).unwrap();

        let opts = opts_for(dir, Some(bump_sha));
        let err = run(opts).expect_err("safety check should fire");
        let msg = format!("{err}");
        assert!(msg.contains("cannot rollback"), "got: {msg}");
        assert!(
            msg.contains("non-bump commit"),
            "missing safety-check phrasing: {msg}"
        );
    }

    #[test]
    #[serial(cwd)]
    fn safety_check_passes_against_clean_head_at_bump_commit() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let _bump_sha = init_bump_repo(dir, 0);
        add_non_github_origin(dir);
        write_minimal_config(dir);

        let _cwd = anodizer_core::test_helpers::CwdGuard::new(dir).unwrap();

        // HEAD == bump_sha; safety check trivially passes (no commits
        // between HEAD and target).
        let mut opts = opts_for(dir, None);
        opts.dry_run = true; // don't mutate the fixture
        run(opts).expect("safety check should pass at HEAD == bump commit");

        // Tag still present (dry-run guarantee).
        let tags = git::get_tags_at_head_in(dir).unwrap();
        assert_eq!(tags, vec!["v1.0.0".to_string()]);
    }

    #[test]
    #[serial(cwd)]
    fn dry_run_makes_no_mutations() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let _bump_sha = init_bump_repo(dir, 0);
        let head_before = String::from_utf8(
            anodizer_core::test_helpers::output_with_spawn_retry(
                || {
                    let mut cmd = Command::new("git");
                    cmd.args(["rev-parse", "HEAD"]).current_dir(dir);
                    cmd
                },
                "git",
            )
            .stdout,
        )
        .unwrap()
        .trim()
        .to_string();
        add_non_github_origin(dir);
        write_minimal_config(dir);

        let _cwd = anodizer_core::test_helpers::CwdGuard::new(dir).unwrap();

        let mut opts = opts_for(dir, None);
        opts.dry_run = true;
        run(opts).expect("dry-run should succeed");

        // Tag still present.
        let tags = git::get_tags_at_head_in(dir).unwrap();
        assert_eq!(tags, vec!["v1.0.0".to_string()]);
        // HEAD unchanged.
        let head_after = String::from_utf8(
            anodizer_core::test_helpers::output_with_spawn_retry(
                || {
                    let mut cmd = Command::new("git");
                    cmd.args(["rev-parse", "HEAD"]).current_dir(dir);
                    cmd
                },
                "git",
            )
            .stdout,
        )
        .unwrap()
        .trim()
        .to_string();
        assert_eq!(head_before, head_after);
    }

    #[test]
    #[serial(cwd)]
    fn no_push_skips_remote_ops_but_does_local_revert() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let bump_sha = init_bump_repo(dir, 0);
        // Non-github origin only; `no_push` keeps push_branch_in from contacting it.
        add_non_github_origin(dir);
        write_minimal_config(dir);

        let _cwd = anodizer_core::test_helpers::CwdGuard::new(dir).unwrap();

        let opts = RollbackOpts {
            sha: None,
            dry_run: false,
            no_push: true,
            force: false,
            scope: Scope::All,
            mode: Mode::Revert,
            branch: None,
            verbose: false,
            debug: false,
            quiet: true,
        };
        run(opts).expect("no-push rollback should succeed locally");

        // Local tag gone.
        let tags = git::get_tags_at_sha_in(dir, &bump_sha).unwrap();
        assert!(
            tags.is_empty(),
            "expected no tags at bump_sha; got {tags:?}"
        );

        // Revert commit landed on top of the bump.
        let subj = git::commit_subject_in(dir, "HEAD").unwrap();
        assert!(
            subj.starts_with("chore(release): rollback v1.0.0"),
            "unexpected HEAD subject: {subj}"
        );
    }

    #[test]
    #[serial(cwd)]
    fn skips_tags_not_matching_anodize_shape() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let bump_sha = init_bump_repo(dir, 0);
        add_non_github_origin(dir);
        write_minimal_config(dir);
        // Add a non-anodize tag at the same SHA.
        run_git(dir, &["tag", "internal-release"]);

        let _cwd = anodizer_core::test_helpers::CwdGuard::new(dir).unwrap();

        let opts = RollbackOpts {
            sha: None,
            dry_run: false,
            no_push: true,
            force: false,
            scope: Scope::All,
            mode: Mode::Revert,
            branch: None,
            verbose: false,
            debug: false,
            quiet: true,
        };
        run(opts).expect("rollback should ignore non-anodize tag");

        // Non-anodize tag survived; anodize tag is gone.
        let surviving = git::get_tags_at_sha_in(dir, &bump_sha).unwrap();
        assert_eq!(surviving, vec!["internal-release".to_string()]);
    }

    // -----------------------------------------------------------------
    // --branch flag + detached-HEAD branch resolution.
    // -----------------------------------------------------------------

    #[test]
    fn resolve_push_branch_honors_explicit_flag() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        // No git init required — explicit branch short-circuits before
        // hitting git_output_in.
        // Explicit short-circuits before any git query; SHA is irrelevant.
        let b = resolve_push_branch(
            dir,
            "0000000000000000000000000000000000000000",
            Some("release/v9.9.9-prep"),
        )
        .unwrap();
        assert_eq!(b, "release/v9.9.9-prep");
    }

    #[test]
    fn resolve_push_branch_hard_fails_on_detached_head_without_branch() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        // Build a repo whose HEAD is detached AND no branch points at
        // it: commit twice on master, then `git checkout --detach` the
        // older sha — master now points past HEAD.
        run_git(dir, &["init", "-b", "master"]);
        run_git(dir, &["config", "user.email", "t@t.com"]);
        run_git(dir, &["config", "user.name", "t"]);
        std::fs::write(dir.join("a"), "1").unwrap();
        run_git(dir, &["add", "."]);
        run_git(dir, &["commit", "-m", "c1"]);
        let older_sha = String::from_utf8(
            anodizer_core::test_helpers::output_with_spawn_retry(
                || {
                    let mut cmd = Command::new("git");
                    cmd.args(["rev-parse", "HEAD"]).current_dir(dir);
                    cmd
                },
                "git",
            )
            .stdout,
        )
        .unwrap()
        .trim()
        .to_string();
        std::fs::write(dir.join("a"), "2").unwrap();
        run_git(dir, &["add", "."]);
        run_git(dir, &["commit", "-m", "c2"]);
        run_git(dir, &["checkout", "--detach", &older_sha]);

        // An empty env source means the `GITHUB_REF_NAME` fallback can't
        // supply a value, then verify the hard-fail surfaces the remediation.
        let env = anodizer_core::MapEnvSource::new();

        // No remote configured → SHA-derivation returns empty, falls
        // through to get_current_branch_in, which fails on detached
        // HEAD with no env fallback → operator-friendly hard-fail.
        let err = resolve_push_branch_with_env(dir, &older_sha, None, &env).unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("cannot determine branch for revert push"),
            "missing hard-fail phrasing: {msg}"
        );
        assert!(
            msg.contains("--branch <name>"),
            "hard-fail must name the remediation flag: {msg}"
        );
    }

    #[test]
    fn resolve_push_branch_hard_fails_when_github_ref_name_looks_like_tag() {
        // Same shape as above (detached HEAD with no pointing branch),
        // but GITHUB_REF_NAME is set to a tag-shaped value. The
        // is_branchlike guard in get_current_branch_in must reject it,
        // and resolve_push_branch must surface the operator-friendly
        // hard-fail (not silently push to a branch named after the tag).
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        run_git(dir, &["init", "-b", "master"]);
        run_git(dir, &["config", "user.email", "t@t.com"]);
        run_git(dir, &["config", "user.name", "t"]);
        std::fs::write(dir.join("a"), "1").unwrap();
        run_git(dir, &["add", "."]);
        run_git(dir, &["commit", "-m", "c1"]);
        let older_sha = String::from_utf8(
            anodizer_core::test_helpers::output_with_spawn_retry(
                || {
                    let mut cmd = Command::new("git");
                    cmd.args(["rev-parse", "HEAD"]).current_dir(dir);
                    cmd
                },
                "git",
            )
            .stdout,
        )
        .unwrap()
        .trim()
        .to_string();
        std::fs::write(dir.join("a"), "2").unwrap();
        run_git(dir, &["add", "."]);
        run_git(dir, &["commit", "-m", "c2"]);
        run_git(dir, &["checkout", "--detach", &older_sha]);

        let env = anodizer_core::MapEnvSource::new().with("GITHUB_REF_NAME", "v0.4.5");

        let err = resolve_push_branch_with_env(dir, &older_sha, None, &env).unwrap_err();
        let msg = format!("{err}");
        assert!(
            msg.contains("cannot determine branch for revert push"),
            "tag-shaped GITHUB_REF_NAME must trigger the operator-facing hard-fail: {msg}"
        );
    }

    #[test]
    fn resolve_push_branch_explicit_branch_wins_over_detached_head() {
        // Even when auto-resolution would hard-fail, --branch wins.
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        run_git(dir, &["init", "-b", "master"]);
        run_git(dir, &["config", "user.email", "t@t.com"]);
        run_git(dir, &["config", "user.name", "t"]);
        std::fs::write(dir.join("a"), "1").unwrap();
        run_git(dir, &["add", "."]);
        run_git(dir, &["commit", "-m", "c1"]);
        let older_sha = String::from_utf8(
            anodizer_core::test_helpers::output_with_spawn_retry(
                || {
                    let mut cmd = Command::new("git");
                    cmd.args(["rev-parse", "HEAD"]).current_dir(dir);
                    cmd
                },
                "git",
            )
            .stdout,
        )
        .unwrap()
        .trim()
        .to_string();
        std::fs::write(dir.join("a"), "2").unwrap();
        run_git(dir, &["add", "."]);
        run_git(dir, &["commit", "-m", "c2"]);
        run_git(dir, &["checkout", "--detach", &older_sha]);

        // --branch short-circuits before any env read, so an empty env source
        // proves the explicit flag wins regardless of `GITHUB_REF_NAME`.
        let env = anodizer_core::MapEnvSource::new();
        let b = resolve_push_branch_with_env(dir, &older_sha, Some("master"), &env).unwrap();
        assert_eq!(b, "master");
    }

    // -----------------------------------------------------------------
    // Published-release guard. Drives `check_no_published_releases`
    // with a stub `gh` script in a tempdir (no PATH mutation) against a
    // fixture repo whose origin is GitHub-shaped (local config only —
    // no network is touched; the stub answers the API call).
    // -----------------------------------------------------------------

    /// Write an executable stub standing in for the `gh` CLI.
    #[cfg(unix)]
    fn write_gh_stub(dir: &Path, body: &str) -> std::path::PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let path = dir.join("gh-stub");
        std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
        path
    }

    /// Fixture repo with a GitHub-shaped origin so
    /// `resolve_repo_slug_in` resolves owner/repo without a network.
    fn init_github_origin_repo(dir: &Path) {
        let _ = init_bump_repo(dir, 0);
        run_git(
            dir,
            &["remote", "add", "origin", "https://github.com/o/r.git"],
        );
    }

    fn quiet_log() -> StageLogger {
        StageLogger::new("test", Verbosity::Quiet)
    }

    /// crates.io index probe stub that must never be consulted — used by
    /// tests whose fixtures carry no repo config (no tag→crate mapping
    /// exists), pinning that the probe layer stays quiet on that path.
    fn probe_untouched(_: &str, _: &str) -> Result<bool> {
        panic!("crates.io index probe must not be consulted on this path")
    }

    /// Moderated-registry probe stub reporting "never submitted", so tests
    /// targeting the crates.io layer (or the summary/release layers)
    /// exercise their subject in isolation.
    fn moderated_probe_clear(_: &str, _: &str) -> Result<Option<String>> {
        Ok(None)
    }

    /// Winget sibling of [`moderated_probe_clear`].
    fn winget_probe_clear(_: &WingetProbeSpec) -> Result<Option<String>> {
        Ok(None)
    }

    /// Wrap a crates.io index probe into the full [`BurnProbes`] seam with
    /// clear moderated-registry probes.
    fn probes_with_crates_io(
        index: &(dyn Fn(&str, &str) -> Result<bool> + Sync),
    ) -> BurnProbes<'_> {
        BurnProbes {
            crates_io: index,
            chocolatey: &moderated_probe_clear,
            winget: &winget_probe_clear,
        }
    }

    /// Config with no crates.io-targeting crate: layer 2 has nothing to
    /// probe, so layer-1/3 tests exercise their subject in isolation.
    /// Named (rather than inlining `Config::default()` at call sites) so
    /// the six guard tests state the fixture's INTENT — "no cargo crate"
    /// is the property under test, not an incidental default.
    fn no_cargo_config() -> anodizer_core::config::Config {
        anodizer_core::config::Config::default()
    }

    /// Minimal in-memory repo config: one crates.io-targeting cargo crate
    /// per `(name, tag_template)` pair.
    fn config_with_cargo_crates(crates: &[(&str, &str)]) -> anodizer_core::config::Config {
        let mut config = anodizer_core::config::Config::default();
        config.crates = crates
            .iter()
            .map(|(name, tmpl)| anodizer_core::config::CrateConfig {
                name: name.to_string(),
                tag_template: tmpl.to_string(),
                publish: Some(anodizer_core::config::PublishConfig {
                    cargo: Some(anodizer_core::config::CargoPublishConfig::default()),
                    ..Default::default()
                }),
                ..Default::default()
            })
            .collect();
        config
    }

    #[test]
    #[cfg(unix)]
    fn guard_refuses_when_release_is_published() {
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo '{"id": 1, "draft": false}'"#);

        let err =
            check_no_published_releases(tmp.path(), &gh, &["v1.0.0".to_string()], &quiet_log())
                .expect_err("published release must block rollback");
        let msg = err.to_string();
        assert!(msg.contains("refusing to roll back"), "got: {msg}");
        assert!(msg.contains("v1.0.0"), "must name the blocking tag: {msg}");
        assert!(
            msg.contains("--force"),
            "must name the override flag: {msg}"
        );
        assert!(
            err.downcast_ref::<RollbackRefusal>().is_some(),
            "a published-release refusal must be typed for the failure policy"
        );
        assert!(
            msg.contains("ORPHAN"),
            "must warn the release may be an orphan of a pre-cleanup rollback: {msg}"
        );
    }

    #[test]
    #[cfg(unix)]
    fn guard_allows_when_release_is_draft() {
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo '{"id": 1, "draft": true}'"#);

        check_no_published_releases(tmp.path(), &gh, &["v1.0.0".to_string()], &quiet_log())
            .expect("draft release is reversible; rollback may proceed");
    }

    #[test]
    #[cfg(unix)]
    fn guard_treats_missing_draft_field_as_published() {
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo '{"id": 1}'"#);

        let err =
            check_no_published_releases(tmp.path(), &gh, &["v1.0.0".to_string()], &quiet_log())
                .expect_err("a release whose draft state is unknown must block");
        assert!(err.to_string().contains("refusing to roll back"));
    }

    #[test]
    #[cfg(unix)]
    fn guard_allows_when_no_release_exists() {
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(
            tmp.path(),
            r#"echo 'gh: HTTP 404: Not Found (https://api.github.com/...)' >&2; exit 1"#,
        );

        check_no_published_releases(tmp.path(), &gh, &["v1.0.0".to_string()], &quiet_log())
            .expect("404 means no release; rollback may proceed");
    }

    #[test]
    #[cfg(unix)]
    fn guard_fails_closed_on_indeterminate_probe() {
        // gh binary missing entirely — with a GitHub-shaped origin and
        // no summary, an unanswerable probe means zero evidence the
        // version is safe to destroy: refuse and point at --force.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let missing = tmp.path().join("nonexistent-gh");

        let err = check_no_published_releases(
            tmp.path(),
            &missing,
            &["v1.0.0".to_string()],
            &quiet_log(),
        )
        .expect_err("indeterminate probe must fail closed");
        let msg = err.to_string();
        assert!(msg.contains("could not determine"), "got: {msg}");
        assert!(msg.contains("v1.0.0"), "must name the tag: {msg}");
        assert!(msg.contains("--force"), "must name the escape hatch: {msg}");
        assert!(
            err.downcast_ref::<RollbackRefusal>().is_none(),
            "an indeterminate (transient) fail-closed is mechanical, not a \
             by-design refusal — it must NOT be typed as RollbackRefusal"
        );
    }

    #[test]
    fn guard_fails_closed_when_origin_unresolvable() {
        // No 'origin' remote at all — zero evidence either way, so the
        // guard must refuse, not warn-and-proceed.
        let tmp = tempfile::tempdir().unwrap();
        let _ = init_bump_repo(tmp.path(), 0);
        let gh = tmp.path().join("gh-never-spawned");

        let err =
            check_no_published_releases(tmp.path(), &gh, &["v1.0.0".to_string()], &quiet_log())
                .expect_err("unresolvable origin must fail closed");
        let msg = err.to_string();
        assert!(msg.contains("refusing to roll back"), "got: {msg}");
        assert!(msg.contains("'origin'"), "must name the remote: {msg}");
        assert!(msg.contains("--force"), "must name the escape hatch: {msg}");
    }

    #[test]
    fn guard_proceeds_for_resolvable_non_github_origin() {
        // Origin resolves but is not github.com-shaped — the one
        // genuinely-inapplicable case: no github.com release can exist,
        // so the guard warns and proceeds without spawning the probe.
        let tmp = tempfile::tempdir().unwrap();
        let _ = init_bump_repo(tmp.path(), 0);
        run_git(
            tmp.path(),
            &["remote", "add", "origin", "https://gitlab.com/o/r.git"],
        );
        let gh = tmp.path().join("gh-never-spawned");

        check_no_published_releases(tmp.path(), &gh, &["v1.0.0".to_string()], &quiet_log())
            .expect("non-github.com origin carries no probe signal; rollback may proceed");
    }

    #[test]
    #[cfg(unix)]
    fn guard_fails_closed_on_gh_auth_error() {
        // gh present but erroring (auth/network) — same fail-closed
        // ruling as a missing gh, with the probe error surfaced.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(
            tmp.path(),
            r#"echo 'gh: HTTP 401: Bad credentials' >&2; exit 1"#,
        );

        let err =
            check_no_published_releases(tmp.path(), &gh, &["v1.0.0".to_string()], &quiet_log())
                .expect_err("auth-failed probe must fail closed");
        assert!(
            err.to_string().contains("401"),
            "must carry the probe error"
        );
    }

    #[test]
    #[serial(cwd)]
    #[cfg(unix)]
    fn run_refuses_rollback_when_release_is_published() {
        // End-to-end through `run_with_gh`: the stub `gh` reports a
        // published release for v1.0.0 → rollback must refuse before
        // any mutation (tag intact, HEAD untouched).
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        init_github_origin_repo(dir);
        let gh = write_gh_stub(dir, r#"echo '{"id": 1, "draft": false}'"#);

        let _cwd = anodizer_core::test_helpers::CwdGuard::new(dir).unwrap();

        let err = run_with_gh(opts_for(dir, None), &gh)
            .expect_err("published release must refuse rollback");
        assert!(err.to_string().contains("refusing to roll back"));

        let tags = git::get_tags_at_head_in(dir).unwrap();
        assert!(
            tags.contains(&"v1.0.0".to_string()),
            "tag must survive a refused rollback; got {tags:?}"
        );
    }

    #[test]
    #[serial(cwd)]
    #[cfg(unix)]
    fn run_force_bypasses_published_release_guard() {
        // Same fixture, but --force: the guard is skipped (the stub gh
        // would refuse) and the local rollback completes. The stub
        // lives OUTSIDE the repo so the revert's dirty-tree check
        // doesn't trip on an untracked file.
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        init_github_origin_repo(dir);
        let stub_dir = tempfile::tempdir().unwrap();
        let _gh = write_gh_stub(stub_dir.path(), r#"echo '{"id": 1, "draft": false}'"#);

        let _cwd = anodizer_core::test_helpers::CwdGuard::new(dir).unwrap();

        let mut opts = opts_for(dir, None);
        opts.force = true;
        run(opts).expect("--force rollback must proceed without the guard");
        let tags = git::get_tags_at_head_in(dir).unwrap();
        assert!(
            !tags.contains(&"v1.0.0".to_string()),
            "tag must be deleted under --force"
        );
    }

    // -----------------------------------------------------------------
    // GitHub release cleanup: a rolled-back tag's release belongs to the
    // aborted attempt and is deleted alongside the tag (matched by tag).
    // -----------------------------------------------------------------

    /// gh stub that records every invocation's args to `record` and
    /// answers GETs with a release object (id 7) while accepting DELETEs.
    #[cfg(unix)]
    fn write_recording_gh_stub(dir: &Path, record: &Path) -> std::path::PathBuf {
        write_gh_stub(
            dir,
            &format!(
                "echo \"$@\" >> {record}\n\
                 case \"$*\" in *DELETE*) exit 0;; *) echo '{{\"id\": 7, \"draft\": true}}';; esac",
                record = record.display()
            ),
        )
    }

    #[test]
    #[cfg(unix)]
    fn release_cleanup_deletes_release_matched_by_tag() {
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let record = tmp.path().join("gh-calls.log");
        let gh = write_recording_gh_stub(tmp.path(), &record);

        delete_release_at_tag(tmp.path(), &gh, "v1.0.0", true, &quiet_log());

        let calls = std::fs::read_to_string(&record).expect("gh must have been consulted");
        assert!(
            calls.contains("/repos/o/r/releases/tags/v1.0.0"),
            "lookup must match by THIS tag only: {calls}"
        );
        assert!(
            calls.contains("-X DELETE /repos/o/r/releases/7"),
            "must delete the release id the tag lookup returned: {calls}"
        );
    }

    #[test]
    #[cfg(unix)]
    fn release_cleanup_noop_when_no_release_exists() {
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let record = tmp.path().join("gh-calls.log");
        let gh = write_gh_stub(
            tmp.path(),
            &format!(
                "echo \"$@\" >> {}\necho 'gh: HTTP 404: Not Found' >&2; exit 1",
                record.display()
            ),
        );

        delete_release_at_tag(tmp.path(), &gh, "v1.0.0", true, &quiet_log());

        let calls = std::fs::read_to_string(&record).expect("lookup must have run");
        assert!(
            !calls.contains("DELETE"),
            "no release means no DELETE call: {calls}"
        );
    }

    #[test]
    #[cfg(unix)]
    fn release_cleanup_skipped_for_non_github_origin() {
        let tmp = tempfile::tempdir().unwrap();
        let _ = init_bump_repo(tmp.path(), 0);
        run_git(
            tmp.path(),
            &["remote", "add", "origin", "https://gitlab.com/o/r.git"],
        );
        let record = tmp.path().join("gh-calls.log");
        let gh = write_recording_gh_stub(tmp.path(), &record);

        delete_release_at_tag(tmp.path(), &gh, "v1.0.0", true, &quiet_log());

        assert!(
            !record.exists(),
            "gh must never be spawned for a non-github.com origin"
        );
    }

    /// A tag with NO run summary is not attributed to this rollback: any
    /// GitHub release it carries (a human's draft notes, a prior reversible
    /// release) must be LEFT IN PLACE, never deleted — even though the tag
    /// itself is removed.
    #[test]
    #[cfg(unix)]
    fn release_cleanup_preserves_unattributed_release() {
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let record = tmp.path().join("gh-calls.log");
        let gh = write_recording_gh_stub(tmp.path(), &record);

        let outcome = delete_release_at_tag(tmp.path(), &gh, "v1.0.0", false, &quiet_log());

        assert!(matches!(outcome, ReleaseCleanup::Cleared));
        let calls = std::fs::read_to_string(&record).expect("lookup must have run");
        assert!(
            !calls.contains("DELETE"),
            "an unattributed release must never be deleted: {calls}"
        );
    }

    /// When an OWNED release lookup succeeds but the DELETE fails, the tag is
    /// RETAINED so the rollback stays retryable, never orphaning the release
    /// under a deleted tag.
    #[test]
    #[cfg(unix)]
    fn release_cleanup_retains_tag_when_release_delete_fails() {
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let record = tmp.path().join("gh-calls.log");
        let gh = write_gh_stub(
            tmp.path(),
            &format!(
                "echo \"$@\" >> {record}\n\
                 case \"$*\" in *DELETE*) echo 'gh: HTTP 500' >&2; exit 1;; \
                 *) echo '{{\"id\": 7}}';; esac",
                record = record.display()
            ),
        );

        let outcome = delete_release_at_tag(tmp.path(), &gh, "v1.0.0", true, &quiet_log());

        assert!(
            matches!(outcome, ReleaseCleanup::Retained),
            "a failed owned-release delete must retain the tag for retry"
        );
    }

    // -----------------------------------------------------------------
    // Summary-based published-state guard: the run summary on disk is
    // the primary evidence; the gh probe is consulted only for tags
    // with no summary. Proven with gh stubs whose answer CONTRADICTS
    // the summary, so the assertion pins which source decided.
    // -----------------------------------------------------------------

    /// Write a run summary for `tag` under the repo's dist tree.
    /// `rel` is the run-dir path relative to dist (e.g. "run-v1.0.0"
    /// or "mycrate/run-mycrate-v1.0.0"), `results` the per-publisher
    /// rows. The top-level flags are computed the way the producer
    /// computes them (via the public types), so these fixtures cannot
    /// drift from the real writer's shape.
    fn write_summary(
        repo: &Path,
        rel: &str,
        tag: &str,
        irreversibly_published: bool,
        results: Vec<anodizer_stage_publish::run_summary::RunSummaryResult>,
    ) {
        use anodizer_stage_publish::run_summary::{
            DeterminismAllowlist, RunSummary, write_summary_json,
        };
        let summary = RunSummary {
            schema_version: RunSummary::CURRENT_SCHEMA_VERSION,
            anodize_version: "0.0.0-test".to_string(),
            tag: tag.to_string(),
            submitter_gated: false,
            announce_gated: false,
            publishers_succeeded: 0,
            publishers_failed: 0,
            irreversibly_published,
            failure_policy: None,
            verify_release: None,
            retry_backoff_secs: 0.0,
            retry_by_scope: vec![],
            results,
            determinism_allowlist: DeterminismAllowlist::default(),
        };
        write_summary_json(&summary, &repo.join("dist").join(rel).join("summary.json"))
            .expect("write summary fixture");
    }

    fn summary_result(
        name: &str,
        group: anodizer_core::publish_report::PublisherGroup,
        status: &str,
    ) -> anodizer_stage_publish::run_summary::RunSummaryResult {
        anodizer_stage_publish::run_summary::RunSummaryResult {
            name: name.to_string(),
            group,
            required: true,
            status: status.to_string(),
            evidence: None,
        }
    }

    #[test]
    #[cfg(unix)]
    fn guard_refuses_when_summary_shows_irreversible_publish() {
        use anodizer_core::publish_report::PublisherGroup;
        // The gh stub answers 404 (no release — would PERMIT), so the
        // refusal can only come from the summary: the summary is the
        // primary evidence and must win.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        write_summary(
            tmp.path(),
            "run-v1.0.0",
            "v1.0.0",
            true,
            vec![
                summary_result("cargo", PublisherGroup::Submitter, "succeeded"),
                summary_result(
                    "chocolatey",
                    PublisherGroup::Submitter,
                    "pending-moderation",
                ),
                summary_result("github-release", PublisherGroup::Assets, "succeeded"),
            ],
        );

        let err = check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["v1.0.0".to_string()],
            &no_cargo_config(),
            &probes_with_crates_io(&probe_untouched),
            &quiet_log(),
        )
        .expect_err("irreversible publish in the summary must block rollback");
        let msg = err.to_string();
        assert!(
            msg.contains("version burned at cargo, chocolatey"),
            "got: {msg}"
        );
        assert!(
            !msg.contains("github-release"),
            "reversible publishers must not be blamed: {msg}"
        );
        assert!(
            msg.contains("--force"),
            "must name the override flag: {msg}"
        );
        assert!(
            msg.contains("cut the NEXT version"),
            "must suggest fix-forward: {msg}"
        );
        assert!(
            err.downcast_ref::<RollbackRefusal>().is_some(),
            "a burn-evidence refusal must be typed so the failure policy \
             renders it as protection, not breakage"
        );
    }

    #[test]
    #[cfg(unix)]
    fn guard_permits_when_summary_shows_only_reversible_publishers() {
        use anodizer_core::publish_report::PublisherGroup;
        // The gh stub reports a published release (would REFUSE), but
        // the summary proves only reversible publishers landed — a
        // same-version re-cut is still possible, so rollback proceeds
        // and the probe is never consulted for this tag.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo '{"id": 1, "draft": false}'"#);
        write_summary(
            tmp.path(),
            "run-v1.0.0",
            "v1.0.0",
            false,
            vec![
                summary_result("github-release", PublisherGroup::Assets, "succeeded"),
                summary_result("homebrew", PublisherGroup::Manager, "succeeded"),
                summary_result(
                    "cargo",
                    PublisherGroup::Submitter,
                    "skipped-submitter-gated",
                ),
            ],
        );

        check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["v1.0.0".to_string()],
            &no_cargo_config(),
            &probes_with_crates_io(&probe_untouched),
            &quiet_log(),
        )
        .expect("reversible-only summary must permit rollback without probing GitHub");
    }

    #[test]
    #[cfg(unix)]
    fn guard_refuses_on_legacy_summary_without_the_flag() {
        // A summary written before `irreversibly_published` existed
        // (raw JSON, field absent) still blocks via the per-result
        // group/status rows.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        let dir = tmp.path().join("dist").join("run-v1.0.0");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("summary.json"),
            r#"{
                "schema_version": 1,
                "anodize_version": "0.7.0",
                "tag": "v1.0.0",
                "submitter_gated": false,
                "announce_gated": false,
                "results": [{
                    "name": "cargo",
                    "group": "Submitter",
                    "required": true,
                    "status": "succeeded",
                    "evidence": null
                }],
                "determinism_allowlist": {"compile_time": [], "runtime": []}
            }"#,
        )
        .unwrap();

        let err = check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["v1.0.0".to_string()],
            &no_cargo_config(),
            &probes_with_crates_io(&probe_untouched),
            &quiet_log(),
        )
        .expect_err("legacy summary with a landed Submitter must block");
        assert!(err.to_string().contains("version burned at cargo"));
    }

    #[test]
    #[cfg(unix)]
    fn guard_falls_back_to_release_probe_when_no_summary_matches_the_tag() {
        use anodizer_core::publish_report::PublisherGroup;
        // A summary exists but for a DIFFERENT tag: the guarded tag has
        // no summary evidence, so the gh probe decides — and it reports
        // a published release, so rollback refuses.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo '{"id": 1, "draft": false}'"#);
        write_summary(
            tmp.path(),
            "run-v0.9.0",
            "v0.9.0",
            false,
            vec![summary_result(
                "github-release",
                PublisherGroup::Assets,
                "succeeded",
            )],
        );

        let err = check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["v1.0.0".to_string()],
            &no_cargo_config(),
            &probes_with_crates_io(&probe_untouched),
            &quiet_log(),
        )
        .expect_err("unsummarized tag must fall back to the release probe");
        assert!(
            err.to_string()
                .contains("published GitHub release(s) exist")
        );
    }

    #[test]
    #[cfg(unix)]
    fn guard_reads_per_crate_summary_layout() {
        use anodizer_core::publish_report::PublisherGroup;
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        write_summary(
            tmp.path(),
            "mycrate/run-mycrate-v1.0.0",
            "mycrate-v1.0.0",
            true,
            vec![summary_result(
                "cargo",
                PublisherGroup::Submitter,
                "succeeded",
            )],
        );

        let err = check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["mycrate-v1.0.0".to_string()],
            &no_cargo_config(),
            &probes_with_crates_io(&probe_untouched),
            &quiet_log(),
        )
        .expect_err("per-crate summary must be found and must block");
        assert!(err.to_string().contains("version burned at cargo"));
    }

    #[test]
    #[cfg(unix)]
    fn guard_ignores_malformed_summary_and_falls_back_to_probe() {
        // Unparseable summary carries no evidence: warn, then let the
        // probe decide (404 here → rollback permitted).
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        let dir = tmp.path().join("dist").join("run-v1.0.0");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("summary.json"), "not json {").unwrap();

        check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["v1.0.0".to_string()],
            &no_cargo_config(),
            &probes_with_crates_io(&probe_untouched),
            &quiet_log(),
        )
        .expect("malformed summary + 404 probe must permit rollback");
    }

    // -----------------------------------------------------------------
    // Global crates.io index probe (layer 2): the run summary answers a
    // per-run question, but whether a version is burned on crates.io is
    // GLOBAL state — a PRIOR run may have published it, and that run's
    // summary lives on another runner's disk.
    // -----------------------------------------------------------------

    #[test]
    fn crates_io_versions_for_tag_maps_tag_families_to_crates() {
        // The tag family prefix comes from the crate's tag_template, NOT
        // the crate name: cfgd's `crd-v...` tags belong to `cfgd-crd`.
        let config = config_with_cargo_crates(&[
            ("cfgd-crd", "crd-v{{ Version }}"),
            ("cfgd", "v{{ Version }}"),
        ]);
        assert_eq!(
            crates_io_versions_for_tag(&config, "crd-v0.5.0").probes,
            vec![("cfgd-crd".to_string(), "0.5.0".to_string())]
        );
        assert_eq!(
            crates_io_versions_for_tag(&config, "v0.5.0").probes,
            vec![("cfgd".to_string(), "0.5.0".to_string())]
        );
        let unmapped = crates_io_versions_for_tag(&config, "other-v1.0.0");
        assert!(
            unmapped.probes.is_empty() && unmapped.matched_non_crates_io == 0,
            "a tag outside every configured family maps to nothing"
        );
    }

    #[test]
    fn crates_io_versions_for_tag_lockstep_maps_every_sharing_crate() {
        // Lockstep workspaces share one `v...` family across all crates —
        // a lockstep tag must probe every crates.io-targeting crate.
        let config =
            config_with_cargo_crates(&[("core", "v{{ Version }}"), ("cli", "v{{ Version }}")]);
        assert_eq!(
            crates_io_versions_for_tag(&config, "v1.2.3").probes,
            vec![
                ("core".to_string(), "1.2.3".to_string()),
                ("cli".to_string(), "1.2.3".to_string()),
            ]
        );
    }

    #[test]
    fn crates_io_versions_for_tag_excludes_custom_registry_crates() {
        // A custom `registry:` points at a different index; the crates.io
        // probe carries no signal for it (same scoping judgment the
        // publisher's guard applies).
        let mut config = config_with_cargo_crates(&[("corp-crate", "v{{ Version }}")]);
        config.crates[0]
            .publish
            .as_mut()
            .expect("fixture publish block")
            .cargo
            .as_mut()
            .expect("fixture cargo block")
            .registry = Some("corp".to_string());
        let mapping = crates_io_versions_for_tag(&config, "v1.0.0");
        assert!(mapping.probes.is_empty());
        assert_eq!(
            mapping.matched_non_crates_io, 1,
            "the family matched — the crate just probes a different index"
        );
    }

    #[test]
    #[cfg(unix)]
    fn crates_io_probe_refuses_burned_version_despite_clean_summary() {
        use anodizer_core::publish_report::PublisherGroup;
        // The v0.5.0 attempt-#5 regression: this run's summary for
        // crd-v0.5.0 shows only reversible publishers (clean), but
        // cfgd-crd@0.5.0 is live on crates.io from a PRIOR run — the
        // per-run summary must not permit deleting a tag whose version is
        // globally burned.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        write_summary(
            tmp.path(),
            "cfgd-crd/run-crd-v0.5.0",
            "crd-v0.5.0",
            false,
            vec![summary_result(
                "github-release",
                PublisherGroup::Assets,
                "succeeded",
            )],
        );
        let config = config_with_cargo_crates(&[("cfgd-crd", "crd-v{{ Version }}")]);
        let probe = |name: &str, version: &str| -> Result<bool> {
            assert_eq!(
                (name, version),
                ("cfgd-crd", "0.5.0"),
                "probe must target the crate name + version the tag stamps on crates.io"
            );
            Ok(true)
        };

        let err = check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["crd-v0.5.0".to_string()],
            &config,
            &probes_with_crates_io(&probe),
            &quiet_log(),
        )
        .expect_err("a version live on the crates.io index must refuse rollback");
        let msg = err.to_string();
        assert!(
            msg.contains("live on the crates.io index"),
            "must name the global registry state: {msg}"
        );
        assert!(
            msg.contains("cfgd-crd@0.5.0"),
            "must name the burned crate@version: {msg}"
        );
        assert!(
            msg.contains("prior attempt"),
            "must explain the source: {msg}"
        );
        assert!(
            msg.contains("cut the NEXT version"),
            "must suggest fix-forward: {msg}"
        );
        assert!(msg.contains("--force"), "must name the escape hatch: {msg}");
        assert!(
            err.downcast_ref::<RollbackRefusal>().is_some(),
            "an index-burn refusal must be typed for the failure policy"
        );
        assert!(
            !msg.contains("No local run summary corroborates"),
            "a summarized tag's index burn is corroborated — no ownership caveat: {msg}"
        );
    }

    /// Index-only burn evidence (no run summary for the tag at all):
    /// existence on crates.io proves publication, not ownership. The refusal
    /// notes the absence of a corroborating summary — leading with the likely
    /// own-prior-run explanation and pointing at the crates.io page so the
    /// rarer foreign-ownership case can be ruled out.
    #[test]
    #[cfg(unix)]
    fn crates_io_refusal_notes_possible_squatting_without_summary() {
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        let config = config_with_cargo_crates(&[("test-project", "v{{ Version }}")]);
        let probe = |_: &str, _: &str| -> Result<bool> { Ok(true) };

        let err = check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["v0.1.0".to_string()],
            &config,
            &probes_with_crates_io(&probe),
            &quiet_log(),
        )
        .expect_err("index-live version must refuse rollback");
        let msg = err.to_string();
        assert!(
            msg.contains("No local run summary corroborates"),
            "uncorroborated index evidence must raise the ownership caveat: {msg}"
        );
        assert!(
            msg.contains("most likely a prior run of yours"),
            "the caveat must lead with the likely own-publish explanation, not squatting: {msg}"
        );
        assert!(
            msg.contains("https://crates.io/crates/test-project"),
            "must link the crates.io page to verify ownership: {msg}"
        );
        assert!(
            err.downcast_ref::<RollbackRefusal>().is_some(),
            "still a typed refusal"
        );
    }

    #[test]
    #[cfg(unix)]
    fn crates_io_probe_permits_absent_version_with_clean_summary() {
        use anodizer_core::publish_report::PublisherGroup;
        // Clean summary AND the version positively absent from the index:
        // nothing irreversible anywhere ⇒ rollback permitted.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        write_summary(
            tmp.path(),
            "run-v1.0.0",
            "v1.0.0",
            false,
            vec![summary_result(
                "github-release",
                PublisherGroup::Assets,
                "succeeded",
            )],
        );
        let config = config_with_cargo_crates(&[("mycrate", "v{{ Version }}")]);
        let probe = |_: &str, _: &str| -> Result<bool> { Ok(false) };

        check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["v1.0.0".to_string()],
            &config,
            &probes_with_crates_io(&probe),
            &quiet_log(),
        )
        .expect("clean summary + version absent from the index must permit rollback");
    }

    #[test]
    #[cfg(unix)]
    fn crates_io_probe_unreachable_index_fails_closed() {
        use anodizer_core::publish_report::PublisherGroup;
        // The index cannot be consulted: publication state is unverifiable,
        // so the guard must refuse (fail closed) rather than gamble a
        // destructive tag delete on a transient outage.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        write_summary(
            tmp.path(),
            "run-v1.0.0",
            "v1.0.0",
            false,
            vec![summary_result(
                "github-release",
                PublisherGroup::Assets,
                "succeeded",
            )],
        );
        let config = config_with_cargo_crates(&[("mycrate", "v{{ Version }}")]);
        let probe =
            |_: &str, _: &str| -> Result<bool> { Err(anyhow::anyhow!("connection refused")) };

        let err = check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["v1.0.0".to_string()],
            &config,
            &probes_with_crates_io(&probe),
            &quiet_log(),
        )
        .expect_err("an unreachable index must fail closed");
        let msg = err.to_string();
        assert!(
            msg.contains("could not be reached"),
            "must explain the index is unreachable: {msg}"
        );
        assert!(
            msg.contains("no proof the version(s) are safe to destroy"),
            "must explain publication state is unverifiable: {msg}"
        );
        assert!(msg.contains("--force"), "must name the escape hatch: {msg}");
    }

    #[test]
    #[cfg(unix)]
    fn crates_io_probe_bails_when_tag_maps_to_no_crate() {
        // The config publishes to crates.io, but the guarded tag matches no
        // crate's tag family: the probe is blind for that tag and must fail
        // closed instead of silently narrowing itself to zero crates.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        let config = config_with_cargo_crates(&[("myapp", "app-v{{ Version }}")]);
        let probe = |_: &str, _: &str| -> Result<bool> {
            panic!("an unmapped tag must never reach the index probe")
        };

        let err = check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["v1.0.0".to_string()],
            &config,
            &probes_with_crates_io(&probe),
            &quiet_log(),
        )
        .expect_err("an unmappable tag must fail closed");
        let msg = err.to_string();
        assert!(
            msg.contains("could not map these tag(s) to any crate"),
            "must name the mapping failure: {msg}"
        );
        assert!(msg.contains("v1.0.0"), "must name the tag: {msg}");
        assert!(
            msg.contains("tag_template"),
            "must point at the family mapping to fix: {msg}"
        );
        assert!(msg.contains("--force"), "must name the escape hatch: {msg}");
    }

    #[test]
    #[cfg(unix)]
    fn crates_io_probe_proceeds_when_mapped_crates_skip_crates_io() {
        // The tag maps to a crate, but that crate publishes to a custom
        // registry: no crates.io one-way door exists for it, so the guard
        // proceeds without probing (distinct from the unmapped-tag bail).
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        let mut config = config_with_cargo_crates(&[
            ("corp-crate", "corp-v{{ Version }}"),
            ("public-crate", "pub-v{{ Version }}"),
        ]);
        config.crates[0]
            .publish
            .as_mut()
            .expect("fixture publish block")
            .cargo
            .as_mut()
            .expect("fixture cargo block")
            .registry = Some("corp".to_string());
        let probe = |_: &str, _: &str| -> Result<bool> {
            panic!("a custom-registry crate must never reach the crates.io probe")
        };

        check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["corp-v1.0.0".to_string()],
            &config,
            &probes_with_crates_io(&probe),
            &quiet_log(),
        )
        .expect("a mapped crate outside crates.io carries no cargo one-way door");
    }

    #[test]
    #[cfg(unix)]
    fn crates_io_probe_dedups_repeated_crate_version_probes() {
        // Under Scope::All a monorepo-prefixed and a bare tag can resolve to
        // the same crate@version; the index must be consulted once per pair.
        let tmp = tempfile::tempdir().unwrap();
        init_github_origin_repo(tmp.path());
        let gh = write_gh_stub(tmp.path(), r#"echo 'gh: HTTP 404: Not Found' >&2; exit 1"#);
        let mut config = config_with_cargo_crates(&[("mycrate", "v{{ Version }}")]);
        config.monorepo = Some(anodizer_core::config::MonorepoConfig {
            tag_prefix: Some("sub/".to_string()),
            ..Default::default()
        });
        let calls = std::sync::atomic::AtomicUsize::new(0);
        let probe = |name: &str, version: &str| -> Result<bool> {
            calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            assert_eq!((name, version), ("mycrate", "1.0.0"));
            Ok(false)
        };

        check_not_irreversibly_published(
            tmp.path(),
            &gh,
            &["v1.0.0".to_string(), "sub/v1.0.0".to_string()],
            &config,
            &probes_with_crates_io(&probe),
            &quiet_log(),
        )
        .expect("version absent from the index must permit rollback");
        assert_eq!(
            calls.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "the duplicate crate@version pair must be probed exactly once"
        );
    }

    #[test]
    fn crates_io_probes_run_concurrently() {
        // Two crates share the bare `v...` family (lockstep): both probes
        // rendezvous on a barrier, which only resolves when they execute on
        // different workers at the same time — a serialized probe loop would
        // deadlock here (and trip the barrier's wait), never pass.
        let config = config_with_cargo_crates(&[("a", "v{{ Version }}"), ("b", "v{{ Version }}")]);
        let barrier = std::sync::Barrier::new(2);
        let probe = |_: &str, _: &str| -> Result<bool> {
            barrier.wait();
            Ok(false)
        };
        check_not_burned_on_crates_io(&["v1.0.0".to_string()], &[], &config, &probe, &quiet_log())
            .expect("absent versions must permit rollback");
    }

    /// Moderated-registry probe stub that must never be consulted — for
    /// fixtures with no chocolatey/winget publisher configured.
    fn moderated_probe_untouched(_: &str, _: &str) -> Result<Option<String>> {
        panic!("moderated-registry probe must not be consulted on this path")
    }

    /// Winget sibling of [`moderated_probe_untouched`].
    fn winget_probe_untouched(_: &WingetProbeSpec) -> Result<Option<String>> {
        panic!("winget probe must not be consulted on this path")
    }

    fn config_with_choco_crate(choco_name: Option<&str>) -> anodizer_core::config::Config {
        let mut config = anodizer_core::config::Config::default();
        config.crates = vec![anodizer_core::config::CrateConfig {
            name: "mytool".to_string(),
            tag_template: "v{{ Version }}".to_string(),
            publish: Some(anodizer_core::config::PublishConfig {
                chocolatey: Some(anodizer_core::config::ChocolateyConfig {
                    name: choco_name.map(str::to_string),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        }];
        config
    }

    fn config_with_winget_crate(package_identifier: &str) -> anodizer_core::config::Config {
        let mut config = anodizer_core::config::Config::default();
        config.crates = vec![anodizer_core::config::CrateConfig {
            name: "mytool".to_string(),
            tag_template: "v{{ Version }}".to_string(),
            publish: Some(anodizer_core::config::PublishConfig {
                winget: Some(anodizer_core::config::WingetConfig {
                    package_identifier: Some(package_identifier.to_string()),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        }];
        config
    }

    #[test]
    fn moderated_registries_choco_pending_submission_refuses() {
        let config = config_with_choco_crate(None);
        let choco = |id: &str, version: &str| -> Result<Option<String>> {
            assert_eq!((id, version), ("mytool", "1.0.0"));
            Ok(Some(
                "submitted, currently: awaiting moderation".to_string(),
            ))
        };
        let probes = BurnProbes {
            crates_io: &probe_untouched,
            chocolatey: &choco,
            winget: &winget_probe_untouched,
        };
        let err = check_not_burned_on_moderated_registries(
            &["v1.0.0".to_string()],
            &config,
            &probes,
            &quiet_log(),
        )
        .expect_err("a pending chocolatey submission consumes the version");
        let msg = err.to_string();
        assert!(
            msg.contains("chocolatey package 'mytool@1.0.0'"),
            "must name the burned package: {msg}"
        );
        assert!(msg.contains("awaiting moderation"), "got: {msg}");
        assert!(
            err.downcast_ref::<RollbackRefusal>().is_some(),
            "a moderated-registry burn must be a typed refusal"
        );
    }

    #[test]
    fn moderated_registries_choco_name_override_is_probed() {
        let config = config_with_choco_crate(Some("renamed-pkg"));
        let choco = |id: &str, _: &str| -> Result<Option<String>> {
            assert_eq!(id, "renamed-pkg");
            Ok(None)
        };
        let probes = BurnProbes {
            crates_io: &probe_untouched,
            chocolatey: &choco,
            winget: &winget_probe_untouched,
        };
        check_not_burned_on_moderated_registries(
            &["v1.0.0".to_string()],
            &config,
            &probes,
            &quiet_log(),
        )
        .expect("a never-submitted version must permit rollback");
    }

    #[test]
    fn moderated_registries_winget_open_pr_refuses() {
        let config = config_with_winget_crate("Acme.MyTool");
        let winget = |spec: &WingetProbeSpec| -> Result<Option<String>> {
            assert_eq!(
                spec,
                &WingetProbeSpec {
                    upstream: "microsoft/winget-pkgs".to_string(),
                    package_id: "Acme.MyTool".to_string(),
                    version: "2.0.0".to_string(),
                    search_in_title: true,
                }
            );
            Ok(Some("an open manifest PR is pending".to_string()))
        };
        let probes = BurnProbes {
            crates_io: &probe_untouched,
            chocolatey: &moderated_probe_untouched,
            winget: &winget,
        };
        let err = check_not_burned_on_moderated_registries(
            &["v2.0.0".to_string()],
            &config,
            &probes,
            &quiet_log(),
        )
        .expect_err("an open winget manifest PR consumes the version");
        let msg = err.to_string();
        assert!(
            msg.contains("winget package 'Acme.MyTool' at 2.0.0"),
            "must name the burned package: {msg}"
        );
        assert!(msg.contains("open manifest PR"), "got: {msg}");
        assert!(err.downcast_ref::<RollbackRefusal>().is_some());
    }

    #[test]
    fn moderated_registries_probe_error_fails_open() {
        // Unlike the crates.io index probe (fail closed), the moderated
        // registries are advisory evidence: a probe failure warns and
        // proceeds so rate-limited/flaky endpoints cannot dead-end recovery.
        let config = config_with_choco_crate(None);
        let failing = |_: &str, _: &str| -> Result<Option<String>> {
            anyhow::bail!("connection reset by peer")
        };
        let probes = BurnProbes {
            crates_io: &probe_untouched,
            chocolatey: &failing,
            winget: &winget_probe_untouched,
        };
        check_not_burned_on_moderated_registries(
            &["v1.0.0".to_string()],
            &config,
            &probes,
            &quiet_log(),
        )
        .expect("an unreachable moderated registry must warn and proceed");
    }

    #[test]
    fn moderated_registries_skipped_when_publisher_not_configured() {
        // Cargo-only config: neither moderated-registry probe may run.
        let config = config_with_cargo_crates(&[("mycrate", "v{{ Version }}")]);
        let probes = BurnProbes {
            crates_io: &probe_untouched,
            chocolatey: &moderated_probe_untouched,
            winget: &winget_probe_untouched,
        };
        check_not_burned_on_moderated_registries(
            &["v1.0.0".to_string()],
            &config,
            &probes,
            &quiet_log(),
        )
        .expect("no moderated publisher configured — nothing to probe");
    }

    #[test]
    fn moderated_registries_templated_package_id_skips_probe() {
        // A template override cannot be resolved without a release context;
        // the probe must skip (warn) rather than probe a guessed id.
        let config = config_with_choco_crate(Some("{{ .ProjectName }}"));
        let probes = BurnProbes {
            crates_io: &probe_untouched,
            chocolatey: &moderated_probe_untouched,
            winget: &winget_probe_untouched,
        };
        check_not_burned_on_moderated_registries(
            &["v1.0.0".to_string()],
            &config,
            &probes,
            &quiet_log(),
        )
        .expect("an unresolvable package id skips the advisory probe");
    }

    #[test]
    fn moderated_registries_non_community_choco_feed_skips_probe() {
        // Only the community gallery has a moderation queue; a private feed
        // target must not be probed against community.chocolatey.org.
        let mut config = config_with_choco_crate(None);
        config.crates[0]
            .publish
            .as_mut()
            .unwrap()
            .chocolatey
            .as_mut()
            .unwrap()
            .source_repo = Some("https://nuget.internal.example/v2/".to_string());
        let probes = BurnProbes {
            crates_io: &probe_untouched,
            chocolatey: &moderated_probe_untouched,
            winget: &winget_probe_untouched,
        };
        check_not_burned_on_moderated_registries(
            &["v1.0.0".to_string()],
            &config,
            &probes,
            &quiet_log(),
        )
        .expect("a non-community feed has no moderation queue — nothing to probe");
    }

    #[test]
    fn moderated_registries_community_choco_feed_spelled_explicitly_is_probed() {
        // An explicit source_repo equal to the community push endpoint
        // (trailing-slash / case variance included) must still probe.
        let mut config = config_with_choco_crate(None);
        config.crates[0]
            .publish
            .as_mut()
            .unwrap()
            .chocolatey
            .as_mut()
            .unwrap()
            .source_repo = Some("HTTPS://PUSH.CHOCOLATEY.ORG".to_string());
        let choco = |id: &str, version: &str| -> Result<Option<String>> {
            assert_eq!((id, version), ("mytool", "1.0.0"));
            Ok(None)
        };
        let probes = BurnProbes {
            crates_io: &probe_untouched,
            chocolatey: &choco,
            winget: &winget_probe_untouched,
        };
        check_not_burned_on_moderated_registries(
            &["v1.0.0".to_string()],
            &config,
            &probes,
            &quiet_log(),
        )
        .expect("the community feed spelled explicitly must still be probed");
    }

    #[test]
    fn moderated_registries_winget_probe_uses_configured_upstream() {
        // The probe must search the same upstream the publisher would
        // submit to (repository.pull_request.base), not a hardcoded
        // microsoft/winget-pkgs.
        let mut config = config_with_winget_crate("Acme.MyTool");
        config.crates[0]
            .publish
            .as_mut()
            .unwrap()
            .winget
            .as_mut()
            .unwrap()
            .repository = Some(anodizer_core::config::RepositoryConfig {
            pull_request: Some(anodizer_core::config::PullRequestConfig {
                base: Some(anodizer_core::config::PullRequestBaseConfig {
                    owner: Some("acme".to_string()),
                    name: Some("winget-fork".to_string()),
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        });
        let winget = |spec: &WingetProbeSpec| -> Result<Option<String>> {
            assert_eq!(spec.upstream, "acme/winget-fork");
            Ok(None)
        };
        let probes = BurnProbes {
            crates_io: &probe_untouched,
            chocolatey: &moderated_probe_untouched,
            winget: &winget,
        };
        check_not_burned_on_moderated_registries(
            &["v2.0.0".to_string()],
            &config,
            &probes,
            &quiet_log(),
        )
        .expect("clear upstream must permit rollback");
    }

    #[test]
    fn moderated_registries_custom_commit_template_widens_winget_search() {
        // A custom commit_msg_template makes the PR title unpredictable, so
        // the probe must drop the in:title qualifier.
        let mut config = config_with_winget_crate("Acme.MyTool");
        config.crates[0]
            .publish
            .as_mut()
            .unwrap()
            .winget
            .as_mut()
            .unwrap()
            .commit_msg_template = Some("chore: bump {{ .Version }}".to_string());
        let winget = |spec: &WingetProbeSpec| -> Result<Option<String>> {
            assert!(
                !spec.search_in_title,
                "a custom PR-title template must widen the search to title+body"
            );
            Ok(None)
        };
        let probes = BurnProbes {
            crates_io: &probe_untouched,
            chocolatey: &moderated_probe_untouched,
            winget: &winget,
        };
        check_not_burned_on_moderated_registries(
            &["v2.0.0".to_string()],
            &config,
            &probes,
            &quiet_log(),
        )
        .expect("clear search must permit rollback");
    }

    #[test]
    fn winget_probe_token_prefers_github_token_via_env_seam() {
        let env = anodizer_core::MapEnvSource::new()
            .with("GITHUB_TOKEN", "gh-primary")
            .with("GH_TOKEN", "gh-fallback");
        assert_eq!(winget_probe_token(&env).as_deref(), Some("gh-primary"));
        let fallback_only = anodizer_core::MapEnvSource::new().with("GH_TOKEN", "gh-fallback");
        assert_eq!(
            winget_probe_token(&fallback_only).as_deref(),
            Some("gh-fallback")
        );
        let empty = anodizer_core::MapEnvSource::new();
        assert_eq!(winget_probe_token(&empty), None);
    }

    #[test]
    #[serial(cwd)]
    fn run_without_config_fails_closed() {
        // Unparseable config: the guard cannot map tags to crates, so a
        // non-forced rollback must refuse instead of silently skipping the
        // crates.io probe (the pre-fix fail-open).
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        let _bump_sha = init_bump_repo(dir, 0);
        std::fs::write(dir.join(".anodizer.yaml"), "::: not yaml {").unwrap();
        add_non_github_origin(dir);

        let _cwd = anodizer_core::test_helpers::CwdGuard::new(dir).unwrap();

        let err = run(opts_for(dir, None)).expect_err("missing config must fail closed");
        let msg = format!("{err}");
        assert!(
            msg.contains("could not load the anodizer config"),
            "must name the config failure: {msg}"
        );
        assert!(msg.contains("--force"), "must name the escape hatch: {msg}");
        // Nothing was mutated: the tag survives the refusal.
        let tags = git::get_tags_at_head_in(dir).unwrap();
        assert_eq!(tags, vec!["v1.0.0".to_string()]);
    }

    #[test]
    #[serial(cwd)]
    #[cfg(unix)]
    fn run_force_bypasses_crates_io_probe() {
        // --force skips the whole published-state guard, index probe
        // included: with a committed config whose crate family matches the
        // tag (the probe WOULD map v1.0.0 → mycrate@1.0.0), the rollback
        // still completes without consulting any registry. Companion to
        // `run_force_bypasses_published_release_guard`, which pins the same
        // bypass for the GitHub-release layer.
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        std::fs::write(
            dir.join(".anodizer.yaml"),
            "crates:\n  - name: mycrate\n    path: .\n    tag_template: \"v{{ Version }}\"\n    publish:\n      cargo: {}\n",
        )
        .unwrap();
        init_github_origin_repo(dir);

        let _cwd = anodizer_core::test_helpers::CwdGuard::new(dir).unwrap();

        let mut opts = opts_for(dir, None);
        opts.force = true;
        run(opts).expect("--force rollback must proceed without the crates.io probe");
        let tags = git::get_tags_at_head_in(dir).unwrap();
        assert!(
            !tags.contains(&"v1.0.0".to_string()),
            "tag must be deleted under --force"
        );
    }
}