autumn-cli 0.10.0

CLI tool for the Autumn web framework
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
//! File-emission engine shared by every generator.
//!
//! Generators describe what they want to do as a list of [`Action`]s, and
//! [`Plan::execute`] handles all the side-effecting filesystem work — including
//! collision detection, `--force` / `--dry-run`, and the human-readable
//! "Created/Modified" output that mirrors `autumn new`.

use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};

use autumn_web::config::DatabaseBackend;

use super::{Flags, GenerateError, provenance, sweep};

/// One filesystem operation the generator wants to perform.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
    /// Create a new file. Treated as a collision if the file already exists.
    Create { path: PathBuf, contents: String },
    /// Modify an existing file (or create it if absent). Never a collision.
    Modify { path: PathBuf, contents: String },
    /// Create a new file from raw bytes, with no UTF-8 or template handling.
    /// Used for verbatim/binary starter assets (e.g. vendored JS). Treated as a
    /// collision if the file already exists, like [`Action::Create`].
    CreateBytes { path: PathBuf, bytes: Vec<u8> },
    /// Create a file only if it does not already exist; skip silently if it
    /// does. Uses an exclusive-create open (analogous to `O_CREAT|O_EXCL`) so
    /// concurrent generator invocations cannot both win the race.
    CreateIfAbsent { path: PathBuf, contents: String },
}

impl Action {
    /// The path this action targets.
    #[must_use]
    pub fn path(&self) -> &Path {
        match self {
            Self::Create { path, .. }
            | Self::Modify { path, .. }
            | Self::CreateBytes { path, .. }
            | Self::CreateIfAbsent { path, .. } => path,
        }
    }
}

/// One in-place edit `generate` made to a shared file, recorded so `autumn
/// destroy` (issue #1048) can remove exactly that edit later — the
/// per-generator "revoke" hook the issue calls for.
///
/// Lives on [`Plan`] rather than on the [`Action::Modify`] it accompanies:
/// some generators (e.g. `scaffold`) collapse several `Modify` actions
/// targeting the same file (`Cargo.toml`) into one via
/// `plan.actions.retain(...)` + re-push, which would silently drop
/// per-action metadata. A plan-level list survives that.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Revert {
    /// Remove a `pub mod <name>;` declaration from a `mod.rs`-style file.
    ModDecl { path: PathBuf, name: String },
    /// Remove `entries` from the first `routes![...]` invocation in `path`
    /// (`src/main.rs`).
    RoutesEntries { path: PathBuf, entries: Vec<String> },
    /// Remove the `diesel::table! { <table> ... }` block from `path`
    /// (`src/schema.rs`) — but only if its content is still byte-identical
    /// to `expected_block` (the literal text this generator invocation
    /// would append for `table`), so a same-named table that pre-existed
    /// with different columns is never destroyed (issue #1048 PR review).
    SchemaTable {
        path: PathBuf,
        table: String,
        expected_block: String,
    },
    /// Remove the named crates' shorthand `[dependencies]` lines from `path`
    /// (`Cargo.toml`) — but only once `owner_dir` (e.g. `src/models`) has no
    /// other resource file left in it, so a sibling resource of the same
    /// generator that still needs this dependency (e.g. a second `model`
    /// also using `uuid`) survives destroying just one of them.
    CargoDeps {
        path: PathBuf,
        names: Vec<String>,
        owner_dir: PathBuf,
    },
    /// Remove `feature` from `autumn-web`'s `[dependencies]` features list
    /// in `path` (`Cargo.toml`), collapsing to a bare version string if that
    /// empties it — but only once `owner_dir` has no other resource file
    /// left in it (see [`Revert::CargoDeps`]); `None` when the generator
    /// pushing this revert has no single clean owning directory to check
    /// (falls back to the old always-remove behavior for that generator).
    CargoAutumnWebFeature {
        path: PathBuf,
        feature: String,
        owner_dir: Option<PathBuf>,
    },
    /// Remove `feature` from `autumn-web`'s `[dev-dependencies]` features
    /// list in `path` (`Cargo.toml`), deleting the whole line if that
    /// empties it (that entry was always freshly inserted, never
    /// pre-existing) — but only once `owner_dir` has no other resource file
    /// left in it (see [`Revert::CargoDeps`]).
    CargoAutumnWebDevFeature {
        path: PathBuf,
        feature: String,
        owner_dir: Option<PathBuf>,
    },
    /// Remove `entry` from the `jobs![...]` list in `path`
    /// (`src/jobs/mod.rs`), dropping the whole freshly-generated
    /// `registered_jobs()` function if it was the only entry.
    JobEntry { path: PathBuf, entry: String },
    /// Remove the `.policy::<...>(...)` and `.scope::<...>(...)` registration
    /// lines this generator injected for `{pascal}` into the `AppBuilder` chain
    /// in `path` (`src/main.rs`) (issue #1125). Unlike [`Revert::JobsRegistration`]
    /// (one shared call gated on `owner_dir`), each resource carries its own
    /// pair of registration lines keyed by its type, so removal is per-resource
    /// and needs no sibling-directory check.
    PolicyRegistration {
        path: PathBuf,
        pascal: String,
        snake: String,
    },
    /// Remove the `.jobs(jobs::registered_jobs())` call from the
    /// `AppBuilder` chain in `path` (`src/main.rs`) — but only once
    /// `owner_dir` (`src/jobs`) has no other job file left in it, so a
    /// sibling job that's still registered in the SAME shared
    /// `jobs![...]` list doesn't lose its only path to actually running
    /// (unlike [`Revert::MailPreview`]/[`Revert::InboundMailHandler`],
    /// whose entry-removal already collapses their own wrapper call only
    /// when their own list empties, this call lives in a *different* file
    /// than the `jobs![...]` list it depends on, so it needs the same
    /// directory-sibling check [`Revert::CargoDeps`] uses instead).
    JobsRegistration { path: PathBuf, owner_dir: PathBuf },
    /// Remove `mailer_type` from the `mail_previews![...]` list in `path`
    /// (`src/main.rs`), dropping the whole freshly-inserted
    /// `.mail_previews(...)` call if it was the only entry.
    MailPreview { path: PathBuf, mailer_type: String },
    /// Remove `.handler(<handler_module_path>())` from the
    /// `.inbound_mail_router(...)` chain in `path` (`src/main.rs`), dropping
    /// the whole freshly-inserted `.inbound_mail_router(...)` call if it was
    /// the only handler registered.
    InboundMailHandler {
        path: PathBuf,
        handler_module_path: String,
    },
    /// Remove `snake_name`'s `[[test]]` entry from `path` (`Cargo.toml`),
    /// plus the shared `system-tests` feature declaration too if no other
    /// `tests/system/*.rs` entry still needs it.
    SystemTestCargoPatch { path: PathBuf, snake_name: String },
    /// Remove the PWA `<link>`/`<meta>` tags and route-handler functions
    /// `autumn generate pwa` injected into `path` (`src/main.rs`).
    PwaMainRsInjection { path: PathBuf },
    /// Remove each `[auth.oauth2.<provider>]` stub block `autumn generate
    /// auth --oauth` appended to `path` (`autumn.toml`).
    AuthOAuthProviderStubs {
        path: PathBuf,
        providers: Vec<String>,
    },
    /// Remove the `[auth.webauthn]` stub block `autumn generate auth
    /// --passkeys` appended to `path` (`autumn.toml`).
    AuthWebauthnStub { path: PathBuf },
    /// Remove the `[[security.webhooks.endpoints]]` entry `autumn generate
    /// webhook` added to `path` (`autumn.toml`) — matched on both `name` and
    /// `route_path`, so a hand-written endpoint that merely shares a name
    /// survives — along with its CSRF/CAPTCHA path exemptions and, once no
    /// endpoint is left, the shared `[security.webhooks.replay]` block.
    WebhookEndpointStub {
        path: PathBuf,
        name: String,
        route_path: String,
    },
    /// Remove `/{plural}/{segment}` from `[security.submit_token]
    /// exempt_paths` in `path` (`autumn.toml`) — a submit-token exemption
    /// `autumn generate scaffold` appended — dropping the block if that empties
    /// a freshly-generated `exempt_paths` key.
    ///
    /// `segment` is `"validate"` for the `--live-validation` inline-validation
    /// routes (issue #1360) or `"preview"` for a `richtext` column's live
    /// Markdown preview routes (issue #1255). Both hx-include the whole form,
    /// so both must be exempt from the one-time submit-token guard.
    SubmitTokenValidateExempt {
        path: PathBuf,
        plural: String,
        segment: String,
    },
    /// Remove the remember-me middleware layer + startup-hook calls
    /// `autumn generate auth` injected into the `AppBuilder` chain in `path`
    /// (`src/main.rs`) (issue #1397).
    RememberMiddleware { path: PathBuf },
    /// Remove the `#[path]`-qualified `mod schema;` / `mod models;` links
    /// `generate model`/`scaffold` injected into `path` (`src/bin/seed.rs`)
    /// via [`super::schema_edit::link_models_into_seed_bin`] (issue #1718) —
    /// but only once `owner_dir` (`src/models`) has no other model file left
    /// in it, i.e. the LAST model is being destroyed and `src/models/mod.rs` /
    /// `src/schema.rs` (the link targets) are themselves removed. Destroying
    /// one of several models keeps the links, matching the surviving modules.
    SeedBinLinks { path: PathBuf, owner_dir: PathBuf },
    /// Remove the children-list + inline-create-form lines `autumn generate
    /// scaffold … --belongs-to` injected into the PARENT resource's generated
    /// `show` handler in `path` (`src/routes/<parents>.rs`) for `child_plural`
    /// (issue #1323).
    ///
    /// Every injected line carries a `// autumn:nested:<child_plural>` trailer,
    /// so removal is exact even when the same parent has several nested
    /// children; the extra CSRF/submit-token extractors spliced into the `show`
    /// signature are shared by all of them and come off only with the last one.
    NestedChildSection { path: PathBuf, child_plural: String },
    /// Remove one resource's block of generated Fluent keys from `path`
    /// (`i18n/en.ftl`) — the marked `# <Pascal> — generated by …` comment plus
    /// every `<snake>.` key `autumn generate scaffold --i18n` added (issue
    /// #1349).
    ///
    /// The shared `common.*` chrome block and the file itself always survive:
    /// sibling resources reuse the chrome, and the generated app calls
    /// `.i18n_auto()`, which panics at startup when the default locale's file is
    /// missing. Destroying the last `--i18n` resource therefore leaves an inert
    /// chrome-only bundle rather than a broken boot.
    I18nFtlKeys {
        path: PathBuf,
        pascal: String,
        snake: String,
    },
}

impl Revert {
    /// The path this revert targets.
    #[must_use]
    pub fn path(&self) -> &Path {
        match self {
            Self::ModDecl { path, .. }
            | Self::RoutesEntries { path, .. }
            | Self::SchemaTable { path, .. }
            | Self::CargoDeps { path, .. }
            | Self::CargoAutumnWebFeature { path, .. }
            | Self::CargoAutumnWebDevFeature { path, .. }
            | Self::JobEntry { path, .. }
            | Self::JobsRegistration { path, .. }
            | Self::PolicyRegistration { path, .. }
            | Self::MailPreview { path, .. }
            | Self::InboundMailHandler { path, .. }
            | Self::SystemTestCargoPatch { path, .. }
            | Self::PwaMainRsInjection { path }
            | Self::AuthOAuthProviderStubs { path, .. }
            | Self::AuthWebauthnStub { path }
            | Self::WebhookEndpointStub { path, .. }
            | Self::SubmitTokenValidateExempt { path, .. }
            | Self::RememberMiddleware { path }
            | Self::SeedBinLinks { path, .. }
            | Self::NestedChildSection { path, .. }
            | Self::I18nFtlKeys { path, .. } => path,
        }
    }

    /// The anchors of the edits this revert undoes (issue #2560).
    ///
    /// An anchor holds the target path and the values that choose the edit. It
    /// holds no template text (for example `expected_block`), because template
    /// text changes with the CLI version. A list value gives one anchor for each
    /// item, because `destroy` can plan more entries than `generate` wrote. The
    /// `match` has no wildcard. A new variant does not compile until it has an
    /// anchor.
    #[must_use]
    pub(super) fn anchors(&self, root: &Path) -> Vec<provenance::RevertAnchor> {
        let rel =
            |p: &Path| provenance::key(root, p).unwrap_or_else(|| p.to_string_lossy().into_owned());
        let owner = |dir: Option<&Path>| dir.map_or_else(String::new, rel);
        let each = |kind: &str, items: &[String], tail: String| -> Vec<String> {
            items
                .iter()
                .map(|item| format!("{kind}({item}{tail})"))
                .collect()
        };
        let reverts: Vec<String> = match self {
            Self::ModDecl { name, .. } => vec![format!("ModDecl({name})")],
            Self::RoutesEntries { entries, .. } => each("RoutesEntries", entries, String::new()),
            Self::SchemaTable { table, .. } => vec![format!("SchemaTable({table})")],
            Self::CargoDeps {
                names, owner_dir, ..
            } => each("CargoDeps", names, format!("; {}", rel(owner_dir))),
            Self::CargoAutumnWebFeature {
                feature, owner_dir, ..
            } => vec![format!(
                "CargoAutumnWebFeature({feature}; {})",
                owner(owner_dir.as_deref())
            )],
            Self::CargoAutumnWebDevFeature {
                feature, owner_dir, ..
            } => vec![format!(
                "CargoAutumnWebDevFeature({feature}; {})",
                owner(owner_dir.as_deref())
            )],
            Self::JobEntry { entry, .. } => vec![format!("JobEntry({entry})")],
            Self::JobsRegistration { owner_dir, .. } => {
                vec![format!("JobsRegistration({})", rel(owner_dir))]
            }
            Self::PolicyRegistration { pascal, snake, .. } => {
                vec![format!("PolicyRegistration({pascal}, {snake})")]
            }
            Self::MailPreview { mailer_type, .. } => vec![format!("MailPreview({mailer_type})")],
            Self::InboundMailHandler {
                handler_module_path,
                ..
            } => vec![format!("InboundMailHandler({handler_module_path})")],
            Self::SystemTestCargoPatch { snake_name, .. } => {
                vec![format!("SystemTestCargoPatch({snake_name})")]
            }
            Self::PwaMainRsInjection { .. } => vec!["PwaMainRsInjection".to_owned()],
            Self::AuthOAuthProviderStubs { providers, .. } => {
                each("AuthOAuthProviderStubs", providers, String::new())
            }
            Self::AuthWebauthnStub { .. } => vec!["AuthWebauthnStub".to_owned()],
            Self::WebhookEndpointStub {
                name, route_path, ..
            } => vec![format!("WebhookEndpointStub({name}, {route_path})")],
            Self::SubmitTokenValidateExempt {
                plural, segment, ..
            } => vec![format!("SubmitTokenValidateExempt({plural}, {segment})")],
            Self::RememberMiddleware { .. } => vec!["RememberMiddleware".to_owned()],
            Self::SeedBinLinks { owner_dir, .. } => {
                vec![format!("SeedBinLinks({})", rel(owner_dir))]
            }
            Self::NestedChildSection { child_plural, .. } => {
                vec![format!("NestedChildSection({child_plural})")]
            }
            Self::I18nFtlKeys { pascal, snake, .. } => {
                vec![format!("I18nFtlKeys({pascal}, {snake})")]
            }
        };
        let path = rel(self.path());
        reverts
            .into_iter()
            .map(|revert| provenance::RevertAnchor {
                path: path.clone(),
                revert,
            })
            .collect()
    }

    /// The directory whose continued occupancy (by any file other than
    /// this same destroy's own deletions) means this revert must NOT be
    /// applied yet — a sibling resource of the same generator may still
    /// need the dependency/feature. `None` means always apply (every
    /// variant except the three Cargo-editing ones, plus the Cargo ones
    /// where the pushing generator has no single owning directory).
    fn owner_dir(&self) -> Option<&Path> {
        match self {
            Self::CargoDeps { owner_dir, .. }
            | Self::JobsRegistration { owner_dir, .. }
            | Self::SeedBinLinks { owner_dir, .. } => Some(owner_dir),
            Self::CargoAutumnWebFeature { owner_dir, .. }
            | Self::CargoAutumnWebDevFeature { owner_dir, .. } => owner_dir.as_deref(),
            Self::ModDecl { .. }
            | Self::RoutesEntries { .. }
            | Self::SchemaTable { .. }
            | Self::JobEntry { .. }
            | Self::PolicyRegistration { .. }
            | Self::MailPreview { .. }
            | Self::InboundMailHandler { .. }
            | Self::SystemTestCargoPatch { .. }
            | Self::PwaMainRsInjection { .. }
            | Self::AuthOAuthProviderStubs { .. }
            | Self::AuthWebauthnStub { .. }
            | Self::WebhookEndpointStub { .. }
            | Self::SubmitTokenValidateExempt { .. }
            | Self::NestedChildSection { .. }
            | Self::I18nFtlKeys { .. }
            | Self::RememberMiddleware { .. } => None,
        }
    }

    /// Apply this revert to `content`, returning the new content. Every
    /// underlying transform is idempotent — a revert whose target is
    /// already absent returns `content` unchanged.
    ///
    /// `overrides` supplies the already-computed post-destroy content of
    /// OTHER files this same `Plan::revert` is also modifying (e.g.
    /// `src/schema.rs`, once its own `SchemaTable` revert has run) — the
    /// project-wide crate/feature usage scan ([`crate_referenced_elsewhere_in_project`]/
    /// [`autumn_web_feature_still_needed_elsewhere`]) reads from there
    /// instead of stale pre-destroy disk content when a path is present,
    /// falling back to `excluding`-gated disk reads otherwise (issue #1048
    /// PR review).
    fn apply(
        &self,
        content: &str,
        project_root: &Path,
        excluding: &[PathBuf],
        overrides: &HashMap<PathBuf, String>,
    ) -> String {
        use super::inbound_mail::remove_inbound_mail_handler;
        use super::schema_edit::{
            remove_autumn_web_dev_dependency_feature, remove_autumn_web_feature, remove_job_entry,
            remove_jobs_registration_from_app, remove_mail_preview_from_app,
            remove_mod_declaration, remove_policy_registration_from_app,
            remove_remember_middleware_from_app, remove_routes_entries, remove_schema_table,
        };
        match self {
            Self::ModDecl { name, .. } => remove_mod_declaration(content, name),
            Self::RoutesEntries { entries, .. } => remove_routes_entries(content, entries),
            Self::SchemaTable {
                table,
                expected_block,
                ..
            } => remove_schema_table(content, table, expected_block),
            Self::CargoDeps { names, .. } => {
                // In addition to the `owner_dir` sibling-directory check the caller
                // already applied, remove a name only if nothing else in the project's
                // source tree still references it — a hand-added dependency unrelated
                // to any generator (#1048 PR review) survives the way a dependency
                // shared with a sibling resource already does. Best-effort: usage via a
                // re-export, or a derive macro that never spells out the crate's own
                // name — a plain `#[derive(Serialize)]` with no qualified `serde::`
                // path — is not detected.
                let survives: Vec<&str> = names
                    .iter()
                    .map(String::as_str)
                    .filter(|name| {
                        !crate_referenced_elsewhere_in_project(
                            project_root,
                            name,
                            excluding,
                            overrides,
                        )
                    })
                    .collect();
                if survives.is_empty() {
                    content.to_owned()
                } else {
                    super::model::remove_cargo_dependencies(content, &survives)
                }
            }
            Self::CargoAutumnWebFeature { feature, .. } => {
                if autumn_web_feature_pinned_by_backend(feature, project_root)
                    || autumn_web_feature_still_needed_elsewhere(
                        feature,
                        project_root,
                        excluding,
                        overrides,
                    )
                {
                    content.to_owned()
                } else {
                    remove_autumn_web_feature(content, feature)
                }
            }
            Self::CargoAutumnWebDevFeature { feature, .. } => {
                if autumn_web_feature_still_needed_elsewhere(
                    feature,
                    project_root,
                    excluding,
                    overrides,
                ) {
                    content.to_owned()
                } else {
                    remove_autumn_web_dev_dependency_feature(content, feature)
                }
            }
            Self::JobEntry { entry, .. } => remove_job_entry(content, entry),
            Self::JobsRegistration { .. } => remove_jobs_registration_from_app(content),
            Self::PolicyRegistration { pascal, snake, .. } => {
                remove_policy_registration_from_app(content, pascal, snake)
            }
            Self::MailPreview { mailer_type, .. } => {
                remove_mail_preview_from_app(content, mailer_type)
            }
            Self::InboundMailHandler {
                handler_module_path,
                ..
            } => remove_inbound_mail_handler(content, handler_module_path),
            Self::SystemTestCargoPatch { snake_name, .. } => {
                super::system_test::remove_cargo_toml_patch(
                    content,
                    snake_name,
                    project_root,
                    excluding,
                )
            }
            Self::PwaMainRsInjection { .. } => super::pwa::remove_pwa_injection(content),
            Self::RememberMiddleware { .. } => remove_remember_middleware_from_app(content),
            Self::AuthOAuthProviderStubs { providers, .. } => {
                super::auth::remove_oauth_provider_stubs(content, providers)
            }
            Self::AuthWebauthnStub { .. } => super::auth::remove_webauthn_stub(content),
            Self::WebhookEndpointStub {
                name, route_path, ..
            } => super::webhook::remove_webhook_endpoint(content, name, route_path),
            Self::SubmitTokenValidateExempt {
                plural, segment, ..
            } => super::scaffold::remove_submit_token_exempt_from_toml(content, plural, segment),
            Self::SeedBinLinks { .. } => super::schema_edit::unlink_models_from_seed_bin(content),
            Self::NestedChildSection { child_plural, .. } => {
                super::nested::remove_nested_child_section(content, child_plural)
            }
            Self::I18nFtlKeys { pascal, snake, .. } => {
                remove_i18n_keys(content, pascal, snake, project_root, excluding, overrides)
            }
        }
    }
}

/// Apply [`Revert::I18nFtlKeys`] to one `.ftl` bundle.
///
/// Split out of [`Revert::apply`] only to keep that match arm short; the
/// interesting part is the second argument to `remove_en_ftl_keys`. Whether any
/// OTHER generated resource still looks chrome keys up is decided by scanning
/// the surviving route modules, NOT by whether they happen to carry a `.ftl`
/// marker comment: a resource whose keys were all hand-authored before it was
/// scaffolded gets no marker (the merge had nothing to add), and taking the
/// shared chrome out from under it would break its build — `t!` validates key
/// existence at COMPILE time. Erring the other way only leaves an unused key,
/// which is a lint warning.
fn remove_i18n_keys(
    content: &str,
    pascal: &str,
    snake: &str,
    project_root: &Path,
    excluding: &[PathBuf],
    overrides: &HashMap<PathBuf, String>,
) -> String {
    // The WHOLE source tree, not just `src/routes`. Chrome keys are ordinary
    // Fluent keys once written, and nothing stops application code reusing
    // them — a `t!(locale, "common.save")` in `src/components/navigation.rs` is
    // exactly the sort of thing a project does. Scanning only the routes
    // directory would call such a key unused when the last scaffold is
    // destroyed, prune it, and break the surviving call at COMPILE time, which
    // is the one failure mode this set exists to prevent. `autumn i18n check`
    // reads the whole tree for the same reason.
    let surviving = keys_still_referenced(content, project_root, excluding, overrides);
    super::scaffold_i18n::remove_en_ftl_keys(content, pascal, snake, &surviving)
}

/// The keys `bundle` defines that project source still reaches — statically, or
/// through a runtime-built key.
///
/// Shared by the two paths that PRUNE a resource's keys, because they have to
/// agree: `destroy` takes the whole block, and a `--force` regeneration that
/// dropped a field takes the keys the new render no longer emits. A key a
/// surviving call site names must outlive both, and `t!` rejects a missing key
/// at COMPILE time, so a set one path honours and the other does not is just a
/// slower way to break the same build.
pub(super) fn keys_still_referenced(
    bundle: &str,
    project_root: &Path,
    excluding: &[PathBuf],
    overrides: &HashMap<PathBuf, String>,
) -> HashSet<String> {
    let scan = scan_surviving_sources(project_root, excluding, overrides);
    keys_still_referenced_in(&scan, bundle)
}

/// [`keys_still_referenced`] against a scan already taken.
///
/// One scan, several bundles: a project whose `t!` validator reads a different
/// file from the one the app loads has BOTH kept in step, and re-walking the
/// source tree per bundle would only give the two a chance to disagree.
pub(super) fn keys_still_referenced_in(
    scan: &crate::i18n::ScanResult,
    bundle: &str,
) -> HashSet<String> {
    // Every key the surviving tree references, NOT just the `common.*` ones.
    // The resource's own keys are ordinary Fluent keys too, and hand-written
    // code reaches for them: a dashboard card or a nav link labelled
    // `t!(locale, "post.index.title")` outlives `src/routes/post.rs`. Deleting
    // the whole marked `post.*` block out from under it breaks the build at
    // COMPILE time — the exact failure this set exists to prevent — and the
    // `common.` prefix was never what made a call site live.
    let mut surviving: HashSet<String> = scan.referenced.iter().cloned().collect();

    // A key built at runtime — `locale.t(&format!("common.{action}"))`, or a bare
    // `locale.t(key)` — names no key a static scan can record, so `scan_source` files it
    // under `dynamic`. Dropping those prunes definitions such a call still reaches at
    // runtime, leaving a missing-key marker in a surviving view. `autumn i18n check`
    // suppresses its unused-key report for exactly these sites, so this must be at least
    // as conservative, or pruning would delete what the checker declines to complain
    // about. `key_prefix` is the leading literal, empty meaning "could be any key", so
    // `starts_with` covers both.
    if !scan.dynamic.is_empty() {
        surviving.extend(
            super::scaffold_i18n::defined_keys(bundle)
                .into_keys()
                .filter(|key| {
                    scan.dynamic
                        .iter()
                        .any(|site| key.starts_with(&site.key_prefix))
                }),
        );
    }
    surviving
}

/// Every file the plan is about to write, as pending content the scan must read
/// INSTEAD of what is on disk.
///
/// A regeneration's own freshly rendered routes are the authority on which keys
/// it still uses; the superseded file on disk names the keys being dropped, and
/// reading that would protect exactly what the reconciliation exists to remove.
pub(super) fn pending_contents(plan: &Plan) -> HashMap<PathBuf, String> {
    plan.actions
        .iter()
        .filter_map(|action| match action {
            Action::Create { path, contents }
            | Action::Modify { path, contents }
            | Action::CreateIfAbsent { path, contents } => Some((path.clone(), contents.clone())),
            Action::CreateBytes { .. } => None,
        })
        .collect()
}

/// Every key still referenced by surviving project source.
///
/// The SET, not a yes/no, and per KEY rather than per block: chrome keys are
/// per-surface, so a resource can be the only user of some of them. Destroying
/// a `--soft-delete` resource while a plain one survives leaves
/// `common.trash`/`restore`/`purge` referenced by nothing, and `autumn i18n
/// check --strict` fails on exactly that — while `common.create`/`save`/… are
/// still very much in use and must stay. A resource's own keys work the same
/// way once hand-written code outside the module reaches for one.
///
/// Parsing is delegated to [`crate::i18n::scan_source`], the `syn`-based
/// scanner behind `autumn i18n check`. That is the authority this set has to
/// agree with — a key it counts and this does not gets pruned out from under a
/// live call, and `t!` rejects that at COMPILE time — and agreement is not
/// something two independently hand-written scanners converge on. The one here
/// had been extended, round after round, for rustfmt line breaks, comments,
/// string literals, arbitrary locale expressions, raw-string keys, and comments
/// before the key; it still recognised only `t!(…)`, never the equally
/// supported `locale.t(…)` / `Locale::t_with(…)`, and its walk started at
/// `src/` while the checker reads the whole project. Both were bugs of the same
/// shape, and neither can recur now.
///
/// The traversal stays here rather than calling `scan_project`, because the
/// generator must read the files it is ABOUT to change from the plan rather
/// than from disk: `overrides` supplies pending content, and `excluding` drops
/// the module being destroyed.
pub(super) fn scan_surviving_sources(
    project_root: &Path,
    excluding: &[PathBuf],
    overrides: &HashMap<PathBuf, String>,
) -> crate::i18n::ScanResult {
    let mut files = Vec::new();
    crate::i18n::collect_rs_files(project_root, &mut files);
    // A pending file that does not exist on disk yet still counts.
    files.extend(overrides.keys().cloned());
    files.sort();
    files.dedup();

    let mut scan = crate::i18n::ScanResult::default();
    for path in files {
        let content = overrides.get(&path).cloned().or_else(|| {
            if excluding.contains(&path) {
                None
            } else {
                fs::read_to_string(&path).ok()
            }
        });
        let Some(content) = content else { continue };
        crate::i18n::scan_source(&content, &path.to_string_lossy(), &mut scan);
    }
    scan
}

/// A complete generator plan — a sequence of actions plus the project root
/// they are anchored against.
#[derive(Debug)]
pub struct Plan {
    /// Project root all action paths are interpreted relative to.
    pub project_root: PathBuf,
    /// The command this plan belongs to, as
    /// [`provenance::current_invocation`] spells it. Recorded beside each
    /// owned file's digest so `destroy` honours the digest only for the same
    /// command with the same arguments (issue #1835).
    pub invocation: String,
    /// The actions this plan will perform when executed.
    pub actions: Vec<Action>,
    /// Advisory messages surfaced to the user on [`Plan::execute`] (both
    /// `--dry-run` and a real run), without failing the generator — e.g. a
    /// `references` field whose target model doesn't exist yet.
    pub warnings: Vec<String>,
    /// In-place edits recorded alongside [`Action::Modify`]s, so
    /// [`Plan::revert`] (`autumn destroy`, issue #1048) can remove exactly
    /// what this plan would have inserted into a shared file.
    pub reverts: Vec<Revert>,
    /// `autumn-web` features this run no longer needs (issue #2328).
    /// [`Plan::settle_released_features`] resolves this list.
    released_features: Vec<ReleasedFeature>,
    /// Whether this plan is the sole resource of its invocation (issue
    /// #2557). Set by [`Plan::claim_sole_resource`].
    sole_resource: bool,
}

/// An `autumn-web` feature a regenerate run no longer needs.
#[derive(Debug)]
struct ReleasedFeature {
    path: PathBuf,
    feature: String,
    /// For a feature with no source marker: a directory, and the file this
    /// run rewrites in it. Other files in the directory keep the feature.
    owner: Option<(PathBuf, PathBuf)>,
}

impl Plan {
    /// Create an empty plan rooted at `project_root`.
    #[must_use]
    pub fn new(project_root: impl Into<PathBuf>) -> Self {
        let project_root = project_root.into();
        Self {
            invocation: provenance::current_invocation(&project_root),
            project_root,
            actions: Vec::new(),
            warnings: Vec::new(),
            reverts: Vec::new(),
            released_features: Vec::new(),
            sole_resource: false,
        }
    }

    /// Claim that this plan is the sole resource of its invocation (issue
    /// #2557).
    ///
    /// A claimed plan records a [`provenance::Scope`] for each file it writes,
    /// and its `revert` sweeps files of this invocation that the plan no longer
    /// names. That is correct only when no other plan of this process shares
    /// the invocation. So one claim succeeds in each process, and later claims
    /// return `false` and leave the plan unclaimed.
    ///
    /// Call it only from a caller that applies one plan in its process (the
    /// CLI dispatcher). Do not call it from a caller that applies many plans.
    pub fn claim_sole_resource(&mut self) -> bool {
        static CLAIMED: AtomicBool = AtomicBool::new(false);
        self.claim_with(&CLAIMED)
    }

    /// [`Self::claim_sole_resource`] against `claimed`.
    fn claim_with(&mut self, claimed: &AtomicBool) -> bool {
        self.sole_resource = !claimed.swap(true, Ordering::SeqCst);
        self.sole_resource
    }

    /// Record an advisory message, printed by [`Plan::execute`] but never
    /// fatal to the plan.
    pub fn warn(&mut self, message: impl Into<String>) {
        self.warnings.push(message.into());
    }

    /// Record a [`Revert`] describing how to undo an in-place edit this plan
    /// makes elsewhere via [`Plan::modify`]. Used by `autumn destroy`
    /// (issue #1048) — irrelevant to a normal `generate` run.
    pub fn push_revert(&mut self, revert: Revert) {
        self.reverts.push(revert);
    }

    /// Record that this run no longer needs `feature` in `path`
    /// (`Cargo.toml`). This is the regenerate pair of
    /// [`Revert::CargoAutumnWebFeature`].
    ///
    /// [`Plan::settle_released_features`] removes it if no other code uses it.
    /// `owner` (directory, own file) applies only to a feature with no
    /// source marker (see [`release_markers`]).
    pub(super) fn release_feature(
        &mut self,
        path: PathBuf,
        feature: &str,
        owner: Option<(PathBuf, PathBuf)>,
    ) {
        self.released_features.push(ReleasedFeature {
            path,
            feature: feature.to_owned(),
            owner,
        });
    }

    /// Remove each released feature that no other code needs.
    ///
    /// Call once, after the last action is queued. Read the pending file
    /// contents, not the files on disk. Then the code that this run
    /// replaces cannot keep its own feature.
    pub(super) fn settle_released_features(&mut self) {
        use super::schema_edit::remove_autumn_web_feature;
        let released = std::mem::take(&mut self.released_features);
        if released.is_empty() {
            return;
        }
        let pending = pending_contents(self);
        for r in released {
            let base = self
                .actions
                .iter()
                .rev()
                .find_map(|a| match a {
                    Action::Modify { path, contents } if path == &r.path => Some(contents.clone()),
                    _ => None,
                })
                .unwrap_or_else(|| fs::read_to_string(&r.path).unwrap_or_default());
            // Marked code or a file next to this one: either keeps the feature.
            // With neither a marker nor an owner, keep it.
            let markers = release_markers(&r.feature);
            let by_marker = markers
                .as_deref()
                .is_some_and(|m| markers_in_project(m, &self.project_root, &[], &pending));
            let by_sibling = r.owner.as_ref().is_some_and(|(dir, own)| {
                resource_dir_has_other_files(dir, std::slice::from_ref(own))
            });
            // Release only what this run takes away. Some file it overwrites
            // used the feature before. A feature that no such file used was
            // not this scaffold's, so keep it.
            // An attachment column enables `multipart` and `storage` together,
            // and an `--api` scaffold uses only `storage` in code.
            let mut used_markers = markers.clone().unwrap_or_default();
            if r.feature == "multipart" {
                used_markers.extend(release_markers("storage").unwrap_or_default());
            }
            let was_used = Some(used_markers.as_slice())
                .filter(|m| !m.is_empty())
                .is_some_and(|m| {
                    self.actions.iter().any(|a| {
                        a.path() != r.path
                            && fs::read_to_string(a.path()).is_ok_and(|old| {
                                m.iter().any(|marker| old.contains(marker.as_str()))
                            })
                    })
                });
            // `htmx` is a default feature. Without default features, other
            // code may need it in ways no marker shows, so keep it.
            let defaults_off = r.feature == "htmx" && base_disables_defaults(&base);
            // Config can run the blob service with no source marker: a
            // `[storage]` block, or `AUTUMN_STORAGE__*` in `.env`.
            let configured = r.feature == "storage" && storage_is_configured(&self.project_root);
            let needed = !was_used
                || by_marker
                || by_sibling
                || defaults_off
                || configured
                || (markers.is_none() && r.owner.is_none());
            if needed {
                continue;
            }
            let updated = remove_autumn_web_feature(&base, &r.feature);
            if updated != base {
                self.actions.retain(|a| a.path() != r.path);
                self.modify(r.path, updated);
            }
        }
    }

    /// Push a [`Action::Create`] action.
    pub fn create(&mut self, path: impl Into<PathBuf>, contents: impl Into<String>) {
        self.actions.push(Action::Create {
            path: path.into(),
            contents: contents.into(),
        });
    }

    /// Push a [`Action::Modify`] action.
    pub fn modify(&mut self, path: impl Into<PathBuf>, contents: impl Into<String>) {
        self.actions.push(Action::Modify {
            path: path.into(),
            contents: contents.into(),
        });
    }

    /// Push a [`Action::CreateBytes`] action (verbatim/binary file).
    pub fn create_bytes(&mut self, path: impl Into<PathBuf>, bytes: impl Into<Vec<u8>>) {
        self.actions.push(Action::CreateBytes {
            path: path.into(),
            bytes: bytes.into(),
        });
    }

    /// Push a [`Action::CreateIfAbsent`] action.
    ///
    /// The file is created atomically using an exclusive open; if the file
    /// already exists (including from a concurrent generator run) the action is
    /// silently skipped — the existing content is left untouched.
    pub fn create_if_absent(&mut self, path: impl Into<PathBuf>, contents: impl Into<String>) {
        self.actions.push(Action::CreateIfAbsent {
            path: path.into(),
            contents: contents.into(),
        });
    }

    /// All `Create` actions whose target file already exists on disk.
    fn collisions(&self) -> Vec<PathBuf> {
        self.actions
            .iter()
            .filter_map(|a| match a {
                Action::Create { path, .. } | Action::CreateBytes { path, .. } if path.exists() => {
                    Some(path.clone())
                }
                _ => None,
            })
            .collect()
    }

    /// Run the plan, honouring `--dry-run` and `--force`.
    ///
    /// On `--dry-run` we print the action list and exit early without touching
    /// the filesystem. On a real run we emit a `Created`/`Modified` line per
    /// action, in the same style as `autumn new`.
    ///
    /// # Errors
    /// Returns [`GenerateError::Collisions`] when any `Create` would overwrite
    /// an existing file and `--force` was not passed; or [`GenerateError::Io`]
    /// for filesystem failures during emission.
    pub fn execute(&self, flags: Flags) -> Result<(), GenerateError> {
        if flags.dry_run {
            self.print_warnings();
            self.print_dry_run();
            return Ok(());
        }

        if !flags.force {
            let collisions = self.collisions();
            if !collisions.is_empty() {
                return Err(GenerateError::Collisions(collisions));
            }
        }

        self.print_warnings();

        // Make sure parent directories of every file action exist.
        let mut dirs: BTreeSet<PathBuf> = BTreeSet::new();
        for action in &self.actions {
            let path = action.path();
            if let Some(parent) = path.parent() {
                dirs.insert(parent.to_path_buf());
            }
        }
        for dir in &dirs {
            fs::create_dir_all(dir)?;
        }

        // Digests of the files this run actually owns, for `revert` to compare
        // against once the template has moved on (issue #1835). Recorded even
        // when a later action fails: the files already written are ours, and a
        // later `destroy` still has to recognise them.
        let mut written: Vec<Written> = Vec::new();
        let result = self.write_actions(&mut written);
        self.record_provenance(written);
        result
    }

    /// Write every action, collecting `(path, digest, scope)` for each file
    /// this plan creates. Split out of [`Self::execute`] so provenance is recorded on the
    /// error path too.
    fn write_actions(&self, written: &mut Vec<Written>) -> Result<(), GenerateError> {
        for action in &self.actions {
            let path = action.path();
            match action {
                Action::Create { contents, .. } | Action::Modify { contents, .. } => {
                    let label = if matches!(action, Action::Modify { .. }) && path.exists() {
                        "Modified"
                    } else {
                        "Created"
                    };
                    fs::write(path, contents)?;
                    // A `Modify` target is shared — other resources and the
                    // developer write to it too — so this plan never owns it.
                    if matches!(action, Action::Create { .. }) {
                        written.push((
                            path.to_path_buf(),
                            provenance::text_digest(contents),
                            provenance::Scope::Owned,
                        ));
                    }
                    println!("  {label} {}", relative_display(path, &self.project_root));
                }
                Action::CreateBytes { bytes, .. } => {
                    fs::write(path, bytes)?;
                    written.push((
                        path.to_path_buf(),
                        provenance::bytes_digest(bytes),
                        provenance::Scope::Owned,
                    ));
                    println!("  Created {}", relative_display(path, &self.project_root));
                }
                Action::CreateIfAbsent { contents, .. } => {
                    match fs::OpenOptions::new()
                        .write(true)
                        .create_new(true)
                        .open(path)
                    {
                        Ok(mut f) => {
                            if let Err(e) = f.write_all(contents.as_bytes()) {
                                // Remove the empty/partial file so the next run
                                // does not skip creation due to AlreadyExists.
                                let _ = fs::remove_file(path);
                                return Err(GenerateError::Io(e));
                            }
                            written.push((
                                path.to_path_buf(),
                                provenance::text_digest(contents),
                                provenance::Scope::Shared,
                            ));
                            println!("  Created {}", relative_display(path, &self.project_root));
                        }
                        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                            // Another process already created the file; leave it
                            // untouched — and unrecorded: this run did not write it.
                        }
                        Err(e) => return Err(GenerateError::Io(e)),
                    }
                }
            }
        }
        Ok(())
    }

    /// Record what this run wrote, so a later `destroy` can tell its own
    /// output from a developer's edit even after the template changed
    /// (issue #1835).
    ///
    /// Best effort: a manifest that cannot be written leaves `destroy`
    /// comparing against the current render alone — the behaviour before this
    /// existed — so it warns rather than failing a generator run that has
    /// already written every file it promised.
    fn record_provenance(&self, written: Vec<Written>) {
        if written.is_empty() {
            return;
        }
        let mut recorded = provenance::Provenance::load(&self.project_root);
        for (path, digest, scope) in written {
            // Only a claimed plan may mark a file as sweepable (issue #2557).
            let scope = self.sole_resource.then_some(scope);
            recorded.record(&self.project_root, &path, digest, &self.invocation, scope);
        }
        // Only a claimed plan records anchors. An unclaimed plan can share its
        // invocation with other plans, and their edits must not count against it.
        if self.sole_resource {
            recorded.record_reverts(&self.invocation, self.revert_anchors());
        }
        if let Err(e) = recorded.save(&self.project_root) {
            eprintln!(
                "Warning: could not record generated-file provenance in {}: {e}. \
                 `autumn destroy` may need --force after a CLI upgrade.",
                provenance::MANIFEST_PATH
            );
        }
    }

    /// The anchors of this plan's reverts (issue #2560).
    fn revert_anchors(&self) -> Vec<provenance::RevertAnchor> {
        let mut anchors: Vec<_> = self
            .reverts
            .iter()
            .flat_map(|r| r.anchors(&self.project_root))
            // A target outside the project can never be checked.
            .filter(provenance::RevertAnchor::is_project_relative)
            .collect();
        anchors.sort();
        anchors.dedup();
        anchors
    }

    /// Print every advisory warning to stderr. Called only on a path that
    /// will actually run (dry-run or a real, non-colliding execution) — never
    /// before a `--force`/collision check that might abort the plan, so a
    /// failed, no-op run never emits misleading warnings about a plan that
    /// was never applied.
    fn print_warnings(&self) {
        for warning in &self.warnings {
            eprintln!("Warning: {warning}");
        }
    }

    fn print_dry_run(&self) {
        println!("Dry run — no files written.");
        for action in &self.actions {
            let label = match action {
                Action::Create { path, .. } | Action::CreateBytes { path, .. } if path.exists() => {
                    "Would overwrite"
                }
                Action::Modify { path, .. } if path.exists() => "Would modify",
                Action::CreateIfAbsent { path, .. } if path.exists() => "Would skip (exists)",
                Action::Create { .. }
                | Action::Modify { .. }
                | Action::CreateBytes { .. }
                | Action::CreateIfAbsent { .. } => "Would create",
            };
            println!(
                "  {label} {}",
                relative_display(action.path(), &self.project_root)
            );
        }
    }

    /// Undo this plan — the deterministic inverse of [`Plan::execute`]
    /// driving `autumn destroy` (issue #1048).
    ///
    /// For each `Create`/`CreateBytes` action, deletes the target file
    /// (refusing when its on-disk content has diverged from what `generate`
    /// would have produced, unless `--force`). A `CreateIfAbsent` target
    /// (a file shared across resources that `generate` only ever writes
    /// once) is deleted only when its content still matches exactly —
    /// divergence there is left alone with a warning instead, never
    /// force-deleted, since it may predate this resource entirely rather
    /// than being this destroy's own edit gone stale. Either way, prunes any
    /// now-empty generated directories afterward. For each [`Revert`] recorded via
    /// [`Plan::push_revert`], removes exactly the lines/entries `generate`
    /// inserted from the current file — never touching content this plan
    /// didn't itself add. A file emptied down to nothing by its reverts is
    /// deleted outright (e.g. a `schema.rs`/`mod.rs` that only ever held
    /// this resource's single entry).
    ///
    /// Migration directories are matched by resource-name suffix, since
    /// destroy recomputes the plan with a fresh timestamp that won't match
    /// the original directory, and are removed only when not yet applied to
    /// a configured database — destroy never touches the database itself.
    ///
    /// A claimed plan (see [`Plan::claim_sole_resource`]) also sweeps files
    /// this invocation wrote that the plan no longer names (issue #2557). See
    /// `sweep::plan_sweep`.
    ///
    /// Honours `--dry-run` (prints `Would remove`/`Would revert` lines,
    /// touches nothing) exactly like [`Plan::execute`].
    ///
    /// # Errors
    /// Returns [`GenerateError::Diverged`] when any targeted file's content
    /// no longer matches what `generate` would have produced and `--force`
    /// was not given; or [`GenerateError::Io`] for filesystem failures.
    pub fn revert(&self, flags: Flags) -> Result<(), GenerateError> {
        let plan = self.compute_revert_plan(flags.force);

        if flags.dry_run {
            println!("Dry run — no files removed.");
            for path in &plan.files_to_remove {
                println!(
                    "  Would remove {}{}",
                    relative_display(path, &self.project_root),
                    plan.sweep_note(path)
                );
            }
            for dir in &plan.migrations_to_remove {
                println!(
                    "  Would remove {}",
                    relative_display(dir, &self.project_root)
                );
            }
            for (path, new_content) in &plan.modifies {
                let label = if new_content.is_none() {
                    "Would remove"
                } else {
                    "Would revert"
                };
                println!("  {label} {}", relative_display(path, &self.project_root));
            }
            if !plan.diverged.is_empty() {
                println!(
                    "  A real run would refuse (without --force) — content has diverged from what generate produced:"
                );
                for path in &plan.diverged {
                    println!(
                        "    Diverged {}",
                        relative_display(path, &self.project_root)
                    );
                }
            }
            if !plan.dropped_reverts.is_empty() {
                println!(
                    "  A real run refuses without --force. It would leave these edits behind:"
                );
                for anchor in &plan.dropped_reverts {
                    println!("    {anchor}");
                }
            }
            for warning in &plan.warnings {
                eprintln!("Warning: {warning}");
            }
            return Ok(());
        }

        if !plan.diverged.is_empty() && !flags.force {
            return Err(GenerateError::Diverged(plan.diverged));
        }
        if !plan.dropped_reverts.is_empty() {
            return Err(GenerateError::RevertsDropped(plan.dropped_reverts));
        }

        for warning in &plan.warnings {
            eprintln!("Warning: {warning}");
        }

        let mut touched_dirs: Vec<PathBuf> = Vec::new();
        // What was actually removed, so the manifest is pruned to match even
        // when a later removal fails part-way (issue #1835).
        let mut removed = Removed {
            stale: plan.stale.clone(),
            ..Removed::default()
        };
        let result = self.apply_revert(&plan, &mut touched_dirs, &mut removed);

        for dir in touched_dirs {
            prune_empty_ancestors(dir, &self.project_root);
        }

        self.forget_provenance(&removed, result.is_ok());
        result?;

        // Nested sub-module declarations (e.g. `src/mailers/mod.rs`'s
        // `pub mod previews;`) must be synced BEFORE `src/main.rs`'s, so a
        // now-empty-and-deleted `src/mailers/mod.rs` is already gone by the
        // time the `mod mailers;` orphan check runs.
        sync_mod_declarations_in(
            &self.project_root.join("src").join("mailers"),
            &["previews"],
            &self.project_root,
        );
        sync_main_rs_mod_declarations(&self.project_root);

        Ok(())
    }

    /// Delete and rewrite what `plan` calls for, recording what actually went.
    ///
    /// Split out of [`Self::revert`] so the manifest is pruned on the error
    /// path too: a run that removes three files and then fails on the fourth
    /// must not leave the manifest describing files that are already gone.
    fn apply_revert(
        &self,
        plan: &RevertPlan,
        touched_dirs: &mut Vec<PathBuf>,
        removed: &mut Removed,
    ) -> Result<(), GenerateError> {
        // The reverts below were computed with every swept file gone (the
        // dependency scans skip them). If one changed since the plan was
        // made, those reverts are wrong for it, so change nothing at all.
        let changed: Vec<PathBuf> = plan
            .swept
            .iter()
            .filter(|(path, digest)| !sweep::still_sweepable(&self.project_root, path, digest))
            .map(|(path, _)| path.clone())
            .collect();
        if !changed.is_empty() {
            return Err(GenerateError::Diverged(changed));
        }
        for path in &plan.files_to_remove {
            let expected = plan.swept.get(path);
            let swept = expected.is_some();
            // Check a swept path once more just before its delete. A change
            // since the check above makes the reverts below wrong for it, so
            // stop here and apply none of them.
            if expected
                .is_some_and(|digest| !sweep::still_sweepable(&self.project_root, path, digest))
            {
                return Err(GenerateError::Diverged(vec![path.clone()]));
            }
            match fs::remove_file(path) {
                // Two manifest spellings of one file: the first removal won.
                Err(e) if swept && e.kind() == std::io::ErrorKind::NotFound => continue,
                other => other?,
            }
            removed.files.push(path.clone());
            if let Some(keys) = plan.recorded_keys.get(path) {
                removed.keys.extend_from_slice(keys);
            }
            println!(
                "  Removed {}{}",
                relative_display(path, &self.project_root),
                plan.sweep_note(path)
            );
            if let Some(parent) = path.parent() {
                touched_dirs.push(parent.to_path_buf());
            }
        }

        for dir in &plan.migrations_to_remove {
            fs::remove_dir_all(dir)?;
            removed.dirs.push(dir.clone());
            println!("  Removed {}", relative_display(dir, &self.project_root));
            touched_dirs.push(self.project_root.join("migrations"));
        }

        for (path, new_content) in &plan.modifies {
            if let Some(content) = new_content {
                fs::write(path, content)?;
                println!("  Reverted {}", relative_display(path, &self.project_root));
            } else {
                fs::remove_file(path)?;
                println!("  Removed {}", relative_display(path, &self.project_root));
                if let Some(parent) = path.parent() {
                    touched_dirs.push(parent.to_path_buf());
                }
            }
        }
        Ok(())
    }

    /// Drop the provenance entries for the files this revert removed, so the
    /// manifest does not outlive what it describes (issue #1835).
    ///
    /// Best effort, like [`Self::record_provenance`]: the files are already
    /// gone, and failing here would report a destroy that in fact succeeded.
    fn forget_provenance(&self, removed: &Removed, finished: bool) {
        // A finished destroy has reverted the run's edits, or the user chose
        // `--force`. Only a claimed plan owns its run (issue #2560).
        let forget_run = finished && self.sole_resource;
        if removed.files.is_empty()
            && removed.dirs.is_empty()
            && removed.stale.is_empty()
            && !forget_run
        {
            return;
        }
        let mut recorded = provenance::Provenance::load(&self.project_root);
        if recorded.is_empty() {
            return;
        }
        if forget_run {
            recorded.forget_run(&self.invocation);
        }
        for path in removed.files.iter().chain(&removed.stale) {
            recorded.forget(&self.project_root, path);
        }
        // A removed file can be recorded under another spelling (issue #3382).
        for key in &removed.keys {
            recorded.forget_key(key);
        }
        for dir in &removed.dirs {
            recorded.forget_dir(&self.project_root, dir);
        }
        if let Err(e) = recorded.save(&self.project_root) {
            eprintln!(
                "Warning: could not update {} after destroy: {e}",
                provenance::MANIFEST_PATH
            );
        }
    }

    /// Compute what [`Plan::revert`] would do, without touching disk except
    /// to read files for divergence comparison. Shared by the `--dry-run`
    /// and real-run paths of `revert` so they can never disagree.
    #[allow(
        clippy::too_many_lines,
        reason = "a linear sequence of independent passes (normal files, migrations, \
                  create-if-absent shared files, modify reverts) that share the \
                  files_to_remove/diverged accumulators — splitting it up would just \
                  move the same state-threading around, not simplify it"
    )]
    fn compute_revert_plan(&self, force: bool) -> RevertPlan {
        let migrations_root = self.project_root.join("migrations");
        // What a matching `generate` recorded writing. A file matching either
        // the current render or this baseline is the generator's own output,
        // however far the template has moved since (issue #1835).
        let recorded = provenance::Provenance::load(&self.project_root);
        let baseline = Baseline {
            recorded: &recorded,
            invocation: &self.invocation,
        };

        // `Create`/`CreateBytes`/`CreateIfAbsent` actions living directly
        // under `migrations/<dir>/` need suffix-based matching (see
        // `resolve_migration_removal`); everything else is a normal,
        // path-stable file to check-and-delete.
        let mut migration_groups: Vec<(PathBuf, Vec<&Action>)> = Vec::new();
        let mut normal_actions: Vec<&Action> = Vec::new();
        // `CreateIfAbsent` actions for a *shared* file (e.g. a mailer's
        // `templates/mailers/_layout.html`) are deferred to their own pass
        // below — unlike an owned `Create`, a later resource's `generate`
        // call silently skips writing to it once an earlier resource's call
        // already created it, so the action being present in THIS resource's
        // plan doesn't mean this resource is the only one still using it.
        let mut create_if_absent_actions: Vec<&Action> = Vec::new();
        for action in &self.actions {
            if matches!(action, Action::Modify { .. }) {
                continue;
            }
            let path = action.path();
            if let Some(dir) = path.parent()
                && dir.parent() == Some(migrations_root.as_path())
            {
                if let Some(entry) = migration_groups.iter_mut().find(|(d, _)| d == dir) {
                    entry.1.push(action);
                } else {
                    migration_groups.push((dir.to_path_buf(), vec![action]));
                }
                continue;
            }
            if matches!(action, Action::CreateIfAbsent { .. }) {
                create_if_absent_actions.push(action);
            } else {
                normal_actions.push(action);
            }
        }

        // Files this invocation wrote that the plan no longer names (issue
        // #2557). Only a claimed plan sweeps. A swept file joins
        // `files_to_remove` first, so every scan below treats it as leaving.
        let sweep = if self.sole_resource {
            let revert_targets: Vec<&Path> = self.reverts.iter().map(Revert::path).collect();
            sweep::plan_sweep(
                &self.project_root,
                &recorded,
                &self.invocation,
                &self.actions,
                &revert_targets,
            )
        } else {
            sweep::Sweep::default()
        };
        // Edits that `generate` made and this plan does not revert (issue
        // #2560). Only a claimed plan checks them (see
        // `Plan::claim_sole_resource`). `--force` skips the check.
        let dropped_reverts = if force || !self.sole_resource {
            Vec::new()
        } else {
            recorded.dropped_reverts(&self.project_root, &self.invocation, &self.revert_anchors())
        };
        let mut files_to_remove = sweep.remove.clone();
        let mut diverged = Vec::new();
        let mut warnings = sweep.warnings;
        for action in normal_actions {
            let path = action.path();
            if !path.exists() {
                continue; // already gone — idempotent skip.
            }
            let matches = is_generator_output(action, path, &self.project_root, baseline);
            if matches || force {
                files_to_remove.push(path.to_path_buf());
            } else {
                diverged.push(path.to_path_buf());
            }
        }

        // Now resolve the deferred `CreateIfAbsent` actions: only remove a
        // shared file once its directory holds no other file this destroy
        // isn't itself already removing — including sibling `CreateIfAbsent`
        // files from the SAME batch (excluded up front, so whichever one is
        // checked first doesn't see the other, still-unprocessed one as
        // false evidence that the directory is still occupied).
        let create_if_absent_paths: Vec<PathBuf> = create_if_absent_actions
            .iter()
            .map(|a| a.path().to_path_buf())
            .collect();
        for action in create_if_absent_actions {
            let path = action.path();
            if !path.exists() {
                continue;
            }
            if let Some(dir) = path.parent() {
                let mut excluding = files_to_remove.clone();
                excluding.extend(create_if_absent_paths.iter().cloned());
                if resource_dir_has_other_files(dir, &excluding) {
                    continue; // a sibling resource's file still lives here — keep it.
                }
            }
            let matches = is_generator_output(action, path, &self.project_root, baseline);
            if matches {
                files_to_remove.push(path.to_path_buf());
            } else {
                // Unlike an owned `Create`, a `CreateIfAbsent` target may have existed
                // before any generator ran — `generate` silently skips writing to it
                // either way — such as a hand-rolled
                // `templates/mailers/_layout.html`. Divergence here cannot be
                // attributed to this destroy's own edit gone stale the way it can for
                // an owned `Create`, so it is never a blocking error and never
                // force-deleted (#1048 PR review): guessing wrong would destroy real,
                // pre-existing project content this destroy never touched. Leave it and
                // say why.
                warnings.push(format!(
                    "{} doesn't match what this generator produces; leaving it in \
                     place since it may predate this resource — remove it by hand \
                     if it's actually orphaned.",
                    relative_display(path, &self.project_root),
                ));
            }
        }

        let mut migrations_to_remove = Vec::new();
        for (dir, actions) in &migration_groups {
            match resolve_migration_removal(
                dir,
                actions,
                &migrations_root,
                force,
                &self.project_root,
                &files_to_remove,
                baseline,
            ) {
                MigrationOutcome::Remove(real_dir) => migrations_to_remove.push(real_dir),
                MigrationOutcome::Diverged(path) => diverged.push(path),
                MigrationOutcome::Applied(real_dir) => warnings.push(format!(
                    "migration {} appears to be applied to the database; skipping it \
                     — write a down-migration instead. destroy never touches the database.",
                    relative_display(&real_dir, &self.project_root),
                )),
                MigrationOutcome::Ambiguous(suffix) => warnings.push(format!(
                    "multiple migrations directories match the expected suffix '{suffix}'; \
                     skipping — remove the correct one manually."
                )),
                MigrationOutcome::StillNeededElsewhere(real_dir) => warnings.push(format!(
                    "migration {} is still needed by another mailer's --list-unsubscribe; \
                     skipping — pass --force to remove it anyway.",
                    relative_display(&real_dir, &self.project_root),
                )),
                MigrationOutcome::StillNeededByCommentable(real_dir) => warnings.push(format!(
                    "migration {} creates the `comments` table that another `#[commentable]` \
                     model still uses; skipping — pass --force to remove it anyway.",
                    relative_display(&real_dir, &self.project_root),
                )),
                MigrationOutcome::NotFound => {}
            }
        }

        let grouped_reverts = group_reverts_by_path(&self.reverts);
        // Every path this destroy is itself rewriting — `src/schema.rs`, emptied by a
        // `SchemaTable` revert — must be excluded from
        // `crate_referenced_elsewhere_in_project`'s scan alongside `files_to_remove`.
        // Its pre-destroy content, still on disk at scan time since the real rewrite
        // happens later in `Plan::revert`'s apply phase, is not evidence of anything a
        // different resource still needs, because this same operation is about to change
        // it too. `scan_overrides` below supplies each such file's real final content
        // instead, so this exclusion only ever falls back to "treat as absent" for a file
        // that becomes empty, never for one that survives with other content.
        let mut cargo_deps_excluding = files_to_remove.clone();
        cargo_deps_excluding.extend(grouped_reverts.iter().map(|(path, _)| path.clone()));

        // Precompute the final, post-destroy content of every modified file other than
        // `Cargo.toml`, via each file's own self-contained reverts — none of
        // `SchemaTable`, `ModDecl`, and the rest consult another file's content.
        // `Cargo.toml`'s `CargoDeps`, `CargoAutumnWebFeature`, and
        // `CargoAutumnWebDevFeature` reverts are the only ones that do, through the
        // project-wide crate and feature usage scan, and they always target `Cargo.toml`
        // itself — so computing every other file's result first and excluding
        // `Cargo.toml` here avoids an ordering cycle. That is what lets the scan see what
        // `src/schema.rs`, `src/main.rs`, or a `mod.rs` will actually look like once this
        // destroy is done: a table this destroy is not touching, still present after its
        // own removal. The alternatives are worse — stale pre-destroy content would
        // wrongly count a table being removed as still needed, and hiding the file from
        // the scan entirely would wrongly hide unrelated content in the same file that
        // legitimately still needs the dependency (#1048 PR review).
        let cargo_toml_path = self.project_root.join("Cargo.toml");
        let mut scan_overrides: HashMap<PathBuf, String> = HashMap::new();
        for (path, reverts) in &grouped_reverts {
            if *path == cargo_toml_path || !path.exists() {
                continue;
            }
            let Ok(original) = fs::read_to_string(path) else {
                continue;
            };
            let mut content = original;
            for revert in reverts {
                if let Some(dir) = revert.owner_dir()
                    && resource_dir_has_other_files(dir, &files_to_remove)
                {
                    continue;
                }
                content = revert.apply(
                    &content,
                    &self.project_root,
                    &cargo_deps_excluding,
                    &scan_overrides,
                );
            }
            if !content.trim().is_empty() {
                scan_overrides.insert(path.clone(), content);
            }
        }

        let mut modifies = Vec::new();
        for (path, reverts) in grouped_reverts {
            if !path.exists() {
                continue;
            }
            let Ok(original) = fs::read_to_string(&path) else {
                continue;
            };
            let mut content = original.clone();
            for revert in &reverts {
                if let Some(dir) = revert.owner_dir()
                    && resource_dir_has_other_files(dir, &files_to_remove)
                {
                    // A sibling resource of the same generator still lives
                    // in `owner_dir` and may still need this dependency or
                    // feature — leave the Cargo.toml edit in place.
                    continue;
                }
                content = revert.apply(
                    &content,
                    &self.project_root,
                    &cargo_deps_excluding,
                    &scan_overrides,
                );
            }
            if content == original {
                continue;
            }
            if content.trim().is_empty() {
                modifies.push((path, None));
            } else {
                modifies.push((path, Some(content)));
            }
        }

        RevertPlan {
            recorded_keys: files_to_remove
                .iter()
                .map(|path| (path.clone(), recorded.keys_for(&self.project_root, path)))
                .collect(),
            files_to_remove,
            migrations_to_remove,
            modifies,
            diverged,
            dropped_reverts,
            warnings,
            swept: sweep.digests,
            stale: sweep.forget,
        }
    }
}

/// One file [`Plan::execute`] wrote: path, digest, scope.
/// [`Plan::record_provenance`] keeps the scope only for a claimed plan.
type Written = (PathBuf, String, provenance::Scope);

/// What a real [`Plan::revert`] actually deleted — the plan minus whatever a
/// mid-run failure stopped it from reaching. The provenance manifest is pruned
/// against this, never against the plan (issue #1835).
#[derive(Default)]
struct Removed {
    files: Vec<PathBuf>,
    dirs: Vec<PathBuf>,
    /// Entries for files that were already gone (issue #2557).
    stale: Vec<PathBuf>,
    /// The manifest keys of `files`, from [`RevertPlan::recorded_keys`].
    keys: Vec<String>,
}

/// The concrete result of [`Plan::compute_revert_plan`] — everything
/// [`Plan::revert`] needs to either print (`--dry-run`) or perform (a real
/// run), computed exactly once so the two paths can't disagree.
struct RevertPlan {
    files_to_remove: Vec<PathBuf>,
    migrations_to_remove: Vec<PathBuf>,
    /// `(path, new_content)`; `None` means the file should be deleted
    /// (its reverts emptied it down to nothing).
    modifies: Vec<(PathBuf, Option<String>)>,
    diverged: Vec<PathBuf>,
    /// Recorded reverts that this plan does not contain (issue #2560).
    dropped_reverts: Vec<provenance::RevertAnchor>,
    warnings: Vec<String>,
    /// Files the orphan sweep removes, with their recorded digests (issue
    /// #2557). Also in `files_to_remove`.
    swept: HashMap<PathBuf, String>,
    /// Entries whose file is already gone. Dropped from the manifest.
    stale: Vec<PathBuf>,
    /// The manifest keys of each file in `files_to_remove`, read before the
    /// delete. A case-only alias resolves only while the file exists (issue
    /// #3382).
    recorded_keys: HashMap<PathBuf, Vec<String>>,
}

impl RevertPlan {
    /// The note printed after a swept path.
    fn sweep_note(&self, path: &Path) -> &'static str {
        if self.swept.contains_key(path) {
            " (no longer generated)"
        } else {
            ""
        }
    }
}

/// Group `reverts` by target path, preserving push order both across groups
/// and within each group.
fn group_reverts_by_path(reverts: &[Revert]) -> Vec<(PathBuf, Vec<&Revert>)> {
    let mut groups: Vec<(PathBuf, Vec<&Revert>)> = Vec::new();
    for revert in reverts {
        let path = revert.path().to_path_buf();
        if let Some(entry) = groups.iter_mut().find(|(p, _)| p == &path) {
            entry.1.push(revert);
        } else {
            groups.push((path, vec![revert]));
        }
    }
    groups
}

/// Remove `dir` and walk up removing each now-empty ancestor, stopping at
/// the first non-empty directory (or `project_root`). `fs::remove_dir`
/// fails harmlessly on a non-empty or already-missing directory, which is
/// exactly the stopping condition we want.
fn prune_empty_ancestors(mut dir: PathBuf, project_root: &Path) {
    while dir != *project_root && dir.starts_with(project_root) {
        if fs::remove_dir(&dir).is_err() {
            break;
        }
        match dir.parent() {
            Some(parent) => dir = parent.to_path_buf(),
            None => break,
        }
    }
}

/// Whether `dir` contains any regular file other than the ones this same
/// destroy operation is itself about to delete (`excluding` — the
/// already-computed `files_to_remove`). Used to gate
/// [`Revert::CargoDeps`]/[`Revert::CargoAutumnWebFeature`]/[`Revert::CargoAutumnWebDevFeature`]:
/// a dependency or feature shared by multiple resources of the same
/// generator (e.g. two `model`s both using `uuid`, two `mailer`s both using
/// the `mail` feature) must survive destroying just one of them. A missing
/// or unreadable `dir` counts as "no other files" (nothing left to protect).
fn resource_dir_has_other_files(dir: &Path, excluding: &[PathBuf]) -> bool {
    let Ok(entries) = fs::read_dir(dir) else {
        return false;
    };
    entries.filter_map(Result::ok).any(|entry| {
        let path = entry.path();
        // `mod.rs` is the shared aggregator every one of these directories
        // has (declaring `pub mod <resource>;` per file) — it is not itself
        // a resource, so its mere presence must never count as "a sibling
        // resource still needs this dependency/feature".
        path.is_file()
            && path.file_name() != Some(std::ffi::OsStr::new("mod.rs"))
            && !excluding.contains(&path)
    })
}

/// Whether `crate_name`'s Rust identifier (`-` replaced with `_`) is
/// referenced anywhere under `project_root`'s `src/`, `tests/`, or
/// `benches/` trees — other than in `excluding` (this same destroy's own
/// file deletions). A whole-project extension of [`resource_dir_has_other_files`]
/// for [`Revert::CargoDeps`]: a project may hand-add a dependency for its
/// own reasons with no generated resource ever touching it, so checking
/// only the generator's `owner_dir` isn't enough to avoid stripping it.
///
/// Best-effort, not exhaustive: looks for `{ident}::` (a qualified path) or
/// `use {ident}` (an import) as plain substrings; a crate used only via a
/// re-export or a derive macro that never spells out its own name (e.g.
/// bare `#[derive(Serialize)]` with no qualified `serde::` path anywhere)
/// is not detected.
fn crate_referenced_elsewhere_in_project(
    project_root: &Path,
    crate_name: &str,
    excluding: &[PathBuf],
    overrides: &HashMap<PathBuf, String>,
) -> bool {
    crate_reference_site(project_root, crate_name, excluding, overrides).is_some()
}

/// The first file under `project_root`'s `src/`, `tests/`, or `benches/` tree
/// that still names `crate_name`, or `None` when nothing does.
///
/// The site-returning half of [`crate_referenced_elsewhere_in_project`], with
/// the same best-effort caveats. `autumn plugin remove` (issue #1631) uses it
/// to decide whether stripping a plugin's dependency would break code the user
/// wrote by hand — and, when it would, to say which file to look at.
pub fn crate_reference_site(
    project_root: &Path,
    crate_name: &str,
    excluding: &[PathBuf],
    overrides: &HashMap<PathBuf, String>,
) -> Option<PathBuf> {
    let markers = crate_reference_markers(crate_name);
    // `examples` alongside the build targets: an example that uses the crate is
    // a target that stops compiling when the dependency goes (issue #1631
    // review). Erring toward retaining a dependency only ever costs an unused
    // manifest line; erring the other way breaks a build.
    ["src", "tests", "benches", "examples"]
        .iter()
        .find_map(|dir| {
            rs_tree_marker_site(&project_root.join(dir), &markers, excluding, overrides)
        })
}

/// The text markers that indicate `crate_name` is in use in Rust source.
///
/// One definition, because two callers scan different file sets with them —
/// [`crate_reference_site`]'s conventional trees and `plugin::remove`'s
/// explicit Cargo target paths — and a marker present in one set but not the
/// other is a dependency stripped from under code that still needs it.
///
/// Three spellings reach a crate by name:
///
/// - `{ident}::` — a qualified path.
/// - `use {ident}` — an import, including `use {ident} as alias;`, which this
///   prefix already covers.
/// - `extern crate {ident}` — the 2015-edition form, still legal in every
///   edition. It is the one spelling that carries NEITHER of the others when
///   aliased: `extern crate autumn_admin_plugin as admin;` followed by
///   `admin::…` contains no `{ident}::` and no `use {ident}` anywhere (issue
///   #1631 review).
///
/// These are substring probes, not a parse. Best-effort in both directions: a
/// crate reached only through a re-export, or a derive macro that never spells
/// the crate's own name, is not detected; and a crate whose name EXTENDS this
/// one (`autumn-admin-plugin-extras`) matches. The two errors are not
/// symmetric — over-retaining leaves an unused manifest line, under-retaining
/// strips a dependency out from under code that still compiles against it — so
/// the loose direction is the deliberate one.
#[must_use]
pub fn crate_reference_markers(crate_name: &str) -> Vec<String> {
    let ident = crate_name.replace('-', "_");
    vec![
        format!("{ident}::"),
        format!("use {ident}"),
        format!("extern crate {ident}"),
    ]
}

/// Text markers that reliably indicate `feature`'s autumn-web API surface
/// is in use somewhere in the project — used as a whole-project supplement
/// to the same-generator `owner_dir` sibling check for
/// [`Revert::CargoAutumnWebFeature`]/[`Revert::CargoAutumnWebDevFeature`],
/// since a feature can be needed by a COMPLETELY DIFFERENT generator kind
/// than the one being destroyed (e.g. `generate auth` and `generate mailer`
/// both need `"mail"` — destroying the only mailer must not strip it while
/// auth's routes still call `Mail::builder()`). Any one marker matching is
/// sufficient evidence. Empty for a feature with no reliable marker — falls
/// back to the `owner_dir` check alone.
fn autumn_web_feature_markers(feature: &str) -> &'static [&'static str] {
    match feature {
        // `maud` and `htmx` are in autumn-web's own `default = [...]` feature set (see
        // `autumn/Cargo.toml`), so a project's default-features dependency already
        // carries them regardless of any generator. Removing the explicit `features =
        // [...]` entry therefore never disables the capability, and a project-wide
        // marker check would wrongly treat autumn's own default-feature boilerplate —
        // `src/main.rs`'s stock `layout()`, which always calls `maud::html!` — as still
        // needed in every project. No check needed: fall through to the `owner_dir`
        // check alone.
        "mail" => &["Mail::builder("],
        "oauth2" => &["OAuth2"],
        "webauthn" => &["Webauthn"],
        // Real WebSocket-transport channels (`#[ws]`) AND SSE-transport
        // channels/`--live` scaffolds (`autumn_web::sse::stream(`, no
        // `#[ws]` marker at all) are both gated behind the same "ws"
        // feature (issue #1048 PR review: destroying the only channel/live
        // scaffold of one transport must not strip a feature the other
        // transport, generated separately, still needs).
        //
        // The prelude re-exports the `ws` types unqualified (`Channels`,
        // `Broadcast`, `ChannelMessage`, `ChannelStats`), so a route that
        // uses `autumn_web::prelude::*` names none of the paths above.
        "ws" => &[
            "#[ws]",
            "autumn_web::sse::stream",
            "autumn_web::channels",
            "Channels",
            "Broadcast",
            "ChannelMessage",
            "ChannelStats",
        ],
        // `TestDb::` (not bare `TestDb`) so a doc comment merely mentioning
        // the type (e.g. the template-shipped `tests/integration_test.rs`'s
        // "Add DB-backed tests with `TestDb`...") doesn't count as usage.
        "test-support" => &["TestDb::"],
        // Attachment scaffolds (`generate scaffold ... --attachment`) enable both
        // `multipart` and `storage`, but a hand-written route can use these APIs
        // directly. Destroying the last attachment model must not strip a feature such
        // a route still needs (PR #1867 review).
        //
        // Bare `Multipart`, not `extract::Multipart`, so the marker also catches a
        // hand-written route that pulls the extractor in through `use
        // autumn_web::prelude::*;` and names it unqualified. The prelude re-exports
        // `Multipart` (`autumn/src/prelude.rs`), so such a route contains neither
        // `extract::Multipart` nor any storage path, and the narrower marker would let
        // `destroy` wrongly strip the feature. This still matches the fully-qualified
        // `autumn_web::extract::Multipart` the scaffold emits and any `use
        // ...::Multipart;` import; the only extra hits are identifiers like
        // `MultipartField` and `MultipartError`, themselves part of the multipart API
        // surface, so over-retaining on them is harmless.
        "multipart" => &["Multipart"],
        // The prelude does not re-export storage types (`Blob`,
        // `BlobStoreState`, …), so each use starts with `autumn_web::storage`.
        // The marker has no trailing `::` (issue #2186). A module import
        // (`use autumn_web::storage;` or `… as blobs;`) ends at the module name.
        // A doc comment that names the module now also keeps the feature.
        // This extra match is safe. `multipart` and `csv` accept the same risk.
        "storage" => &["autumn_web::storage"],
        // A `richtext` scaffold (issue #1255) enables `markdown` for
        // `render_user_content`. Hand-written code can also use `render` or
        // `MarkdownRegistry`. The prelude re-exports none of them, so each use
        // starts with `autumn_web::markdown`. The marker has no trailing `::`,
        // for the same reason as `storage` (issue #2186).
        "markdown" => &["autumn_web::markdown"],
        // Widget families (issue #3408). A scaffold renders these widgets by
        // their full path, and hand-written code may import them. Each marker
        // is a widget fn or config type name of the family.
        "widgets-search" => &[
            "active_search",
            "autocomplete_input",
            "autocomplete_option",
            "autocomplete_create_option",
            "autocomplete_empty_state",
            "ActiveSearchConfig",
            "AutocompleteConfig",
        ],
        "widgets-workflow" => &[
            "bulk_actions_form",
            "bulk_actions_toolbar",
            "bulk_select_checkbox",
            "BulkActionsConfig",
            "transition_controls",
            "TransitionLabels",
        ],
        // A scaffolded CSV export (issue #1315) enables `csv` for the
        // `CsvSchema` impl and `export_csv` call its `export.csv` route emits,
        // but a hand-written route, job or task can use the same module —
        // `import_csv` has no generator at all, so an author wiring an upload
        // form is doing it by hand by definition. Destroying the last
        // scaffolded resource must not strip the feature out from under them.
        // The prelude re-exports nothing from `data::csv`, so every spelling
        // goes through this path. Deliberately NO trailing `::`: an author can
        // import the MODULE (`use autumn_web::data::csv;` or `… as data_csv;`)
        // and then call `csv::export_csv(…)`, and that import line ends at the
        // module name. A `autumn_web::data::csv::` marker misses it, and
        // destroying the last export-enabled scaffold would then strip a
        // feature the surviving code needs — a build break. Dropping the `::`
        // costs only over-retention (a doc comment naming the module now
        // counts as usage, leaving the feature enabled), which is the same
        // harmless direction `multipart` already accepts above; under-retention
        // is the one that does not compile.
        //
        // `Csv<T>` is the extractor and responder gated by the same feature. It
        // lives in `autumn_web::extract` and is not in the prelude.
        "csv" => &[
            "autumn_web::data::csv",
            "extract::Csv",
            "autumn_web::Csv",
            "Csv<",
        ],
        _ => &[],
    }
}

/// Whether `feature` is still referenced anywhere under `project_root`'s
/// `src/`, `tests/`, or `benches/` trees, other than in `excluding` — see
/// [`autumn_web_feature_markers`]. Always `false` (never blocks removal) for
/// a feature with no known marker.
/// Whether an `autumn-web` `feature` is pinned by the app's own database
/// backend rather than by any generated resource (issue #1924).
///
/// `sqlite` is a whole-app backend flip: `autumn new` never writes it, no
/// generated code contains a marker naming it, and without it the app's
/// `sqlite://` URL is refused at boot with `UnsupportedBackend`. Destroying the
/// last model must not take it out from under a `SQLite` app, so the backend
/// decides here rather than the generic `owner_dir` rule.
fn autumn_web_feature_pinned_by_backend(feature: &str, project_root: &Path) -> bool {
    feature == "sqlite" && super::detect_backend(project_root) == DatabaseBackend::Sqlite
}

fn autumn_web_feature_still_needed_elsewhere(
    feature: &str,
    project_root: &Path,
    excluding: &[PathBuf],
    overrides: &HashMap<PathBuf, String>,
) -> bool {
    let markers = autumn_web_feature_markers(feature);
    if markers.is_empty() {
        return false;
    }
    let markers: Vec<String> = markers.iter().map(|m| (*m).to_owned()).collect();
    markers_in_project(&markers, project_root, excluding, overrides)
}

/// Whether project config may turn on blob storage.
///
/// Reads every `autumn*.toml` and `.env*` file in the project root. That
/// covers profile overlays and local overrides without listing each name. Any
/// mention of storage keeps the feature. Variables set only in a deployment
/// are not visible here.
fn storage_is_configured(root: &Path) -> bool {
    let Ok(entries) = fs::read_dir(root) else {
        return false;
    };
    entries.filter_map(Result::ok).any(|entry| {
        let name = entry.file_name().to_string_lossy().into_owned();
        let is_toml = entry
            .path()
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("toml"));
        let is_config = (name.starts_with("autumn") && is_toml) || name.starts_with(".env");
        is_config
            && fs::read_to_string(entry.path())
                .is_ok_and(|text| text.to_ascii_lowercase().contains("storage"))
    })
}

/// Whether the manifest turns off default features for `autumn-web`.
///
/// Reads an inline entry (also over many lines), or the lines under a
/// `[dependencies.autumn-web]` style table. Another dependency's setting does
/// not count. An entry that inherits from the workspace (`workspace = true`)
/// counts as off, because the workspace manifest is not read here.
fn base_disables_defaults(manifest: &str) -> bool {
    let is_off = |line: &str| {
        let squeezed = line.replace(' ', "");
        squeezed.contains("default-features=false") || squeezed.contains("workspace=true")
    };
    let names_web = |text: &str| text.contains("autumn-web") || text.contains("autumn_web");
    let depth = |text: &str| {
        i32::try_from(text.matches('{').count()).unwrap_or(0)
            - i32::try_from(text.matches('}').count()).unwrap_or(0)
    };
    let mut in_web_table = false;
    // Brace depth left open by an `autumn-web = {` entry.
    let mut open_entry = 0;
    for line in manifest.lines() {
        let trimmed = line.trim();
        if open_entry > 0 {
            if is_off(trimmed) {
                return true;
            }
            open_entry += depth(trimmed);
        } else if trimmed.starts_with('[') {
            in_web_table = names_web(trimmed);
        } else if in_web_table || names_web(trimmed) {
            if is_off(trimmed) {
                return true;
            }
            if !in_web_table {
                open_entry = depth(trimmed).max(0);
            }
        }
    }
    false
}

/// Whether any of `markers` appears in `src/`, `tests/`, `benches/` or `examples/`.
fn markers_in_project(
    markers: &[String],
    project_root: &Path,
    excluding: &[PathBuf],
    overrides: &HashMap<PathBuf, String>,
) -> bool {
    // Targets whose `path` sits outside the four conventional trees count too.
    let named = crate::plugin::install::explicit_target_sources(project_root);
    let in_named = named.iter().any(|path| {
        let content = overrides.get(path).cloned().or_else(|| {
            (!excluding.contains(path))
                .then(|| fs::read_to_string(path).ok())
                .flatten()
        });
        content.is_some_and(|text| markers.iter().any(|m| text.contains(m.as_str())))
    });
    in_named
        || ["src", "tests", "benches", "examples"].iter().any(|dir| {
            rs_tree_contains_marker(&project_root.join(dir), markers, excluding, overrides)
        })
}

/// Markers that show `feature` is in use, for a regenerate run.
///
/// `None` means the feature has no marker. `htmx` has markers here only. The
/// stock `main.rs` names `autumn_web::htmx`, so a marker for it in
/// [`autumn_web_feature_markers`] would keep the feature on every `destroy`.
fn release_markers(feature: &str) -> Option<Vec<String>> {
    let markers: &[&str] = match feature {
        "htmx" => &["HTMX_JS_PATH", "HxRequest"],
        other => autumn_web_feature_markers(other),
    };
    (!markers.is_empty()).then(|| markers.iter().map(|m| (*m).to_owned()).collect())
}

/// Whether a local Cargo `feature` (not an `autumn-web` feature — see
/// [`autumn_web_feature_still_needed_elsewhere`] for that) is still gated on
/// anywhere under `project_root`'s `src/`, `tests/`, or `benches/` trees,
/// other than in `excluding`. Used by [`Revert::SystemTestCargoPatch`]:
/// destroying the last generated system test (or `generate pwa`'s smoke
/// test) must not strip a shared `[features] system-tests = [...]` entry
/// that pre-existed for unrelated hand-written `#[cfg(feature =
/// "system-tests")]` code (issue #1048 PR review).
pub(super) fn cargo_feature_still_gated_elsewhere(
    feature: &str,
    project_root: &Path,
    excluding: &[PathBuf],
) -> bool {
    let markers = [format!("feature = \"{feature}\"")];
    let no_overrides = HashMap::new();
    ["src", "tests", "benches"].iter().any(|dir| {
        rs_tree_contains_marker(&project_root.join(dir), &markers, excluding, &no_overrides)
    })
}

/// Recursively scan `dir` for any `.rs` file containing one of `markers` as
/// a plain substring.
///
/// `overrides` (path → already-computed post-destroy content) takes
/// priority over both disk and `excluding` — it's how a caller supplies the
/// real final content of a file this same `Plan::revert` is also modifying
/// in place (e.g. `src/schema.rs`), so scanning it doesn't see stale
/// pre-destroy content (issue #1048 PR review). A path in `excluding` but
/// absent from `overrides` is skipped entirely — it's either being deleted
/// outright, or emptied down to nothing by its own reverts, so it won't
/// exist to provide evidence either way once this destroy finishes.
fn rs_tree_contains_marker(
    dir: &Path,
    markers: &[String],
    excluding: &[PathBuf],
    overrides: &HashMap<PathBuf, String>,
) -> bool {
    rs_tree_marker_site(dir, markers, excluding, overrides).is_some()
}

/// The first `.rs` file under `dir` containing any of `markers`, or `None`.
///
/// The site-returning half of [`rs_tree_contains_marker`]: `autumn plugin
/// remove` (issue #1631) has to *name* the file that keeps a plugin
/// dependency alive, because "kept the dependency" without "because
/// `src/support.rs` still uses it" is an unactionable report.
fn rs_tree_marker_site(
    dir: &Path,
    markers: &[String],
    excluding: &[PathBuf],
    overrides: &HashMap<PathBuf, String>,
) -> Option<PathBuf> {
    let entries = fs::read_dir(dir).ok()?;
    // Sorted so the reported site is stable across runs and filesystems —
    // `read_dir` order is not specified, and a report that names a different
    // file on each run reads like a different finding.
    let mut paths: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).collect();
    paths.sort();
    for path in paths {
        if path.is_dir() {
            if let Some(found) = rs_tree_marker_site(&path, markers, excluding, overrides) {
                return Some(found);
            }
            continue;
        }
        if path.extension().is_none_or(|ext| ext != "rs") {
            continue;
        }
        let content = overrides.get(&path).cloned().or_else(|| {
            if excluding.contains(&path) {
                None
            } else {
                fs::read_to_string(&path).ok()
            }
        });
        if content.is_some_and(|c| markers.iter().any(|m| c.contains(m.as_str()))) {
            return Some(path);
        }
    }
    None
}

/// Outcome of matching one plan-time migration directory (built with a
/// fresh, destroy-time timestamp) against what's actually on disk.
enum MigrationOutcome {
    /// Safe to remove — content matched (or `--force`) and it is not applied.
    Remove(PathBuf),
    /// The real directory's content no longer matches what `generate` would
    /// have produced.
    Diverged(PathBuf),
    /// The migration appears to be applied to a configured database (or the
    /// database couldn't be reached, which is treated conservatively the
    /// same way) — never removed, not even with `--force`: deleting the
    /// files backing an applied migration would leave the database unable
    /// to reconstruct or roll back that step.
    Applied(PathBuf),
    /// More than one on-disk migration directory normalizes to the same
    /// suffix (e.g. a `model`-generated migration and an independently
    /// hand-run `generate migration` for the same resource) and content
    /// comparison couldn't tell them apart either — never guess which one
    /// to delete.
    Ambiguous(String),
    /// This is the `mail_unsubscribes` suppression migration (the one
    /// migration in the codebase reused across multiple resources of the
    /// same generator, via `create_if_absent` — see
    /// `mailer::plan_unsubscribe_migration`) and another mailer file besides
    /// the ones this destroy is itself removing still opts into
    /// `--list-unsubscribe` — never removed except with `--force`.
    StillNeededElsewhere(PathBuf),
    /// This migration creates the `comments` table, and another
    /// `#[commentable]` model still needs it (#2283) — never removed except
    /// with `--force`.
    StillNeededByCommentable(PathBuf),
    /// No on-disk directory matches this suffix — already destroyed, or
    /// never generated.
    NotFound,
}

/// Whether every `Create`/`CreateIfAbsent` action's expected content
/// exactly matches the corresponding file in `dir` — used only to
/// disambiguate between multiple same-suffix migration directories, so it
/// never honours `--force` (a loose match here would let `--force` guess
/// wrong on top of bypassing safety, rather than just bypassing safety).
/// Compares against the current render only, never a recorded digest: this
/// picks WHICH directory to delete, out of candidates found by scanning
/// `migrations/`, rather than gating a path the plan already named. The
/// manifest is project content, so honouring it here would let a crafted or
/// stale entry aim `remove_dir_all` at a hand-written migration. Candidates
/// that no longer match the current render stay `Ambiguous` — the pre-#1835
/// answer, and the safe one. Provenance still relaxes the per-file check once
/// one directory has been identified.
fn migration_dir_matches_actions(dir: &Path, actions: &[&Action]) -> bool {
    actions.iter().all(|action| {
        let Some(file_name) = action.path().file_name() else {
            return true;
        };
        let expected: &str = match action {
            Action::Create { contents, .. } | Action::CreateIfAbsent { contents, .. } => contents,
            Action::CreateBytes { .. } | Action::Modify { .. } => return true,
        };
        fs::read_to_string(dir.join(file_name)).is_ok_and(|actual| text_matches(&actual, expected))
    })
}

/// Whether the file at `path` is generator output rather than a developer's.
///
/// True when it matches what this plan would write now, and also when it
/// matches the digest `generate` recorded for it — the same file, written by a
/// CLI whose template has since moved on (issue #1835). A developer's edit
/// matches neither, and stays protected.
///
/// The recorded digest is keyed by PATH, not by which plan wrote it, so a file
/// one generator owns also reads as generator output to another plan naming
/// the same path. That is deliberate: the caller has already decided the path
/// belongs to the resource being destroyed, and the question left here is only
/// whether a human has since changed the file.
///
/// A `Modify` target is shared, never owned by one plan; every caller filters
/// those out first, and the arm below is the belt-and-braces answer.
fn is_generator_output(
    action: &Action,
    path: &Path,
    project_root: &Path,
    baseline: Baseline<'_>,
) -> bool {
    let (on_disk_digest, planned) = match action {
        Action::Create { contents, .. } | Action::CreateIfAbsent { contents, .. } => {
            let Ok(on_disk) = fs::read_to_string(path) else {
                return false;
            };
            if text_matches(&on_disk, contents) {
                return true;
            }
            (provenance::text_digest(&on_disk), Claim::of(action))
        }
        Action::CreateBytes { bytes, .. } => {
            let Ok(on_disk) = fs::read(path) else {
                return false;
            };
            if &on_disk == bytes {
                return true;
            }
            (provenance::bytes_digest(&on_disk), Claim::of(action))
        }
        Action::Modify { .. } => return false,
    };
    baseline.accepts(planned, project_root, path, &on_disk_digest)
}

/// What a revert compares an on-disk file against: the digests `generate`
/// recorded, and the command allowed to claim them.
#[derive(Clone, Copy)]
struct Baseline<'a> {
    recorded: &'a provenance::Provenance,
    invocation: &'a str,
}

impl Baseline<'_> {
    /// Whether `claim` holds for `digest` at `path`.
    fn accepts(self, claim: Claim, project_root: &Path, path: &Path, digest: &str) -> bool {
        match claim {
            Claim::ByThisCommand => {
                self.recorded
                    .is_ours(project_root, path, digest, self.invocation)
            }
            Claim::ByAnyCommand => self.recorded.was_written(project_root, path, digest),
        }
    }
}

/// Who has to have written a file for its recorded digest to count.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Claim {
    /// The command doing the destroying — the rule for a file it owns
    /// outright, so one command cannot delete another's output.
    ByThisCommand,
    /// Any command — the rule for a file several resources share, where only
    /// the first writer was ever recorded, so requiring the destroying command
    /// to BE that writer would strand the file the moment a template change
    /// stopped the content compare from matching. Every path that reaches this
    /// establishes first that no sibling still needs the file: the
    /// `CreateIfAbsent` pass checks the directory, and the shared
    /// `mail_unsubscribes` migration has its own still-needed-elsewhere guard
    /// after the content check.
    ByAnyCommand,
}

impl Claim {
    /// A shared file is written once for all its consumers; anything else
    /// belongs to the one command that wrote it.
    const fn of(action: &Action) -> Self {
        match action {
            Action::CreateIfAbsent { .. } => Self::ByAnyCommand,
            Action::Create { .. } | Action::CreateBytes { .. } | Action::Modify { .. } => {
                Self::ByThisCommand
            }
        }
    }
}

/// Whether two texts are the same file, ignoring line endings.
///
/// `git config core.autocrlf true` rewrites every text file on checkout, and
/// that is a checkout artifact rather than an edit — the same reason the
/// recorded digest is taken over LF-normalised text. Comparing raw here would
/// make the tolerance depend on a manifest entry surviving.
fn text_matches(on_disk: &str, expected: &str) -> bool {
    on_disk == expected || provenance::text_digest(on_disk) == provenance::text_digest(expected)
}

/// Split a migration directory name into its leading numeric timestamp
/// ("version") and the remaining suffix, e.g.
/// `"20260706120000_create_posts"` → `("20260706120000", "create_posts")`.
pub(super) fn split_migration_dir_name(name: &str) -> (&str, &str) {
    let digit_len = name
        .bytes()
        .position(|b| !b.is_ascii_digit())
        .unwrap_or(name.len());
    let (version, rest) = name.split_at(digit_len);
    (version, rest.strip_prefix('_').unwrap_or(rest))
}

/// Resolve one migration-directory group from the (destroy-time,
/// fresh-timestamp) plan against the real on-disk `migrations/` directory,
/// matched by suffix, and decide whether it's safe to remove.
fn resolve_migration_removal(
    plan_dir: &Path,
    actions: &[&Action],
    migrations_root: &Path,
    force: bool,
    project_root: &Path,
    excluding: &[PathBuf],
    baseline: Baseline<'_>,
) -> MigrationOutcome {
    let Some(plan_dir_name) = plan_dir.file_name().and_then(|n| n.to_str()) else {
        return MigrationOutcome::NotFound;
    };
    let (_, suffix) = split_migration_dir_name(plan_dir_name);

    let Ok(entries) = fs::read_dir(migrations_root) else {
        return MigrationOutcome::NotFound;
    };
    let mut candidates: Vec<PathBuf> = entries
        .filter_map(Result::ok)
        .map(|e| e.path())
        .filter(|p| {
            p.is_dir()
                && p.file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|name| split_migration_dir_name(name).1 == suffix)
        })
        .collect();
    candidates.sort();

    let real_dir = match candidates.len() {
        0 => return MigrationOutcome::NotFound,
        1 => candidates.into_iter().next().expect("len checked above"),
        _ => {
            // Multiple on-disk directories share this suffix — disambiguate
            // by exact content match rather than guessing (filesystem read
            // order is unspecified, so picking the first would be
            // non-deterministic).
            let mut matching: Vec<PathBuf> = candidates
                .into_iter()
                .filter(|dir| migration_dir_matches_actions(dir, actions))
                .collect();
            if matching.len() != 1 {
                return MigrationOutcome::Ambiguous(suffix.to_owned());
            }
            matching.remove(0)
        }
    };

    for action in actions {
        let Some(file_name) = action.path().file_name() else {
            continue;
        };
        // A byte asset inside a migration directory was never content-checked
        // here, and still is not — the unplanned-file sweep below is what
        // guards this directory. No generator emits one today.
        if matches!(action, Action::CreateBytes { .. } | Action::Modify { .. }) {
            continue;
        }
        // The on-disk directory carries the timestamp `generate` used, not the
        // fresh one this recomputed plan holds, so compare against the real
        // file — under its own recorded digest too (issue #1835).
        let real_file = real_dir.join(file_name);
        if !is_generator_output(action, &real_file, project_root, baseline) && !force {
            return MigrationOutcome::Diverged(real_file);
        }
    }

    // Refuse to sweep up files this generator never planned — a hand-added
    // `README.md` or an auxiliary fixture living alongside `up.sql`/
    // `down.sql` — unless `--force` is passed (issue #1048 PR review).
    // Without this, `remove_dir_all` below would silently delete
    // hand-authored content just because it happens to share a directory
    // with the generated migration files.
    if !force && let Ok(entries) = fs::read_dir(&real_dir) {
        for entry in entries.filter_map(Result::ok) {
            let name = entry.file_name();
            let planned = actions
                .iter()
                .any(|action| action.path().file_name() == Some(name.as_os_str()));
            if !planned {
                return MigrationOutcome::Diverged(entry.path());
            }
        }
    }

    if !force
        && mail_unsubscribes_migration_still_needed_elsewhere(&real_dir, project_root, excluding)
    {
        return MigrationOutcome::StillNeededElsewhere(real_dir);
    }

    // Deliberately NOT gated on `force`: `--force` bypasses content
    // divergence and the sibling-resource "still needed elsewhere" caution,
    // but never the applied-migration check (issue #1048 PR review) —
    // removing files backing a migration the database already recorded as
    // applied would leave that database unable to reconstruct or roll back
    // the step, which is a data-safety concern `--force`'s documented
    // purpose (bypassing content mismatches) was never meant to cover.
    let real_dir_name = real_dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
    let (version, _) = split_migration_dir_name(real_dir_name);
    match migration_applied_status(version, migrations_root) {
        MigrationStatus::Applied | MigrationStatus::Unknown => MigrationOutcome::Applied(real_dir),
        // After the status check: `--force` can remove only an unapplied
        // migration, so only then is it the way out (#2283).
        MigrationStatus::NotApplied | MigrationStatus::NotConfigured
            if !force
                && super::commentable::comments_migration_still_needed(
                    project_root,
                    &real_dir,
                    excluding,
                ) =>
        {
            MigrationOutcome::StillNeededByCommentable(real_dir)
        }
        MigrationStatus::NotApplied | MigrationStatus::NotConfigured => {
            MigrationOutcome::Remove(real_dir)
        }
    }
}

/// Whether `real_dir` is the `mail_unsubscribes` suppression migration and
/// another mailer file (besides ones this same destroy is itself removing)
/// still opts into `--list-unsubscribe` — the one migration in the codebase
/// reused across multiple resources of the same generator via
/// `create_if_absent` (see `mailer::plan_unsubscribe_migration`), so it
/// needs its own sibling check rather than the generic `owner_dir`
/// mechanism `Revert::CargoDeps` and friends use.
fn mail_unsubscribes_migration_still_needed_elsewhere(
    real_dir: &Path,
    project_root: &Path,
    excluding: &[PathBuf],
) -> bool {
    let is_unsubscribes_migration = real_dir
        .file_name()
        .and_then(|n| n.to_str())
        .is_some_and(|name| split_migration_dir_name(name).1 == "create_mail_unsubscribes");
    if !is_unsubscribes_migration {
        return false;
    }
    let Ok(entries) = fs::read_dir(project_root.join("src").join("mailers")) else {
        return false;
    };
    entries.filter_map(Result::ok).any(|entry| {
        let path = entry.path();
        path.extension().is_some_and(|ext| ext == "rs")
            && !excluding.contains(&path)
            && fs::read_to_string(&path)
                .is_ok_and(|content| content.contains("list_unsubscribe = "))
    })
}

/// Best-effort classification of whether a migration has already been
/// applied to a database.
enum MigrationStatus {
    /// No database URL is configured — this project has never run
    /// migrations against a real database, so the just-generated migration
    /// cannot be applied either.
    NotConfigured,
    /// A live database check confirmed it has not been applied.
    NotApplied,
    /// A live database check confirmed it has been applied.
    Applied,
    /// A database URL is configured but couldn't be reached/queried —
    /// treated the same as `Applied` (conservative: never delete migration
    /// files destroy can't confirm are safe to remove).
    Unknown,
}

fn migration_applied_status(version: &str, migrations_dir: &Path) -> MigrationStatus {
    // Resolve the same profile/overlay `autumn migrate` would (see
    // `migrate::resolve_targets`), not just the bare base `autumn.toml` — a
    // project that only configures its database via `[profile.prod.database]`
    // or an `autumn-prod.toml` overlay must not look "NotConfigured" here,
    // which would defeat the applied-migration safety guard below.
    let profile = crate::migrate::effective_profile(None);
    let table = crate::migrate::read_autumn_toml_table_with_profile(Some(&profile));
    let control_url = crate::migrate::resolve_primary_database_url_from_sources(
        |k| std::env::var(k),
        table.as_ref(),
    );
    // `autumn migrate run --shard <name>` applies user migrations to shard
    // databases too, independently of the control database (issue #1048 PR
    // review) — a sharded project checking only the control URL could
    // delete a migration's files while a shard still records it as applied,
    // leaving that shard unable to reconstruct or roll back the step.
    let shard_urls = crate::migrate::resolve_shard_database_urls_from_sources(
        |k| std::env::var(k),
        table.as_ref(),
    );
    let urls: Vec<String> = control_url
        .into_iter()
        .chain(shard_urls.into_iter().map(|(_, url)| url))
        .collect();
    if urls.is_empty() {
        return MigrationStatus::NotConfigured;
    }
    // Applied on ANY target (control or a shard) blocks removal outright;
    // otherwise an unreachable target is treated the same as "applied"
    // (conservative: never delete migration files destroy can't confirm are
    // safe to remove on every configured database).
    let mut any_unreachable = false;
    for url in urls {
        match autumn_web::migrate::applied_user_migrations(&url, migrations_dir) {
            Ok(applied) if applied.iter().any(|m| m.version == version) => {
                return MigrationStatus::Applied;
            }
            Ok(_) => {}
            Err(_) => any_unreachable = true,
        }
    }
    if any_unreachable {
        MigrationStatus::Unknown
    } else {
        MigrationStatus::NotApplied
    }
}

/// Shared, infrastructure-only module names any generator's `update_main_rs`
/// call might declare in `src/main.rs` — never resource-specific. Destroy
/// only ever removes one of these once its backing file/directory no longer
/// exists, so a project with a second resource still using it is untouched
/// (issue #1048's "never remove shared declarations" guarantee, made
/// precise: shared while still needed, removed once genuinely orphaned).
const SHARED_MAIN_MODULE_NAMES: &[&str] = &[
    "models",
    "schema",
    "repositories",
    "routes",
    "channels",
    "jobs",
    "mailers",
    "inbound_mailers",
    // `autumn generate webhook` (issue #1366) — directory-backed like the
    // entries above, so `shared_module_backing_path_exists` treats it as
    // orphaned once `src/webhooks/` is gone.
    "webhooks",
    "policies",
    // A fixed single-file module (`src/notifications.rs`, no directory) —
    // `shared_module_backing_path_exists` already handles that shape.
    "notifications",
    // `autumn generate teams` (issue #1261) — like the other directory-backed
    // entries above, `shared_module_backing_path_exists` treats this as
    // orphaned once `src/teams/` is gone.
    "teams",
];

/// Whether `name`'s backing module still exists on disk — either as
/// `src/<name>.rs` (the shape `schema` and a single-file resource module
/// use) or `src/<name>/mod.rs` (a directory of per-resource files).
fn shared_module_backing_path_exists(project_root: &Path, name: &str) -> bool {
    let src = project_root.join("src");
    src.join(format!("{name}.rs")).is_file() || src.join(name).join("mod.rs").is_file()
}

/// After a real (non-dry-run) `Plan::revert`, strip any [`SHARED_MAIN_MODULE_NAMES`]
/// declaration from `src/main.rs` whose backing module no longer exists —
/// the corresponding directory/file was just emptied and deleted by this
/// same `revert` call. A no-op if `src/main.rs` is missing or nothing
/// qualifies.
fn sync_main_rs_mod_declarations(project_root: &Path) {
    let main_path = project_root.join("src").join("main.rs");
    let Ok(content) = fs::read_to_string(&main_path) else {
        return;
    };
    let orphaned: Vec<&str> = SHARED_MAIN_MODULE_NAMES
        .iter()
        .copied()
        .filter(|name| {
            content.lines().any(|l| l.trim() == format!("mod {name};"))
                && !shared_module_backing_path_exists(project_root, name)
        })
        .collect();
    if orphaned.is_empty() {
        return;
    }
    let updated = super::schema_edit::remove_main_mod_declarations(&content, &orphaned);
    if updated != content && fs::write(&main_path, &updated).is_ok() {
        println!("  Reverted {}", relative_display(&main_path, project_root));
    }
}

/// Strip a `pub mod <name>;` declaration from `<dir>/mod.rs` for any `name`
/// in `shared_names` whose backing file/directory no longer exists — the
/// same "shared while still needed, removed once orphaned" rule
/// [`sync_main_rs_mod_declarations`] applies to `src/main.rs`, but for a
/// nested shared sub-module declared in some *other* generated `mod.rs`
/// (e.g. `src/mailers/mod.rs`'s `pub mod previews;`, shared by every
/// generated mailer, not owned by one). A no-op if `<dir>/mod.rs` is missing
/// or nothing qualifies. If removing every orphaned declaration empties the
/// file, it is deleted instead of left blank.
fn sync_mod_declarations_in(dir: &Path, shared_names: &[&str], project_root: &Path) {
    let mod_path = dir.join("mod.rs");
    let Ok(content) = fs::read_to_string(&mod_path) else {
        return;
    };
    let orphaned: Vec<&str> = shared_names
        .iter()
        .copied()
        .filter(|name| {
            content
                .lines()
                .any(|l| l.trim() == format!("pub mod {name};"))
                && !dir.join(format!("{name}.rs")).is_file()
                && !dir.join(name).join("mod.rs").is_file()
        })
        .collect();
    if orphaned.is_empty() {
        return;
    }
    let mut updated = content.clone();
    for name in orphaned {
        updated = super::schema_edit::remove_mod_declaration(&updated, name);
    }
    if updated == content {
        return;
    }
    if updated.trim().is_empty() {
        if fs::remove_file(&mod_path).is_ok() {
            println!("  Removed {}", relative_display(&mod_path, project_root));
            prune_empty_ancestors(dir.to_path_buf(), project_root);
        }
    } else if fs::write(&mod_path, &updated).is_ok() {
        println!("  Reverted {}", relative_display(&mod_path, project_root));
    }
}

pub fn relative_display(path: &Path, root: &Path) -> String {
    let display = path
        .strip_prefix(root)
        .map_or_else(|_| path.display().to_string(), |p| p.display().to_string());
    // Always render with forward slashes so the generator's output (and any
    // tests that grep for it) is platform-consistent.
    display.replace('\\', "/")
}

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

    /// The `common.*` keys a scan of `root` still finds referenced.
    fn surviving_common_keys(root: &Path) -> HashSet<String> {
        scan_surviving_sources(root, &[], &HashMap::new())
            .referenced
            .into_iter()
            .filter(|key| key.starts_with("common."))
            .collect()
    }

    /// `common.*` keys the project scanner finds in one source string.
    fn common_keys_in(src: &str) -> Vec<String> {
        let mut scan = crate::i18n::ScanResult::default();
        crate::i18n::scan_source(src, "test.rs", &mut scan);
        scan.referenced
            .into_iter()
            .filter(|k| k.starts_with("common."))
            .collect()
    }

    fn fixture() -> (tempfile::TempDir, Plan) {
        let tmp = tempfile::TempDir::new().unwrap();
        let plan = Plan::new(tmp.path());
        (tmp, plan)
    }

    #[test]
    fn new_plan_has_no_warnings() {
        let (_tmp, plan) = fixture();
        assert!(plan.warnings.is_empty());
    }

    /// A key built at runtime reaches definitions no static scan can name.
    /// Pruning them leaves a missing-key marker in a surviving view — and
    /// `autumn i18n check` deliberately does NOT report such keys as unused, so
    /// destroy must not delete what the checker declines to complain about.
    #[test]
    fn chrome_reachable_only_through_a_dynamic_key_survives() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(
            root.join("src").join("nav.rs"),
            "fn nav(locale: &Locale, action: &str) -> String {\n                 locale.t(&format!(\"common.{action}\"))\n}\n",
        )
        .unwrap();

        let ftl = concat!(
            "# Shared chrome — reused by every scaffolded resource.\n",
            "common.save = Save\n",
            "common.back = Back\n",
            "# — end shared chrome —\n",
            "\n",
            "# Post — generated by `autumn generate scaffold --i18n`.\n",
            "post.new = New Post\n",
            "# — end Post —\n",
        );
        let out = remove_i18n_keys(ftl, "Post", "post", root, &[], &HashMap::new());
        assert!(
            out.contains("common.save") && out.contains("common.back"),
            "a `common.{{action}}` lookup can reach both:\n{out}"
        );
        // The resource's own block still goes.
        assert!(!out.contains("post.new"), "{out}");
    }

    /// `t!` compiles in `tests/` and `examples/` too, and `autumn i18n check`
    /// reads the whole project. A scan rooted at `src/` calls such a key unused
    /// and prunes it, breaking that target's build.
    #[test]
    fn chrome_survives_when_only_a_non_src_target_uses_it() {
        let tmp = tempfile::TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("src/routes")).unwrap();
        std::fs::create_dir_all(root.join("tests")).unwrap();
        std::fs::create_dir_all(root.join("examples")).unwrap();
        std::fs::write(
            root.join("tests").join("views.rs"),
            "fn t() { let _ = t!(locale, \"common.save\"); }\n",
        )
        .unwrap();
        std::fs::write(
            root.join("examples").join("demo.rs"),
            "fn main() { let _ = locale.t(\"common.back\"); }\n",
        )
        .unwrap();
        std::fs::write(
            root.join("src/routes").join("posts.rs"),
            "fn show() { let _ = t!(locale, \"post.new\"); }\n",
        )
        .unwrap();

        let found = surviving_common_keys(root);
        assert!(found.contains("common.save"), "tests/ counts: {found:?}");
        assert!(found.contains("common.back"), "examples/ counts: {found:?}");
    }

    /// The forms a surviving `common.*` lookup can take.
    ///
    /// Every row here was once a bug: the scan this replaced was a hand-rolled
    /// text search, extended a round at a time as reviews found the next token
    /// class it could not read. Parsing now goes through the same `syn` scanner
    /// as `autumn i18n check`, so these are no longer separate features to
    /// implement — but they stay as the regression contract, because pruning a
    /// key one of them still references breaks the user's build at COMPILE
    /// time, and that is the failure this whole set exists to prevent.
    #[test]
    fn chrome_scan_reads_every_supported_lookup_form() {
        let cases: &[(&str, &str)] = &[
            ("plain", r#"let a = t!(locale, "common.plain");"#),
            (
                "rustfmt-wrapped",
                "let b = t!(\n    locale,\n    \"common.wrapped\",\n    n = &c.to_string()\n);",
            ),
            (
                "comment before key",
                r#"let c = t!(locale, /* shared */ "common.commented");"#,
            ),
            ("raw string key", r#"let d = t!(locale, r"common.raw");"#),
            (
                "hashed raw key",
                r##"let e = t!(locale, r#"common.hashed"#);"##,
            ),
            (
                "other locale binding",
                r#"let f = t!(lang, "common.lang");"#,
            ),
            ("field locale", r#"let g = t!(ctx.locale, "common.field");"#),
            ("spaced call", r#"let h = t! (locale, "common.spaced");"#),
            // Not a macro at all — the `Locale` methods are equally supported,
            // and were invisible to the text scanner.
            ("method call", r#"let i = locale.t("common.method");"#),
            (
                "method with args",
                r#"let j = locale.t_with("common.method_args", &[]);"#,
            ),
            (
                "associated call",
                r#"let k = Locale::t(&locale, "common.assoc");"#,
            ),
            // Inside `html!`, where view translations actually live.
            (
                "inside a macro body",
                r#"let l = html! { span { (t!(locale, "common.nested")) } };"#,
            ),
        ];
        for (what, src) in cases {
            let found = common_keys_in(src);
            assert!(!found.is_empty(), "no key found for the {what} form: {src}");
        }
    }

    /// Not every `t` is a translation, and a key that is not code is not a
    /// reference. Over-counting only strands an unused key; both directions are
    /// still worth pinning.
    #[test]
    fn chrome_scan_ignores_non_lookups() {
        for src in [
            r#"let a = "common.just-a-string";"#,
            r#"// t!(locale, "common.commented-out")"#,
            r#"/* t!(locale, "common.blocked") */"#,
            // A bare `t(...)` is not the `Locale` API.
            r#"let b = t("common.bare-fn");"#,
        ] {
            assert!(
                common_keys_in(src).is_empty(),
                "unexpectedly counted a reference in: {src}"
            );
        }
    }

    /// Chrome keys are ordinary keys once written, and application code outside
    /// `src/routes` may well reuse them. Pruning one that a surviving
    /// `src/components/…` still calls breaks the build, because `t!` validates
    /// key existence at compile time.
    #[test]
    fn chrome_survives_when_only_non_route_source_still_uses_it() {
        let tmp = tempfile::TempDir::new().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(src.join("routes")).unwrap();
        std::fs::create_dir_all(src.join("components")).unwrap();
        // The only surviving caller of `common.save` lives outside `routes/`.
        std::fs::write(
            src.join("components").join("navigation.rs"),
            "fn nav(locale: &Locale) -> Markup { html! { (t!(locale, \"common.save\")) } }\n",
        )
        .unwrap();
        std::fs::write(
            src.join("routes").join("posts.rs"),
            "fn show(locale: &Locale) -> Markup { html! { (t!(locale, \"post.new\")) } }\n",
        )
        .unwrap();

        let found = surviving_common_keys(&src);
        assert!(
            found.contains("common.save"),
            "a non-route caller keeps the key alive: {found:?}"
        );
    }

    /// The same protection the chrome set gives `common.*`, for the resource's
    /// own keys. A nav link or dashboard card outside the generated module can
    /// render `t!(locale, "post.index.title")`; destroying the marked `post.*`
    /// block out from under it breaks the build, because `t!` validates key
    /// existence at COMPILE time.
    #[test]
    fn a_resource_key_a_surviving_source_still_uses_is_not_destroyed() {
        let tmp = tempfile::TempDir::new().unwrap();
        let src = tmp.path().join("src");
        std::fs::create_dir_all(src.join("components")).unwrap();
        std::fs::write(
            src.join("components").join("nav.rs"),
            "fn nav(locale: &Locale) -> Markup { html! { (t!(locale, \"post.index.title\")) } }\n",
        )
        .unwrap();

        let ftl = super::super::scaffold_i18n::merge_en_ftl_keeping(
            "",
            "Post",
            "post",
            &[
                ("post.index.title", "Posts"),
                ("post.new.title", "New Post"),
            ]
            .into_iter()
            .map(|(k, v)| (k.to_owned(), v.to_owned()))
            .collect(),
            &HashSet::new(),
        );

        let out = remove_i18n_keys(&ftl, "Post", "post", &src, &[], &HashMap::new());
        assert!(
            out.contains("post.index.title = Posts"),
            "the surviving call site keeps its key:\n{out}"
        );
        assert!(
            !out.contains("post.new.title"),
            "keys nothing references still go:\n{out}"
        );
    }

    #[test]
    fn warn_records_message_and_execute_does_not_fail() {
        let (_tmp, mut plan) = fixture();
        plan.warn("referenced table 'posts' is assumed to exist");
        assert_eq!(plan.warnings.len(), 1);
        // A warning never fails the plan — it's advisory only.
        plan.execute(Flags::default()).unwrap();
    }

    #[test]
    fn warnings_do_not_block_a_collision_error() {
        // A colliding Create must still fail with Collisions even when the
        // plan also carries a warning (the warning is printed to stderr,
        // which this test can't capture in-process, but it must never be
        // allowed to suppress or alter the underlying error).
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        fs::write(&target, "existing").unwrap();
        plan.warn("some advisory message");
        plan.create(target, "new");
        let err = plan.execute(Flags::default()).unwrap_err();
        assert!(matches!(err, GenerateError::Collisions(_)));
    }

    #[test]
    fn create_action_writes_file() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        plan.create(target.clone(), "hello");
        plan.execute(Flags::default()).unwrap();
        assert_eq!(fs::read_to_string(&target).unwrap(), "hello");
    }

    #[test]
    fn create_action_creates_parent_dirs() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("nested/dir/out.txt");
        plan.create(target.clone(), "hi");
        plan.execute(Flags::default()).unwrap();
        assert!(target.exists());
    }

    #[test]
    fn collision_without_force_errors() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        fs::write(&target, "old").unwrap();
        plan.create(target.clone(), "new");
        let err = plan.execute(Flags::default()).unwrap_err();
        match err {
            GenerateError::Collisions(paths) => {
                assert_eq!(paths, vec![target.clone()]);
            }
            _ => panic!("expected collision error, got {err:?}"),
        }
        assert_eq!(fs::read_to_string(&target).unwrap(), "old");
    }

    #[test]
    fn collision_with_force_overwrites() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        fs::write(&target, "old").unwrap();
        plan.create(target.clone(), "new");
        plan.execute(Flags {
            force: true,
            dry_run: false,
        })
        .unwrap();
        assert_eq!(fs::read_to_string(&target).unwrap(), "new");
    }

    #[test]
    fn modify_action_overwrites_without_force() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        fs::write(&target, "old").unwrap();
        plan.modify(target.clone(), "new");
        plan.execute(Flags::default()).unwrap();
        assert_eq!(fs::read_to_string(&target).unwrap(), "new");
    }

    #[test]
    fn dry_run_writes_nothing() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        plan.create(target.clone(), "hello");
        plan.execute(Flags {
            dry_run: true,
            force: false,
        })
        .unwrap();
        assert!(!target.exists());
    }

    #[test]
    fn dry_run_skips_collision_check() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        fs::write(&target, "existing").unwrap();
        plan.create(target.clone(), "new");
        plan.execute(Flags {
            dry_run: true,
            force: false,
        })
        .unwrap();
        assert_eq!(fs::read_to_string(&target).unwrap(), "existing");
    }

    #[test]
    fn collision_lists_every_offender() {
        let (tmp, mut plan) = fixture();
        let a = tmp.path().join("a.txt");
        let b = tmp.path().join("b.txt");
        fs::write(&a, "x").unwrap();
        fs::write(&b, "y").unwrap();
        plan.create(a.clone(), "1");
        plan.create(b.clone(), "2");
        let err = plan.execute(Flags::default()).unwrap_err();
        let msg = err.to_string();
        // The error message normalises path separators to `/` so the
        // assertion needs to match that form (Windows uses `\` natively).
        assert!(msg.contains(a.display().to_string().replace('\\', "/").as_str()));
        assert!(msg.contains(b.display().to_string().replace('\\', "/").as_str()));
    }

    // ── `Plan::revert` — the inverse of `Plan::execute` (issue #1048) ──────

    fn no_db_env<R>(f: impl FnOnce() -> R) -> R {
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
            ],
            f,
        )
    }

    #[test]
    fn revert_removes_create_action_file() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        plan.create(target.clone(), "hello");
        plan.execute(Flags::default()).unwrap();
        assert!(target.exists());
        plan.revert(Flags::default()).unwrap();
        assert!(!target.exists());
    }

    #[test]
    fn revert_is_idempotent_when_file_already_missing() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        plan.create(target.clone(), "hello");
        // Never executed — file was never created.
        plan.revert(Flags::default()).unwrap();
        assert!(!target.exists());
    }

    #[test]
    fn revert_refuses_on_diverged_content_without_force() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        plan.create(target.clone(), "hello");
        plan.execute(Flags::default()).unwrap();
        fs::write(&target, "hand-edited by user").unwrap();
        let err = plan.revert(Flags::default()).unwrap_err();
        assert!(matches!(err, GenerateError::Diverged(_)));
        assert!(target.exists(), "diverged file must not be deleted");
    }

    #[test]
    fn revert_with_force_deletes_diverged_file() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        plan.create(target.clone(), "hello");
        plan.execute(Flags::default()).unwrap();
        fs::write(&target, "hand-edited by user").unwrap();
        plan.revert(Flags {
            force: true,
            dry_run: false,
        })
        .unwrap();
        assert!(!target.exists());
    }

    #[test]
    fn revert_dry_run_does_not_touch_disk() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("out.txt");
        plan.create(target.clone(), "hello");
        plan.execute(Flags::default()).unwrap();
        plan.revert(Flags {
            dry_run: true,
            force: false,
        })
        .unwrap();
        assert!(target.exists());
    }

    // ---- issue #1835: provenance-tolerant revert -------------------------
    //
    // `destroy` run by a NEWER CLI recomputes the plan from the CURRENT
    // template, so any generator whose template changed since the project was
    // generated reported `Diverged` on untouched files. These tests pin the
    // provenance manifest that tells the two cases apart.

    /// The plan a newer CLI would recompute: same path, newer template text.
    fn newer_template_plan(tmp: &tempfile::TempDir, path: &Path, contents: &str) -> Plan {
        let mut plan = Plan::new(tmp.path());
        plan.create(path.to_path_buf(), contents);
        plan
    }

    #[test]
    fn revert_removes_untouched_file_whose_template_changed_since_generation() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("src/routes/auth.rs");
        plan.create(target.clone(), "// v1 template\n");
        plan.execute(Flags::default()).unwrap();

        // Newer CLI: the renderer now emits different text for the same file.
        let newer = newer_template_plan(&tmp, &target, "// v2 template\n");
        newer.revert(Flags::default()).unwrap();

        assert!(!target.exists(), "untouched generated file must be removed");
    }

    #[test]
    fn revert_still_refuses_a_hand_edited_file_whose_template_changed() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("src/routes/auth.rs");
        plan.create(target.clone(), "// v1 template\n");
        plan.execute(Flags::default()).unwrap();
        fs::write(&target, "// hand-edited by user\n").unwrap();

        let newer = newer_template_plan(&tmp, &target, "// v2 template\n");
        let err = newer.revert(Flags::default()).unwrap_err();

        assert!(matches!(err, GenerateError::Diverged(_)));
        assert!(target.exists(), "a real edit must survive");
    }

    #[test]
    fn execute_records_a_provenance_digest_for_every_owned_file() {
        let (tmp, mut plan) = fixture();
        plan.create(tmp.path().join("src/models/post.rs"), "// model\n");
        plan.create_bytes(tmp.path().join("static/logo.png"), vec![1, 2, 3]);
        plan.create_if_absent(tmp.path().join("templates/_layout.html"), "<html>\n");
        plan.modify(tmp.path().join("src/main.rs"), "fn main() {}\n");
        plan.execute(Flags::default()).unwrap();

        let recorded = provenance::Provenance::load(tmp.path());
        assert!(recorded.contains("src/models/post.rs"));
        assert!(recorded.contains("static/logo.png"));
        assert!(recorded.contains("templates/_layout.html"));
        assert!(
            !recorded.contains("src/main.rs"),
            "a Modify target is shared, never owned by one plan"
        );
    }

    #[test]
    fn dry_run_execute_records_no_provenance() {
        let (tmp, mut plan) = fixture();
        plan.create(tmp.path().join("out.txt"), "hello");
        plan.execute(Flags {
            dry_run: true,
            force: false,
        })
        .unwrap();
        assert!(!tmp.path().join(provenance::MANIFEST_PATH).exists());
    }

    #[test]
    fn dry_run_revert_records_no_provenance_change() {
        let (tmp, mut plan) = fixture();
        plan.create(tmp.path().join("out.txt"), "hello");
        plan.execute(Flags::default()).unwrap();

        plan.revert(Flags {
            dry_run: true,
            force: false,
        })
        .unwrap();

        assert!(
            provenance::Provenance::load(tmp.path()).contains("out.txt"),
            "a dry run must leave the manifest alone"
        );
    }

    #[test]
    fn revert_prunes_the_provenance_entries_it_removed() {
        let (tmp, mut plan) = fixture();
        plan.create(tmp.path().join("out.txt"), "hello");
        plan.execute(Flags::default()).unwrap();
        plan.revert(Flags::default()).unwrap();

        assert!(!provenance::Provenance::load(tmp.path()).contains("out.txt"));
        assert!(
            !tmp.path().join(provenance::MANIFEST_PATH).exists(),
            "an emptied manifest is removed, not left as a stub"
        );
    }

    #[test]
    fn a_skipped_create_if_absent_is_not_recorded_as_ours() {
        let (tmp, mut plan) = fixture();
        let shared = tmp.path().join("templates/_layout.html");
        fs::create_dir_all(shared.parent().unwrap()).unwrap();
        fs::write(&shared, "<html>hand-written</html>\n").unwrap();

        plan.create_if_absent(shared, "<html>generated</html>\n");
        plan.execute(Flags::default()).unwrap();

        assert!(
            !provenance::Provenance::load(tmp.path()).contains("templates/_layout.html"),
            "generate skipped the write, so it owns nothing"
        );
    }

    #[test]
    fn create_if_absent_matching_provenance_is_removed_after_a_template_change() {
        let (tmp, mut plan) = fixture();
        let shared = tmp.path().join("templates/_layout.html");
        plan.create_if_absent(shared.clone(), "<html>v1</html>\n");
        plan.execute(Flags::default()).unwrap();

        let mut newer = Plan::new(tmp.path());
        newer.create_if_absent(shared.clone(), "<html>v2</html>\n");
        newer.revert(Flags::default()).unwrap();

        assert!(!shared.exists());
    }

    #[test]
    fn create_bytes_matching_provenance_is_removed_after_a_template_change() {
        let (tmp, mut plan) = fixture();
        let asset = tmp.path().join("static/vendor.js");
        plan.create_bytes(asset.clone(), b"v1".to_vec());
        plan.execute(Flags::default()).unwrap();

        let mut newer = Plan::new(tmp.path());
        newer.create_bytes(asset.clone(), b"v2".to_vec());
        newer.revert(Flags::default()).unwrap();

        assert!(!asset.exists());
    }

    #[test]
    fn a_crlf_checkout_of_a_generated_file_is_not_divergence() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("src/models/post.rs");
        plan.create(target.clone(), "line one\nline two\n");
        plan.execute(Flags::default()).unwrap();
        fs::write(&target, "line one\r\nline two\r\n").unwrap();

        plan.revert(Flags::default()).unwrap();

        assert!(!target.exists(), "core.autocrlf is not a user edit");
    }

    #[test]
    fn a_project_without_provenance_still_refuses_a_changed_template() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("src/routes/auth.rs");
        plan.create(target.clone(), "// v1 template\n");
        plan.execute(Flags::default()).unwrap();
        // An app generated before the manifest existed has no baseline.
        fs::remove_file(tmp.path().join(provenance::MANIFEST_PATH)).unwrap();

        let newer = newer_template_plan(&tmp, &target, "// v2 template\n");
        let err = newer.revert(Flags::default()).unwrap_err();

        assert!(matches!(err, GenerateError::Diverged(_)));
        assert!(target.exists());
    }

    #[test]
    fn revert_removes_a_migration_whose_template_changed_since_generation() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            let dir = tmp.path().join("migrations/20260101000000_create_posts");
            plan.create(dir.join("up.sql"), "CREATE TABLE posts ();\n");
            plan.create(dir.join("down.sql"), "DROP TABLE posts;\n");
            plan.execute(Flags::default()).unwrap();

            // Destroy recomputes with a fresh timestamp AND a newer template.
            let mut newer = Plan::new(tmp.path());
            let fresh = tmp.path().join("migrations/99999999999999_create_posts");
            newer.create(fresh.join("up.sql"), "CREATE TABLE posts (id BIGINT);\n");
            newer.create(fresh.join("down.sql"), "DROP TABLE posts;\n");
            newer.revert(Flags::default()).unwrap();

            assert!(!dir.exists());
        });
    }

    #[test]
    fn a_hand_edited_migration_whose_template_changed_is_still_refused() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            let dir = tmp.path().join("migrations/20260101000000_create_posts");
            plan.create(dir.join("up.sql"), "CREATE TABLE posts ();\n");
            plan.create(dir.join("down.sql"), "DROP TABLE posts;\n");
            plan.execute(Flags::default()).unwrap();
            fs::write(dir.join("up.sql"), "CREATE TABLE posts (mine INT);\n").unwrap();

            let mut newer = Plan::new(tmp.path());
            let fresh = tmp.path().join("migrations/99999999999999_create_posts");
            newer.create(fresh.join("up.sql"), "CREATE TABLE posts (id BIGINT);\n");
            newer.create(fresh.join("down.sql"), "DROP TABLE posts;\n");
            let err = newer.revert(Flags::default()).unwrap_err();

            assert!(matches!(err, GenerateError::Diverged(_)));
            assert!(dir.exists());
        });
    }

    #[test]
    fn regenerating_after_a_template_change_refreshes_the_recorded_digest() {
        let (tmp, mut plan) = fixture();
        let target = tmp.path().join("src/routes/auth.rs");
        plan.create(target.clone(), "// v1 template\n");
        plan.execute(Flags::default()).unwrap();

        let mut newer = Plan::new(tmp.path());
        newer.create(target.clone(), "// v2 template\n");
        newer
            .execute(Flags {
                force: true,
                dry_run: false,
            })
            .unwrap();
        newer.revert(Flags::default()).unwrap();

        assert!(!target.exists());
    }

    #[test]
    fn provenance_accumulates_across_generator_runs() {
        let (tmp, mut first) = fixture();
        first.invocation = "model\u{1f}Post".to_owned();
        first.create(tmp.path().join("src/models/post.rs"), "// post\n");
        first.execute(Flags::default()).unwrap();

        let mut second = Plan::new(tmp.path());
        second.invocation = "model\u{1f}Comment".to_owned();
        second.create(tmp.path().join("src/models/comment.rs"), "// comment\n");
        second.execute(Flags::default()).unwrap();

        let recorded = provenance::Provenance::load(tmp.path());
        assert!(
            recorded.contains("src/models/post.rs"),
            "a second generator must not drop the first's baseline"
        );
        assert!(recorded.contains("src/models/comment.rs"));
    }

    #[test]
    fn destroying_one_resource_keeps_another_resources_provenance() {
        let (tmp, mut first) = fixture();
        let post = tmp.path().join("src/models/post.rs");
        first.invocation = "model\u{1f}Post".to_owned();
        first.create(post.clone(), "// post\n");
        first.execute(Flags::default()).unwrap();

        let mut second = Plan::new(tmp.path());
        let comment = tmp.path().join("src/models/comment.rs");
        second.invocation = "model\u{1f}Comment".to_owned();
        second.create(comment.clone(), "// comment\n");
        second.execute(Flags::default()).unwrap();

        first.revert(Flags::default()).unwrap();

        assert!(!post.exists());
        assert!(comment.exists(), "a sibling resource survives");
        let recorded = provenance::Provenance::load(tmp.path());
        assert!(!recorded.contains("src/models/post.rs"));
        assert!(recorded.contains("src/models/comment.rs"));
    }

    #[test]
    fn the_same_command_owns_the_path_it_recorded() {
        // Within one command's arguments the digest is keyed by path, so a
        // recomputed plan whose render has moved on still deletes the file.
        let (tmp, mut generated) = fixture();
        let path = tmp.path().join("src/controllers/post.rs");
        generated.invocation = "controller\u{1f}Post\u{1f}index".to_owned();
        generated.create(path.clone(), "// v1 template\n");
        generated.execute(Flags::default()).unwrap();

        let mut destroy = Plan::new(tmp.path());
        destroy.invocation = "controller\u{1f}Post\u{1f}index".to_owned();
        destroy.create(path.clone(), "// v2 template\n");
        destroy.revert(Flags::default()).unwrap();

        assert!(!path.exists());
    }

    #[test]
    fn a_different_command_never_owns_a_recorded_path() {
        // `autumn destroy model Post` with the fields omitted renders nothing
        // that matches, and must not borrow the digest recorded for the full
        // command — the shared-file reverts are argument-derived and would
        // silently no-op, leaving a half-destroyed project.
        let (tmp, mut generated) = fixture();
        let path = tmp.path().join("src/models/post.rs");
        generated.invocation = "model\u{1f}Post\u{1f}title:String".to_owned();
        generated.create(path.clone(), "// v1 template\n");
        generated.execute(Flags::default()).unwrap();

        let mut destroy = Plan::new(tmp.path());
        destroy.invocation = "model\u{1f}Post".to_owned();
        destroy.create(path.clone(), "// v2 template\n");
        let err = destroy.revert(Flags::default()).unwrap_err();

        assert!(matches!(err, GenerateError::Diverged(_)));
        assert!(path.exists());
    }

    #[test]
    fn a_starter_scaffold_never_owns_a_generators_output() {
        // `autumn new --starter` writes its files through this same engine.
        // Its entries are recorded under its own command, so a later
        // `destroy` of a generator that renders the same path cannot claim
        // the starter's hand-written file.
        let (tmp, mut starter) = fixture();
        let routes = tmp.path().join("src/routes/auth.rs");
        starter.invocation = "new\u{1f}--starter\u{1f}saas\u{1f}app".to_owned();
        starter.create(routes.clone(), "// the starter's own auth routes\n");
        starter.execute(Flags::default()).unwrap();

        let mut destroy = Plan::new(tmp.path());
        destroy.invocation = "auth\u{1f}User".to_owned();
        destroy.create(routes.clone(), "// what generate auth renders\n");
        let err = destroy.revert(Flags::default()).unwrap_err();

        assert!(matches!(err, GenerateError::Diverged(_)));
        assert!(
            routes.exists(),
            "a starter file is never a generator's to delete"
        );
    }

    #[test]
    fn execute_records_provenance_even_when_a_later_action_fails() {
        let (tmp, mut plan) = fixture();
        let good = tmp.path().join("src/models/post.rs");
        // A directory cannot be overwritten by a file write.
        let blocked = tmp.path().join("src/models/blocked.rs");
        fs::create_dir_all(&blocked).unwrap();

        plan.create(good.clone(), "// post\n");
        plan.create(blocked, "// never lands\n");
        plan.execute(Flags {
            dry_run: false,
            force: true,
        })
        .unwrap_err();

        assert!(good.exists());
        assert!(
            provenance::Provenance::load(tmp.path()).contains("src/models/post.rs"),
            "a file already written is still ours"
        );
    }

    #[test]
    fn revert_prunes_provenance_for_what_it_removed_before_failing() {
        let (tmp, mut plan) = fixture();
        let removable = tmp.path().join("a.rs");
        let blocked = tmp.path().join("z.rs");
        plan.create(removable.clone(), "// a\n");
        plan.create(blocked.clone(), "// z\n");
        plan.execute(Flags::default()).unwrap();

        // Replace the second target with a directory: `remove_file` fails on it.
        fs::remove_file(&blocked).unwrap();
        fs::create_dir_all(&blocked).unwrap();

        plan.revert(Flags {
            dry_run: false,
            force: true,
        })
        .unwrap_err();

        assert!(!removable.exists());
        assert!(
            !provenance::Provenance::load(tmp.path()).contains("a.rs"),
            "an entry must never outlive the file it describes"
        );
    }

    #[test]
    fn destroying_a_migration_prunes_its_provenance_entries() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            let dir = tmp.path().join("migrations/20260101000000_create_posts");
            plan.create(dir.join("up.sql"), "CREATE TABLE posts ();\n");
            plan.create(dir.join("down.sql"), "DROP TABLE posts;\n");
            plan.execute(Flags::default()).unwrap();
            assert!(
                provenance::Provenance::load(tmp.path())
                    .contains("migrations/20260101000000_create_posts/up.sql")
            );

            let mut newer = Plan::new(tmp.path());
            let fresh = tmp.path().join("migrations/99999999999999_create_posts");
            newer.create(fresh.join("up.sql"), "CREATE TABLE posts ();\n");
            newer.create(fresh.join("down.sql"), "DROP TABLE posts;\n");
            newer.revert(Flags::default()).unwrap();

            let recorded = provenance::Provenance::load(tmp.path());
            assert!(!recorded.contains("migrations/20260101000000_create_posts/up.sql"));
            assert!(!recorded.contains("migrations/20260101000000_create_posts/down.sql"));
        });
    }

    #[test]
    fn same_suffix_migrations_are_disambiguated_by_the_current_render_alone() {
        // Two directories share a suffix. One still matches what the plan
        // renders; the other only matches its own recorded digest. Selection
        // must follow the render, so manifest content can never aim
        // `remove_dir_all` at the wrong directory.
        no_db_env(|| {
            let (tmp, mut older) = fixture();
            let older_dir = tmp.path().join("migrations/20260101000000_create_posts");
            older.create(older_dir.join("up.sql"), "CREATE TABLE posts (old INT);\n");
            older.create(older_dir.join("down.sql"), "DROP TABLE posts;\n");
            older.execute(Flags::default()).unwrap();

            let mut current = Plan::new(tmp.path());
            let current_dir = tmp.path().join("migrations/20260202000000_create_posts");
            current.create(current_dir.join("up.sql"), "CREATE TABLE posts ();\n");
            current.create(current_dir.join("down.sql"), "DROP TABLE posts;\n");
            current.execute(Flags::default()).unwrap();

            let mut destroy = Plan::new(tmp.path());
            let fresh = tmp.path().join("migrations/99999999999999_create_posts");
            destroy.create(fresh.join("up.sql"), "CREATE TABLE posts ();\n");
            destroy.create(fresh.join("down.sql"), "DROP TABLE posts;\n");
            destroy.revert(Flags::default()).unwrap();

            assert!(!current_dir.exists(), "the matching directory is removed");
            assert!(older_dir.exists(), "the other one is never guessed at");
        });
    }

    #[test]
    fn a_crlf_rewritten_binary_asset_is_still_divergence() {
        let (tmp, mut plan) = fixture();
        let asset = tmp.path().join("static/vendor.bin");
        plan.create_bytes(asset.clone(), b"a\nb".to_vec());
        plan.execute(Flags::default()).unwrap();
        fs::write(&asset, b"a\r\nb").unwrap();

        let err = plan.revert(Flags::default()).unwrap_err();

        assert!(matches!(err, GenerateError::Diverged(_)));
        assert!(asset.exists(), "bytes are never LF-normalised");
    }

    #[test]
    fn a_modify_only_plan_records_nothing() {
        let (tmp, mut plan) = fixture();
        plan.modify(tmp.path().join("src/main.rs"), "fn main() {}\n");
        plan.execute(Flags::default()).unwrap();

        assert!(!tmp.path().join(provenance::MANIFEST_PATH).exists());
    }

    #[cfg(unix)]
    #[test]
    fn a_generator_run_still_writes_its_files_when_provenance_cannot_be_recorded() {
        let (tmp, mut plan) = fixture();
        let outside = tempfile::TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join(".autumn")).unwrap();
        std::os::unix::fs::symlink(
            outside.path().join("escaped.toml"),
            tmp.path().join(provenance::MANIFEST_PATH),
        )
        .unwrap();

        let target = tmp.path().join("out.txt");
        plan.create(target.clone(), "hello");
        plan.execute(Flags::default())
            .expect("recording is best effort, never fatal to a generator run");

        assert!(target.exists());
        assert!(!outside.path().join("escaped.toml").exists());
    }

    #[test]
    fn editing_the_generator_config_drops_the_baseline() {
        // `autumn.generate.toml` never appears in the arguments, so an edited
        // recipe would otherwise leave a textually identical `destroy` looking
        // like the same inputs while the plan is rebuilt from different fields
        // (Codex review of PR #2551).
        let tmp = tempfile::TempDir::new().unwrap();
        let config = tmp.path().join("autumn.generate.toml");
        fs::write(&config, "[scaffold.Post]\nfields = [\"title:String\"]\n").unwrap();
        // Built after the config exists: the identity is captured when the
        // plan is, as it is in a real run.
        let mut generated = Plan::new(tmp.path());
        let target = tmp.path().join("src/models/post.rs");
        generated.create(target.clone(), "// built from the first recipe\n");
        generated.execute(Flags::default()).unwrap();

        fs::write(&config, "[scaffold.Post]\nfields = [\"body:Text\"]\n").unwrap();
        let mut destroy = Plan::new(tmp.path());
        destroy.create(target.clone(), "// built from the second recipe\n");
        let err = destroy.revert(Flags::default()).unwrap_err();

        assert!(matches!(err, GenerateError::Diverged(_)));
        assert!(target.exists());
    }

    #[test]
    fn an_unchanged_generator_config_keeps_the_baseline() {
        let tmp = tempfile::TempDir::new().unwrap();
        fs::write(
            tmp.path().join("autumn.generate.toml"),
            "[scaffold.Post]\nfields = [\"title:String\"]\n",
        )
        .unwrap();
        let mut generated = Plan::new(tmp.path());
        let target = tmp.path().join("src/models/post.rs");
        generated.create(target.clone(), "// v1 template\n");
        generated.execute(Flags::default()).unwrap();

        let mut destroy = Plan::new(tmp.path());
        destroy.create(target.clone(), "// v2 template\n");
        destroy.revert(Flags::default()).unwrap();

        assert!(!target.exists());
    }

    fn i18n_revert(root: &Path, dir: &str) -> Revert {
        Revert::I18nFtlKeys {
            path: root.join(dir).join("en.ftl"),
            pascal: "Post".to_owned(),
            snake: "post".to_owned(),
        }
    }

    /// A project with one generated file and one shared bundle, generated by a
    /// plan that reverts `i18n/en.ftl`.
    fn generated_with_bundle(tmp: &tempfile::TempDir) -> PathBuf {
        let target = tmp.path().join("src/models/post.rs");
        fs::create_dir_all(tmp.path().join("i18n")).unwrap();
        fs::write(
            tmp.path().join("i18n/en.ftl"),
            "# Post\npost.title = Post\n",
        )
        .unwrap();
        let mut generated = Plan::new(tmp.path());
        generated.create(target.clone(), "// v1 template\n");
        generated.push_revert(i18n_revert(tmp.path(), "i18n"));
        sole(generated).execute(Flags::default()).unwrap();
        target
    }

    fn destroy_plan(tmp: &tempfile::TempDir, target: &Path, template: &str, dir: &str) -> Plan {
        let mut destroy = Plan::new(tmp.path());
        destroy.create(target.to_path_buf(), template);
        destroy.push_revert(i18n_revert(tmp.path(), dir));
        sole(destroy)
    }

    #[test]
    fn a_revert_that_moved_off_a_live_target_refuses_the_destroy() {
        // The files match the current render, so the digest is not even
        // consulted. The shared edit would still be left behind (issue #2560).
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);

        let err = destroy_plan(&tmp, &target, "// v1 template\n", "translations")
            .revert(Flags::default())
            .unwrap_err();

        assert!(
            matches!(err, GenerateError::RevertsDropped(ref r) if r.len() == 1),
            "{err}"
        );
        assert!(err.to_string().contains("i18n/en.ftl"), "{err}");
        assert!(target.exists(), "nothing is removed");
    }

    #[test]
    fn a_moved_revert_is_refused_after_a_template_change_too() {
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);

        let err = destroy_plan(&tmp, &target, "// v2 template\n", "translations")
            .revert(Flags::default())
            .unwrap_err();

        assert!(matches!(err, GenerateError::RevertsDropped(_)));
        assert!(target.exists());
    }

    #[test]
    fn force_overrides_a_moved_revert() {
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);

        destroy_plan(&tmp, &target, "// v2 template\n", "translations")
            .revert(Flags {
                force: true,
                ..Flags::default()
            })
            .unwrap();

        assert!(!target.exists());
    }

    #[test]
    fn a_dry_run_reports_a_moved_revert_and_touches_nothing() {
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);

        destroy_plan(&tmp, &target, "// v1 template\n", "translations")
            .revert(Flags {
                dry_run: true,
                ..Flags::default()
            })
            .unwrap();

        assert!(target.exists());
    }

    #[test]
    fn the_same_reverts_keep_the_baseline_across_a_template_change() {
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);

        destroy_plan(&tmp, &target, "// v2 template\n", "i18n")
            .revert(Flags::default())
            .unwrap();

        assert!(!target.exists());
    }

    #[test]
    fn a_revert_planned_in_addition_is_not_a_drop() {
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);
        let mut destroy = destroy_plan(&tmp, &target, "// v2 template\n", "i18n");
        destroy.push_revert(i18n_revert(tmp.path(), "i18n-extra"));

        destroy.revert(Flags::default()).unwrap();

        assert!(!target.exists());
    }

    #[test]
    fn a_recorded_revert_whose_target_is_gone_does_not_block() {
        // `destroy model` then `destroy admin`: the shared entry is already out.
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);
        fs::remove_file(tmp.path().join("i18n/en.ftl")).unwrap();

        destroy_plan(&tmp, &target, "// v2 template\n", "translations")
            .revert(Flags::default())
            .unwrap();

        assert!(!target.exists());
    }

    #[test]
    fn a_manifest_without_recorded_reverts_keeps_the_old_behaviour() {
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);
        let manifest = tmp.path().join(provenance::MANIFEST_PATH);
        let text = fs::read_to_string(&manifest).unwrap();
        let (files, _) = text.split_once("[[runs").expect("a run was recorded");
        fs::write(&manifest, files).unwrap();

        destroy_plan(&tmp, &target, "// v2 template\n", "translations")
            .revert(Flags::default())
            .unwrap();

        assert!(!target.exists());
    }

    #[test]
    fn an_unclaimed_plan_neither_records_nor_checks_reverts() {
        // Two plans of one process share an invocation, so one plan's edits
        // must not count against the other.
        let tmp = tempfile::TempDir::new().unwrap();
        let target = tmp.path().join("src/models/post.rs");
        fs::create_dir_all(tmp.path().join("i18n")).unwrap();
        fs::write(tmp.path().join("i18n/en.ftl"), "").unwrap();
        let mut generated = Plan::new(tmp.path());
        generated.create(target.clone(), "// v1 template\n");
        generated.push_revert(i18n_revert(tmp.path(), "i18n"));
        generated.execute(Flags::default()).unwrap();
        let text = fs::read_to_string(tmp.path().join(provenance::MANIFEST_PATH)).unwrap();
        assert!(!text.contains("runs"), "{text}");

        let mut destroy = Plan::new(tmp.path());
        destroy.create(target.clone(), "// v1 template\n");
        destroy.revert(Flags::default()).unwrap();
        assert!(!target.exists());
    }

    #[test]
    fn a_destroy_prunes_the_recorded_run_with_its_last_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);

        destroy_plan(&tmp, &target, "// v1 template\n", "i18n")
            .revert(Flags::default())
            .unwrap();

        assert!(!tmp.path().join(provenance::MANIFEST_PATH).exists());
    }

    #[test]
    fn a_revert_anchor_ignores_template_text_and_the_project_location() {
        let here = tempfile::TempDir::new().unwrap();
        let there = tempfile::TempDir::new().unwrap();
        let schema = |root: &Path, block: &str| Revert::SchemaTable {
            path: root.join("src/schema.rs"),
            table: "posts".to_owned(),
            expected_block: block.to_owned(),
        };

        assert_eq!(
            schema(here.path(), "v1 columns").anchors(here.path()),
            schema(there.path(), "v2 columns").anchors(there.path()),
        );
        assert_ne!(
            i18n_revert(here.path(), "i18n").anchors(here.path()),
            i18n_revert(here.path(), "translations").anchors(here.path()),
        );
    }

    #[test]
    fn a_list_revert_anchors_each_item_so_a_longer_list_is_a_superset() {
        let root = Path::new("/p");
        let routes = |entries: &[&str]| Revert::RoutesEntries {
            path: root.join("src/main.rs"),
            entries: entries.iter().map(|e| (*e).to_owned()).collect(),
        };
        let short = routes(&["a", "b"]).anchors(root);
        let long = routes(&["a", "b", "c"]).anchors(root);

        assert_eq!(short.len(), 2);
        assert!(short.iter().all(|anchor| long.contains(anchor)));
    }

    #[test]
    fn a_revert_the_plan_skips_is_not_a_drop() {
        // The generator skips a revert when its append is already done. That
        // is file state, not a changed input (issue #2560).
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);
        let mut destroy = Plan::new(tmp.path());
        destroy.create(target.clone(), "// v1 template\n");
        destroy.push_revert(Revert::PwaMainRsInjection {
            path: tmp.path().join("src/main.rs"),
        });

        sole(destroy).revert(Flags::default()).unwrap();

        assert!(!target.exists());
    }

    #[test]
    fn an_unclaimed_destroy_does_not_check_recorded_reverts() {
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);
        let mut destroy = Plan::new(tmp.path());
        destroy.create(target.clone(), "// v1 template\n");
        destroy.push_revert(i18n_revert(tmp.path(), "translations"));

        destroy.revert(Flags::default()).unwrap();

        assert!(!target.exists());
    }

    #[test]
    fn a_finished_destroy_forgets_the_recorded_run() {
        let tmp = tempfile::TempDir::new().unwrap();
        let target = generated_with_bundle(&tmp);
        let stray = tmp.path().join("stray.rs");
        fs::write(&stray, "x").unwrap();
        let manifest = tmp.path().join(provenance::MANIFEST_PATH);
        let mut recorded = provenance::Provenance::load(tmp.path());
        recorded.record(
            tmp.path(),
            &stray,
            provenance::text_digest("x"),
            "other",
            None,
        );
        recorded.save(tmp.path()).unwrap();

        destroy_plan(&tmp, &target, "// v1 template\n", "i18n")
            .revert(Flags::default())
            .unwrap();

        let text = fs::read_to_string(manifest).unwrap();
        assert!(!text.contains("I18nFtlKeys"), "{text}");
        assert!(text.contains("stray.rs"), "{text}");
    }

    #[test]
    fn a_target_outside_the_project_is_never_recorded() {
        let tmp = tempfile::TempDir::new().unwrap();
        let target = tmp.path().join("src/models/post.rs");
        let mut generated = Plan::new(tmp.path());
        generated.create(target, "// v1 template\n");
        generated.push_revert(Revert::PwaMainRsInjection {
            path: PathBuf::from("/elsewhere/main.rs"),
        });

        assert!(generated.revert_anchors().is_empty());
    }

    #[test]
    fn an_owner_dir_changes_the_anchor_and_none_is_stable() {
        let root = Path::new("/p");
        let feature = |dir: Option<&str>| Revert::CargoAutumnWebFeature {
            path: root.join("Cargo.toml"),
            feature: "maud".to_owned(),
            owner_dir: dir.map(|d| root.join(d)),
        };

        assert_eq!(feature(None).anchors(root), feature(None).anchors(root));
        assert_ne!(
            feature(None).anchors(root),
            feature(Some("src/routes")).anchors(root)
        );
    }

    #[test]
    #[allow(
        clippy::too_many_lines,
        reason = "one table row for each Revert variant; splitting it hides a missing row"
    )]
    fn every_revert_kind_anchors_by_its_values_and_not_by_template_text() {
        let root = Path::new("/p");
        let path = |p: &str| root.join(p);
        let s = |v: &str| v.to_owned();
        let kinds: Vec<(&str, Revert, Revert)> = vec![
            (
                "ModDecl",
                Revert::ModDecl {
                    path: path("a"),
                    name: s("x"),
                },
                Revert::ModDecl {
                    path: path("a"),
                    name: s("y"),
                },
            ),
            (
                "RoutesEntries",
                Revert::RoutesEntries {
                    path: path("a"),
                    entries: vec![s("x")],
                },
                Revert::RoutesEntries {
                    path: path("a"),
                    entries: vec![s("y")],
                },
            ),
            (
                "SchemaTable",
                Revert::SchemaTable {
                    path: path("a"),
                    table: s("x"),
                    expected_block: s("1"),
                },
                Revert::SchemaTable {
                    path: path("a"),
                    table: s("y"),
                    expected_block: s("1"),
                },
            ),
            (
                "CargoDeps",
                Revert::CargoDeps {
                    path: path("a"),
                    names: vec![s("x")],
                    owner_dir: path("o"),
                },
                Revert::CargoDeps {
                    path: path("a"),
                    names: vec![s("y")],
                    owner_dir: path("o"),
                },
            ),
            (
                "CargoAutumnWebFeature",
                Revert::CargoAutumnWebFeature {
                    path: path("a"),
                    feature: s("x"),
                    owner_dir: None,
                },
                Revert::CargoAutumnWebFeature {
                    path: path("a"),
                    feature: s("y"),
                    owner_dir: None,
                },
            ),
            (
                "CargoAutumnWebDevFeature",
                Revert::CargoAutumnWebDevFeature {
                    path: path("a"),
                    feature: s("x"),
                    owner_dir: None,
                },
                Revert::CargoAutumnWebDevFeature {
                    path: path("a"),
                    feature: s("y"),
                    owner_dir: None,
                },
            ),
            (
                "JobEntry",
                Revert::JobEntry {
                    path: path("a"),
                    entry: s("x"),
                },
                Revert::JobEntry {
                    path: path("a"),
                    entry: s("y"),
                },
            ),
            (
                "JobsRegistration",
                Revert::JobsRegistration {
                    path: path("a"),
                    owner_dir: path("x"),
                },
                Revert::JobsRegistration {
                    path: path("a"),
                    owner_dir: path("y"),
                },
            ),
            (
                "PolicyRegistration",
                Revert::PolicyRegistration {
                    path: path("a"),
                    pascal: s("X"),
                    snake: s("x"),
                },
                Revert::PolicyRegistration {
                    path: path("a"),
                    pascal: s("Y"),
                    snake: s("x"),
                },
            ),
            (
                "MailPreview",
                Revert::MailPreview {
                    path: path("a"),
                    mailer_type: s("x"),
                },
                Revert::MailPreview {
                    path: path("a"),
                    mailer_type: s("y"),
                },
            ),
            (
                "InboundMailHandler",
                Revert::InboundMailHandler {
                    path: path("a"),
                    handler_module_path: s("x"),
                },
                Revert::InboundMailHandler {
                    path: path("a"),
                    handler_module_path: s("y"),
                },
            ),
            (
                "SystemTestCargoPatch",
                Revert::SystemTestCargoPatch {
                    path: path("a"),
                    snake_name: s("x"),
                },
                Revert::SystemTestCargoPatch {
                    path: path("a"),
                    snake_name: s("y"),
                },
            ),
            (
                "PwaMainRsInjection",
                Revert::PwaMainRsInjection { path: path("a") },
                Revert::PwaMainRsInjection { path: path("b") },
            ),
            (
                "AuthOAuthProviderStubs",
                Revert::AuthOAuthProviderStubs {
                    path: path("a"),
                    providers: vec![s("x")],
                },
                Revert::AuthOAuthProviderStubs {
                    path: path("a"),
                    providers: vec![s("y")],
                },
            ),
            (
                "AuthWebauthnStub",
                Revert::AuthWebauthnStub { path: path("a") },
                Revert::AuthWebauthnStub { path: path("b") },
            ),
            (
                "WebhookEndpointStub",
                Revert::WebhookEndpointStub {
                    path: path("a"),
                    name: s("x"),
                    route_path: s("/r"),
                },
                Revert::WebhookEndpointStub {
                    path: path("a"),
                    name: s("x"),
                    route_path: s("/q"),
                },
            ),
            (
                "SubmitTokenValidateExempt",
                Revert::SubmitTokenValidateExempt {
                    path: path("a"),
                    plural: s("x"),
                    segment: s("validate"),
                },
                Revert::SubmitTokenValidateExempt {
                    path: path("a"),
                    plural: s("x"),
                    segment: s("preview"),
                },
            ),
            (
                "RememberMiddleware",
                Revert::RememberMiddleware { path: path("a") },
                Revert::RememberMiddleware { path: path("b") },
            ),
            (
                "SeedBinLinks",
                Revert::SeedBinLinks {
                    path: path("a"),
                    owner_dir: path("x"),
                },
                Revert::SeedBinLinks {
                    path: path("a"),
                    owner_dir: path("y"),
                },
            ),
            (
                "NestedChildSection",
                Revert::NestedChildSection {
                    path: path("a"),
                    child_plural: s("x"),
                },
                Revert::NestedChildSection {
                    path: path("a"),
                    child_plural: s("y"),
                },
            ),
            (
                "I18nFtlKeys",
                Revert::I18nFtlKeys {
                    path: path("a"),
                    pascal: s("X"),
                    snake: s("x"),
                },
                Revert::I18nFtlKeys {
                    path: path("b"),
                    pascal: s("X"),
                    snake: s("x"),
                },
            ),
        ];

        for (kind, one, other) in kinds {
            let anchors = one.anchors(root);
            assert!(!anchors.is_empty(), "{kind}");
            assert!(
                anchors.iter().all(|a| a.kind() == kind),
                "{kind}: {anchors:?}"
            );
            assert_ne!(
                anchors,
                other.anchors(root),
                "{kind} ignores a value that names the edit"
            );
        }
    }

    #[test]
    fn the_last_consumer_of_a_shared_file_can_still_remove_it() {
        // Only the FIRST writer of a `CreateIfAbsent` file is recorded. The
        // sibling that destroys last has a different command, so requiring it
        // to be that writer would strand the layout the moment a template
        // change stopped the content compare from matching (Codex review of
        // PR #2551).
        let (tmp, mut first) = fixture();
        let shared = tmp.path().join("templates/mailers/_layout.html");
        first.invocation = "mailer\u{1f}Welcome".to_owned();
        first.create_if_absent(shared.clone(), "<html>v1</html>\n");
        first.execute(Flags::default()).unwrap();

        // The second mailer's own run skips the write — the file is there.
        let mut second = Plan::new(tmp.path());
        second.invocation = "mailer\u{1f}Receipt".to_owned();
        second.create_if_absent(shared.clone(), "<html>v2</html>\n");
        second.execute(Flags::default()).unwrap();

        // Destroying the last consumer, under a newer template.
        let mut destroy = Plan::new(tmp.path());
        destroy.invocation = "mailer\u{1f}Receipt".to_owned();
        destroy.create_if_absent(shared.clone(), "<html>v2</html>\n");
        destroy.revert(Flags::default()).unwrap();

        assert!(
            !shared.exists(),
            "the last consumer takes the layout with it"
        );
    }

    #[test]
    fn a_shared_file_still_survives_while_a_sibling_needs_it() {
        let (tmp, mut first) = fixture();
        let shared = tmp.path().join("templates/mailers/_layout.html");
        let sibling = tmp.path().join("templates/mailers/receipt.html");
        first.invocation = "mailer\u{1f}Welcome".to_owned();
        first.create_if_absent(shared.clone(), "<html>v1</html>\n");
        first.execute(Flags::default()).unwrap();
        fs::write(&sibling, "<html>receipt</html>\n").unwrap();

        let mut destroy = Plan::new(tmp.path());
        destroy.invocation = "mailer\u{1f}Welcome".to_owned();
        destroy.create_if_absent(shared.clone(), "<html>v2</html>\n");
        destroy.revert(Flags::default()).unwrap();

        assert!(shared.exists(), "a sibling still renders through it");
    }

    #[test]
    fn a_hand_written_shared_file_is_still_never_removed() {
        // The relaxed claim only accepts a digest Autumn recorded. Content
        // nobody recorded stays put, with a warning, exactly as before.
        let (tmp, mut plan) = fixture();
        let shared = tmp.path().join("templates/mailers/_layout.html");
        fs::create_dir_all(shared.parent().unwrap()).unwrap();
        fs::write(&shared, "<html>hand-written</html>\n").unwrap();

        plan.create_if_absent(shared.clone(), "<html>generated</html>\n");
        plan.execute(Flags::default()).unwrap();
        plan.revert(Flags::default()).unwrap();

        assert!(
            shared.exists(),
            "content Autumn never wrote is never deleted"
        );
    }

    #[test]
    fn revert_applies_mod_decl_revert_and_deletes_now_empty_file() {
        let (tmp, mut plan) = fixture();
        let mod_path = tmp.path().join("mod.rs");
        plan.modify(
            mod_path.clone(),
            crate::generate::schema_edit::add_mod_declaration("", "post"),
        );
        plan.push_revert(Revert::ModDecl {
            path: mod_path.clone(),
            name: "post".to_owned(),
        });
        plan.execute(Flags::default()).unwrap();
        assert!(mod_path.exists());
        plan.revert(Flags::default()).unwrap();
        assert!(!mod_path.exists());
    }

    #[test]
    fn revert_applies_mod_decl_revert_preserving_other_mods() {
        let (tmp, mut plan) = fixture();
        let mod_path = tmp.path().join("mod.rs");
        fs::write(&mod_path, "pub mod user;\n").unwrap();
        plan.modify(
            mod_path.clone(),
            crate::generate::schema_edit::add_mod_declaration("pub mod user;\n", "post"),
        );
        plan.push_revert(Revert::ModDecl {
            path: mod_path.clone(),
            name: "post".to_owned(),
        });
        plan.execute(Flags::default()).unwrap();
        plan.revert(Flags::default()).unwrap();
        assert!(mod_path.exists());
        assert_eq!(fs::read_to_string(&mod_path).unwrap(), "pub mod user;\n");
    }

    #[test]
    fn revert_prunes_now_empty_generated_directory_but_not_sibling_content() {
        let (tmp, mut plan) = fixture();
        let posts_tmpl = tmp.path().join("templates/posts/index.html.tmpl");
        plan.create(posts_tmpl.clone(), "content");
        plan.execute(Flags::default()).unwrap();
        // A sibling directory under `templates/` must survive pruning.
        fs::create_dir_all(tmp.path().join("templates/other")).unwrap();
        fs::write(tmp.path().join("templates/other/keep.tmpl"), "keep").unwrap();

        plan.revert(Flags::default()).unwrap();

        assert!(!posts_tmpl.exists());
        assert!(!tmp.path().join("templates/posts").exists());
        assert!(tmp.path().join("templates").exists());
        assert!(tmp.path().join("templates/other/keep.tmpl").exists());
    }

    #[test]
    fn revert_never_deletes_a_diverged_create_if_absent_file_even_with_force() {
        // A `CreateIfAbsent` target (e.g. a shared mailer layout) may
        // pre-exist before ANY generator ever wrote to it — `generate`
        // silently skips it either way, so content divergence here can't be
        // attributed to "this destroy's own edit gone stale" the way it can
        // for an owned `Create`. `--force` must never delete it (issue
        // #1048 PR review): guessing wrong would destroy real, pre-existing
        // project content this destroy never touched.
        let (tmp, mut plan) = fixture();
        let layout = tmp.path().join("templates/mailers/_layout.html");
        fs::create_dir_all(layout.parent().unwrap()).unwrap();
        fs::write(&layout, "hand-rolled layout, predates any mailer").unwrap();
        plan.create_if_absent(layout.clone(), "generated default layout");

        plan.revert(Flags {
            force: true,
            dry_run: false,
        })
        .unwrap();

        assert!(
            layout.exists(),
            "pre-existing content diverging from the generated default must survive \
             even with --force"
        );
        assert_eq!(
            fs::read_to_string(&layout).unwrap(),
            "hand-rolled layout, predates any mailer"
        );
    }

    #[test]
    fn revert_deletes_a_create_if_absent_file_when_content_matches_the_generated_default() {
        let (tmp, mut plan) = fixture();
        let layout = tmp.path().join("templates/mailers/_layout.html");
        fs::create_dir_all(layout.parent().unwrap()).unwrap();
        plan.create_if_absent(layout.clone(), "generated default layout");
        plan.execute(Flags::default()).unwrap();

        plan.revert(Flags::default()).unwrap();

        assert!(!layout.exists());
    }

    #[test]
    fn revert_keeps_a_dependency_still_needed_by_another_table_in_the_same_schema_file() {
        // issue #1048 PR review: excluding the WHOLE `src/schema.rs` from
        // the crate-usage scan (because this destroy is also rewriting it)
        // hid a second, unrelated `diesel::table!` block that survives the
        // destroy — wrongly treating `diesel` as unused project-wide when
        // it's still needed by that other table. The scan must see
        // `schema.rs`'s real POST-destroy content, not exclude the file
        // outright.
        use crate::generate::dsl::parse_fields;
        use crate::generate::schema_edit::append_schema_table;

        let (tmp, mut plan) = fixture();
        let fields = parse_fields(&["title:String".to_owned()]).unwrap();
        let posts_block = append_schema_table("", "posts", &fields);
        let schema_path = tmp.path().join("src/schema.rs");
        fs::create_dir_all(schema_path.parent().unwrap()).unwrap();
        // A second, pre-existing table this destroy never touches.
        let schema_with_users = append_schema_table("", "users", &fields);
        let schema_content = append_schema_table(&schema_with_users, "posts", &fields);
        fs::write(&schema_path, &schema_content).unwrap();

        let cargo_path = tmp.path().join("Cargo.toml");
        fs::write(
            &cargo_path,
            "[package]\nname = \"x\"\n\n[dependencies]\ndiesel = \"2\"\n",
        )
        .unwrap();

        plan.push_revert(Revert::SchemaTable {
            path: schema_path.clone(),
            table: "posts".to_owned(),
            expected_block: posts_block,
        });
        let models_dir = tmp.path().join("src/models");
        fs::create_dir_all(&models_dir).unwrap();
        plan.push_revert(Revert::CargoDeps {
            path: cargo_path.clone(),
            names: vec!["diesel".to_owned()],
            owner_dir: models_dir,
        });

        plan.revert(Flags::default()).unwrap();

        let schema_after = fs::read_to_string(&schema_path).unwrap();
        assert!(
            !schema_after.contains("posts ("),
            "posts table must be removed"
        );
        assert!(
            schema_after.contains("users ("),
            "the other table must survive: {schema_after}"
        );
        let cargo_after = fs::read_to_string(&cargo_path).unwrap();
        assert!(
            cargo_after.contains("diesel"),
            "diesel must survive — schema.rs still has a diesel::table! for `users`: \
             {cargo_after}"
        );
    }

    #[test]
    fn revert_keeps_ws_feature_when_a_live_scaffold_route_still_uses_sse_stream() {
        // `--live` scaffolds and SSE-transport channels both need the "ws"
        // feature via `autumn_web::sse::stream(...)`, with no `#[ws]`
        // marker at all (issue #1048 PR review) — destroying the only
        // WebSocket-transport channel must not strip "ws" while a live
        // scaffold's route in a completely different directory still needs
        // it.
        let (tmp, mut plan) = fixture();
        let routes_dir = tmp.path().join("src/routes");
        fs::create_dir_all(&routes_dir).unwrap();
        fs::write(
            routes_dir.join("posts.rs"),
            "pub async fn stream_posts() {\n    autumn_web::sse::stream(&state, \"posts\")\n}\n",
        )
        .unwrap();

        let cargo_path = tmp.path().join("Cargo.toml");
        fs::write(
            &cargo_path,
            "[package]\nname = \"x\"\n\n[dependencies]\nautumn-web = { version = \"0.6\", features = [\"ws\"] }\n",
        )
        .unwrap();

        let channels_dir = tmp.path().join("src/channels");
        fs::create_dir_all(&channels_dir).unwrap();
        plan.push_revert(Revert::CargoAutumnWebFeature {
            path: cargo_path.clone(),
            feature: "ws".to_owned(),
            owner_dir: Some(channels_dir),
        });

        plan.revert(Flags::default()).unwrap();

        let cargo_after = fs::read_to_string(&cargo_path).unwrap();
        assert!(
            cargo_after.contains("\"ws\""),
            "ws must survive — a live scaffold route still uses autumn_web::sse::stream: \
             {cargo_after}"
        );
    }

    #[test]
    fn revert_removes_unapplied_migration_matched_by_suffix() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            fs::create_dir_all(tmp.path().join("migrations")).unwrap();
            // Destroy recomputes the plan with a FRESH timestamp, which won't
            // match the real, already-generated directory on disk.
            let plan_dir = tmp.path().join("migrations/99999999999999_create_posts");
            let real_dir = tmp.path().join("migrations/20260101000000_create_posts");
            fs::create_dir_all(&real_dir).unwrap();
            fs::write(real_dir.join("up.sql"), "CREATE TABLE posts ();\n").unwrap();
            fs::write(real_dir.join("down.sql"), "DROP TABLE posts;\n").unwrap();

            plan.create(plan_dir.join("up.sql"), "CREATE TABLE posts ();\n");
            plan.create(plan_dir.join("down.sql"), "DROP TABLE posts;\n");
            // Not executing this plan (it would create the wrong-timestamp
            // dir) — the point is that revert must find `real_dir` by suffix.

            plan.revert(Flags::default()).unwrap();

            assert!(!real_dir.exists());
        });
    }

    /// #2283: an adopted `comments` table starts with the `Comment` model's
    /// own migration. Plant it, a later adoption `ALTER`, and a `Post` model
    /// that is still `#[commentable]`. Returns the real migration directory.
    fn adopted_comments_fixture(tmp: &tempfile::TempDir, plan: &mut Plan) -> PathBuf {
        let plain_sql = "CREATE TABLE comments (id BIGSERIAL PRIMARY KEY, body TEXT NOT NULL, \
                     created_at TIMESTAMP NOT NULL);\n";
        let real_dir = tmp.path().join("migrations/20260101000000_create_comments");
        fs::create_dir_all(&real_dir).unwrap();
        fs::write(real_dir.join("up.sql"), plain_sql).unwrap();
        fs::write(real_dir.join("down.sql"), "DROP TABLE comments;\n").unwrap();
        let adopt = tmp.path().join("migrations/20260102000000_adopt_comments");
        fs::create_dir_all(&adopt).unwrap();
        fs::write(
            adopt.join("up.sql"),
            "ALTER TABLE comments ADD COLUMN commentable_type TEXT, \
             ADD COLUMN commentable_id BIGINT, ADD COLUMN parent_id BIGINT, \
             ADD COLUMN author_id BIGINT, ADD COLUMN deleted_at TIMESTAMP;\n",
        )
        .unwrap();
        fs::create_dir_all(tmp.path().join("src/models")).unwrap();
        fs::write(
            tmp.path().join("src/models/post.rs"),
            "#[commentable]\npub struct Post {}\n",
        )
        .unwrap();
        let plan_dir = tmp.path().join("migrations/99999999999999_create_comments");
        plan.create(plan_dir.join("up.sql"), plain_sql);
        plan.create(plan_dir.join("down.sql"), "DROP TABLE comments;\n");
        real_dir
    }

    #[test]
    fn revert_keeps_a_comments_migration_the_shared_table_needs() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            let real_dir = adopted_comments_fixture(&tmp, &mut plan);
            plan.revert(Flags::default()).unwrap();
            assert!(real_dir.exists(), "`Post` still needs this `CREATE TABLE`");
        });
    }

    #[test]
    fn revert_with_force_removes_a_comments_migration_the_shared_table_needs() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            let real_dir = adopted_comments_fixture(&tmp, &mut plan);
            plan.revert(Flags {
                force: true,
                dry_run: false,
            })
            .unwrap();
            assert!(!real_dir.exists());
        });
    }

    #[test]
    fn revert_removes_a_comments_migration_no_commentable_model_needs() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            let real_dir = adopted_comments_fixture(&tmp, &mut plan);
            fs::remove_file(tmp.path().join("src/models/post.rs")).unwrap();
            plan.revert(Flags::default()).unwrap();
            assert!(!real_dir.exists());
        });
    }

    /// An applied migration is kept even with `--force`, so the warning must
    /// not offer `--force` as the way out.
    #[test]
    fn an_applied_needed_comments_migration_gets_the_applied_warning() {
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                (
                    "AUTUMN_DATABASE__URL",
                    Some("postgres://postgres:x@127.0.0.1:1/nope"),
                ),
                ("DATABASE_URL", None::<&str>),
            ],
            || {
                let (tmp, mut plan) = fixture();
                let real_dir = adopted_comments_fixture(&tmp, &mut plan);
                let warnings = plan.compute_revert_plan(false).warnings;
                assert!(
                    warnings.iter().any(|w| w.contains("appears to be applied")),
                    "{warnings:#?}"
                );
                assert!(
                    !warnings.iter().any(|w| w.contains("pass --force")),
                    "{warnings:#?}"
                );
                assert!(real_dir.exists());
            },
        );
    }

    /// The old behaviour left a separate generator-written shared migration.
    /// The plain `Comment` migration is then not needed.
    #[test]
    fn revert_removes_a_comments_migration_beside_the_generated_shared_one() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            let real_dir = adopted_comments_fixture(&tmp, &mut plan);
            fs::remove_dir_all(tmp.path().join("migrations/20260102000000_adopt_comments"))
                .unwrap();
            let shared = tmp
                .path()
                .join("migrations/202601010000002_create_comments");
            fs::create_dir_all(&shared).unwrap();
            fs::write(
                shared.join("up.sql"),
                super::super::commentable::up_sql(autumn_web::config::DatabaseBackend::Postgres),
            )
            .unwrap();
            plan.revert(Flags::default()).unwrap();
            assert!(!real_dir.exists());
            assert!(shared.exists());
        });
    }

    #[test]
    fn revert_refuses_diverged_migration_sql_without_force() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            fs::create_dir_all(tmp.path().join("migrations")).unwrap();
            let plan_dir = tmp.path().join("migrations/99999999999999_create_posts");
            let real_dir = tmp.path().join("migrations/20260101000000_create_posts");
            fs::create_dir_all(&real_dir).unwrap();
            fs::write(
                real_dir.join("up.sql"),
                "CREATE TABLE posts (extra_col INT);\n",
            )
            .unwrap();
            fs::write(real_dir.join("down.sql"), "DROP TABLE posts;\n").unwrap();

            plan.create(plan_dir.join("up.sql"), "CREATE TABLE posts ();\n");
            plan.create(plan_dir.join("down.sql"), "DROP TABLE posts;\n");

            let err = plan.revert(Flags::default()).unwrap_err();
            assert!(matches!(err, GenerateError::Diverged(_)));
            assert!(real_dir.exists());
        });
    }

    #[test]
    fn revert_never_removes_a_migration_with_an_unreachable_database_even_with_force() {
        // A configured but unreachable database is treated the same as
        // "applied" (conservative: destroy can't confirm it's safe). Even
        // `--force` must not remove the migration files in that case
        // (issue #1048 PR review) — `--force` bypasses content divergence
        // and shared-resource caution, never the applied-migration guard,
        // since deleting files backing a migration the database might
        // already record as applied would leave it unable to reconstruct
        // or roll back that step.
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                (
                    "AUTUMN_DATABASE__URL",
                    Some("postgres://postgres:x@127.0.0.1:1/nope"),
                ),
                ("DATABASE_URL", None::<&str>),
            ],
            || {
                let (tmp, mut plan) = fixture();
                fs::create_dir_all(tmp.path().join("migrations")).unwrap();
                let plan_dir = tmp.path().join("migrations/99999999999999_create_posts");
                let real_dir = tmp.path().join("migrations/20260101000000_create_posts");
                fs::create_dir_all(&real_dir).unwrap();
                fs::write(real_dir.join("up.sql"), "CREATE TABLE posts ();\n").unwrap();
                fs::write(real_dir.join("down.sql"), "DROP TABLE posts;\n").unwrap();

                plan.create(plan_dir.join("up.sql"), "CREATE TABLE posts ();\n");
                plan.create(plan_dir.join("down.sql"), "DROP TABLE posts;\n");

                plan.revert(Flags {
                    force: true,
                    dry_run: false,
                })
                .unwrap();

                assert!(
                    real_dir.exists(),
                    "migration must survive even with --force when the database is unreachable"
                );
            },
        );
    }

    #[test]
    fn revert_never_removes_a_migration_when_only_an_unreachable_shard_is_configured() {
        // A shard-only deployment (no control database role) is a valid
        // shape (issue #1048 PR review): `autumn migrate run --shard
        // <name>` applies user migrations to shard databases independently
        // of any control URL. Checking only the control URL would see "no
        // database configured" and happily delete migration files a shard
        // still needs.
        temp_env::with_vars(
            [
                ("AUTUMN_DATABASE__PRIMARY_URL", None::<&str>),
                ("AUTUMN_DATABASE__URL", None::<&str>),
                ("DATABASE_URL", None::<&str>),
                ("AUTUMN_DATABASE__SHARDS__0__NAME", Some("shard0")),
                (
                    "AUTUMN_DATABASE__SHARDS__0__PRIMARY_URL",
                    Some("postgres://postgres:x@127.0.0.1:1/nope"),
                ),
            ],
            || {
                let (tmp, mut plan) = fixture();
                fs::create_dir_all(tmp.path().join("migrations")).unwrap();
                let plan_dir = tmp.path().join("migrations/99999999999999_create_posts");
                let real_dir = tmp.path().join("migrations/20260101000000_create_posts");
                fs::create_dir_all(&real_dir).unwrap();
                fs::write(real_dir.join("up.sql"), "CREATE TABLE posts ();\n").unwrap();
                fs::write(real_dir.join("down.sql"), "DROP TABLE posts;\n").unwrap();

                plan.create(plan_dir.join("up.sql"), "CREATE TABLE posts ();\n");
                plan.create(plan_dir.join("down.sql"), "DROP TABLE posts;\n");

                plan.revert(Flags {
                    force: true,
                    dry_run: false,
                })
                .unwrap();

                assert!(
                    real_dir.exists(),
                    "migration must survive when a shard is configured but unreachable, \
                     even with no control database URL and even with --force"
                );
            },
        );
    }

    #[test]
    fn revert_is_idempotent_when_migration_dir_missing() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            fs::create_dir_all(tmp.path().join("migrations")).unwrap();
            let plan_dir = tmp.path().join("migrations/99999999999999_create_posts");
            plan.create(plan_dir.join("up.sql"), "CREATE TABLE posts ();\n");
            plan.create(plan_dir.join("down.sql"), "DROP TABLE posts;\n");

            // No matching real directory on disk at all — nothing to do.
            plan.revert(Flags::default()).unwrap();
        });
    }

    #[test]
    fn revert_refuses_to_guess_between_two_migrations_sharing_a_suffix() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            fs::create_dir_all(tmp.path().join("migrations")).unwrap();
            let plan_dir = tmp.path().join("migrations/99999999999999_create_posts");
            // Two independently-created directories normalize to the same
            // suffix (e.g. a `model`-generated one and a hand-run `generate
            // migration` for the same resource), and BOTH have content that
            // exactly matches what this plan expects — content-based
            // disambiguation genuinely can't tell them apart either.
            let first = tmp.path().join("migrations/20260101000000_create_posts");
            let second = tmp.path().join("migrations/20260201000000_create_posts");
            fs::create_dir_all(&first).unwrap();
            fs::write(first.join("up.sql"), "CREATE TABLE posts ();\n").unwrap();
            fs::write(first.join("down.sql"), "DROP TABLE posts;\n").unwrap();
            fs::create_dir_all(&second).unwrap();
            fs::write(second.join("up.sql"), "CREATE TABLE posts ();\n").unwrap();
            fs::write(second.join("down.sql"), "DROP TABLE posts;\n").unwrap();

            plan.create(plan_dir.join("up.sql"), "CREATE TABLE posts ();\n");
            plan.create(plan_dir.join("down.sql"), "DROP TABLE posts;\n");

            // Refuses to guess, even without --force: neither directory is removed.
            plan.revert(Flags::default()).unwrap();
            assert!(
                first.exists(),
                "ambiguous suffix must not delete either dir"
            );
            assert!(
                second.exists(),
                "ambiguous suffix must not delete either dir"
            );
        });
    }

    #[test]
    fn revert_disambiguates_shared_suffix_migrations_by_exact_content_match() {
        no_db_env(|| {
            let (tmp, mut plan) = fixture();
            fs::create_dir_all(tmp.path().join("migrations")).unwrap();
            let plan_dir = tmp.path().join("migrations/99999999999999_create_posts");
            // Two directories share a suffix, but only one has content that
            // exactly matches what this plan would have produced — that one
            // (and only that one) should be identified and removed.
            let matching = tmp.path().join("migrations/20260101000000_create_posts");
            let other = tmp.path().join("migrations/20260201000000_create_posts");
            fs::create_dir_all(&matching).unwrap();
            fs::write(matching.join("up.sql"), "CREATE TABLE posts ();\n").unwrap();
            fs::write(matching.join("down.sql"), "DROP TABLE posts;\n").unwrap();
            fs::create_dir_all(&other).unwrap();
            fs::write(other.join("up.sql"), "CREATE TABLE posts (extra INT);\n").unwrap();
            fs::write(other.join("down.sql"), "DROP TABLE posts;\n").unwrap();

            plan.create(plan_dir.join("up.sql"), "CREATE TABLE posts ();\n");
            plan.create(plan_dir.join("down.sql"), "DROP TABLE posts;\n");

            plan.revert(Flags::default()).unwrap();

            assert!(
                !matching.exists(),
                "the content-matching directory must be removed"
            );
            assert!(
                other.exists(),
                "the non-matching directory must be left alone"
            );
        });
    }

    #[test]
    fn revert_prunes_now_empty_directory_after_shared_submodule_deletion() {
        // A single mailer's `src/mailers/previews/mod.rs` empties down to
        // nothing (deleted + pruned by the ordinary Modify-turned-empty
        // path), which then orphans `pub mod previews;` in
        // `src/mailers/mod.rs` — cleaned up by `sync_mod_declarations_in`.
        // That leaves `src/mailers/` itself empty; it must be pruned too,
        // exactly like every other now-empty generated directory.
        let tmp = tempfile::TempDir::new().unwrap();
        fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname=\"x\"\n\n[dependencies]\nautumn-web = \"0.6\"\n",
        )
        .unwrap();
        fs::create_dir_all(tmp.path().join("src")).unwrap();
        fs::write(
            tmp.path().join("src/main.rs"),
            "use autumn_web::prelude::*;\n\n#[autumn_web::main]\nasync fn main() {\n    \
             autumn_web::app().routes(routes![]).run().await;\n}\n",
        )
        .unwrap();

        let plan =
            crate::generate::mailer::plan_mailer(tmp.path(), "Welcome", None, false).unwrap();
        plan.execute(Flags::default()).unwrap();
        assert!(tmp.path().join("src/mailers/mod.rs").exists());

        plan.revert(Flags::default()).unwrap();

        assert!(
            !tmp.path().join("src/mailers").exists(),
            "src/mailers/ must be fully pruned once mod.rs and every file under it are gone, \
             just like every other now-empty generated directory"
        );
    }

    #[test]
    fn multipart_and_storage_have_feature_markers() {
        // Attachment scaffolds enable `autumn-web/multipart` and
        // `autumn-web/storage`; both must carry markers so `autumn destroy`
        // of the last attachment model can't strip a feature a hand-written
        // route still uses (PR #1867 review).
        // The marker is the bare `Multipart` substring so it also catches a
        // route that names the extractor unqualified via `use
        // autumn_web::prelude::*;` (the prelude re-exports `Multipart`), not
        // just the fully-qualified `autumn_web::extract::Multipart` spelling.
        let multipart = autumn_web_feature_markers("multipart");
        assert!(
            multipart.contains(&"Multipart"),
            "multipart marker must catch bare `Multipart` (covers prelude-unqualified \
             and `autumn_web::extract::Multipart` usage), got {multipart:?}"
        );

        let storage = autumn_web_feature_markers("storage");
        assert!(
            storage.contains(&"autumn_web::storage"),
            "storage marker must match `autumn_web::storage`, got {storage:?}"
        );
    }

    #[test]
    fn multipart_and_storage_markers_retain_features_for_handwritten_routes() {
        // A hand-written route using the multipart extractor and the blob
        // store must keep those features alive even when the model/route the
        // attachment scaffold generated is being destroyed (excluded). The
        // route deliberately imports through `use autumn_web::prelude::*;` and
        // names `Multipart` UNQUALIFIED (the prelude re-exports it), the exact
        // shape the narrower `extract::Multipart` marker used to miss; the
        // blob store stays a `autumn_web::storage::` path since the prelude
        // does not re-export storage types.
        let tmp = tempfile::TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("src/routes")).unwrap();
        let handwritten = tmp.path().join("src/routes/manual.rs");
        fs::write(
            &handwritten,
            "use autumn_web::prelude::*;\n\n\
             async fn upload(mut mp: Multipart, store: autumn_web::storage::BlobStoreState) {}\n",
        )
        .unwrap();

        // The scaffold's own generated files are being destroyed — excluded
        // from the scan so they can't self-retain — but the hand-written
        // route is not, so both features must stay needed.
        let excluding = vec![tmp.path().join("src/models/photo.rs")];
        let overrides = HashMap::new();
        assert!(
            autumn_web_feature_still_needed_elsewhere(
                "multipart",
                tmp.path(),
                &excluding,
                &overrides
            ),
            "multipart must be retained while a hand-written route uses the Multipart extractor"
        );
        assert!(
            autumn_web_feature_still_needed_elsewhere(
                "storage",
                tmp.path(),
                &excluding,
                &overrides
            ),
            "storage must be retained while a hand-written route references autumn_web::storage::"
        );

        // With the hand-written route removed too, nothing references the
        // features anymore — they become free to strip.
        fs::remove_file(&handwritten).unwrap();
        assert!(!autumn_web_feature_still_needed_elsewhere(
            "multipart",
            tmp.path(),
            &excluding,
            &overrides
        ));
        assert!(!autumn_web_feature_still_needed_elsewhere(
            "storage",
            tmp.path(),
            &excluding,
            &overrides
        ));
    }

    /// A module import has no trailing `::`. It must still keep the feature
    /// (issue #2186).
    #[test]
    fn storage_and_markdown_markers_match_module_imports() {
        let cases = [
            ("storage", "use autumn_web::storage;\n"),
            ("storage", "use autumn_web::storage as blobs;\n"),
            ("markdown", "use autumn_web::markdown;\n"),
            ("markdown", "use autumn_web::markdown as md;\n"),
        ];
        for (feature, source) in cases {
            let tmp = tempfile::TempDir::new().unwrap();
            fs::create_dir_all(tmp.path().join("src")).unwrap();
            let file = tmp.path().join("src/handwritten.rs");
            fs::write(&file, source).unwrap();
            let still_needed = || {
                autumn_web_feature_still_needed_elsewhere(feature, tmp.path(), &[], &HashMap::new())
            };
            assert!(still_needed(), "{feature} must stay for {source:?}");
            fs::remove_file(&file).unwrap();
            assert!(!still_needed(), "{feature} must go when no file uses it");
        }
    }

    /// Every spelling that reaches a crate by name is a marker; a dependency
    /// used only through an `extern crate … as` alias must not read as unused
    /// (issue #1631 review).
    #[test]
    fn crate_reference_markers_cover_every_spelling_that_names_a_crate() {
        let markers = crate_reference_markers("autumn-admin-plugin");
        let matches = |src: &str| markers.iter().any(|m| src.contains(m.as_str()));
        assert!(matches("let p = autumn_admin_plugin::AdminPlugin::new();"));
        assert!(matches("use autumn_admin_plugin::AdminPlugin;"));
        assert!(matches("use autumn_admin_plugin as admin;"));
        assert!(matches("extern crate autumn_admin_plugin as admin;"));
        assert!(matches("extern crate autumn_admin_plugin;"));
        assert!(!matches("let x = 1;"));
        assert!(!matches("use some_other_crate::Thing;"));
        // A crate whose name merely EXTENDS this one does match, and that is
        // deliberate: these are substring probes, and the two possible errors
        // are not symmetric. Over-retaining leaves an unused manifest line;
        // under-retaining strips a dependency out from under code that still
        // compiles against it. The tie goes to the build.
        assert!(matches("use autumn_admin_plugin_extras::Thing;"));
    }

    // ---- issue #2557: sweep files the templates no longer name ------------
    //
    // A newer template can rename or drop a generated file. The recomputed
    // plan then names no action for the old path. A claimed plan sweeps it.

    /// A plan claimed as the sole resource of its invocation.
    fn sole(mut plan: Plan) -> Plan {
        plan.sole_resource = true;
        plan
    }

    /// Generate `old.rs` + `kept.rs` under a claimed plan.
    fn generated_v1(tmp: &tempfile::TempDir) -> (PathBuf, PathBuf) {
        let old = tmp.path().join("src/widgets/old.rs");
        let kept = tmp.path().join("src/kept.rs");
        let mut v1 = sole(Plan::new(tmp.path()));
        v1.create(old.clone(), "// v1 old\n");
        v1.create(kept.clone(), "// kept\n");
        v1.execute(Flags::default()).unwrap();
        (old, kept)
    }

    /// The plan a newer CLI builds: `old.rs` is now `new.rs`.
    fn renamed_v2(tmp: &tempfile::TempDir) -> Plan {
        let mut v2 = sole(Plan::new(tmp.path()));
        v2.create(tmp.path().join("src/widgets/new.rs"), "// v2 new\n");
        v2.create(tmp.path().join("src/kept.rs"), "// kept\n");
        v2
    }

    /// Generate `src/models/Foo.rs` with `v1`. Return it and the plan of a
    /// newer CLI that writes `v2` to `src/models/foo.rs` (issue #3382).
    fn case_renamed(tmp: &tempfile::TempDir, v1: &str, v2: &str) -> (PathBuf, Plan) {
        let old = tmp.path().join("src/models/Foo.rs");
        let mut first = sole(Plan::new(tmp.path()));
        first.create(old.clone(), v1);
        first.execute(Flags::default()).unwrap();
        let mut newer = sole(Plan::new(tmp.path()));
        newer.create(tmp.path().join("src/models/foo.rs"), v2);
        (old, newer)
    }

    /// Like [`case_renamed`], but only the directory changes case:
    /// `src/models/foo.rs` becomes `src/Models/foo.rs`.
    fn dir_case_renamed(tmp: &tempfile::TempDir, v1: &str, v2: &str) -> (PathBuf, Plan) {
        let old = tmp.path().join("src/models/foo.rs");
        let mut first = sole(Plan::new(tmp.path()));
        first.create(old.clone(), v1);
        first.execute(Flags::default()).unwrap();
        let mut newer = sole(Plan::new(tmp.path()));
        newer.create(tmp.path().join("src/Models/foo.rs"), v2);
        (old, newer)
    }

    #[test]
    fn a_directory_case_rename_removes_the_untouched_file() {
        for (v1, v2) in [("// v1\n", "// v2\n"), ("// same\n", "// same\n")] {
            let tmp = tempfile::TempDir::new().unwrap();
            let (old, newer) = dir_case_renamed(&tmp, v1, v2);
            let one_dir = tmp.path().join("src/Models").exists();

            newer.revert(Flags::default()).unwrap();

            // A case-sensitive host has no `src/Models`, so the sweep keeps
            // the orphan with a warning.
            assert_eq!(old.exists(), !one_dir, "{v1:?} -> {v2:?}");
            assert_eq!(
                provenance::Provenance::load(tmp.path()).contains("src/models/foo.rs"),
                !one_dir,
                "{v1:?} -> {v2:?}"
            );
        }
    }

    #[test]
    fn a_failed_destroy_still_drops_the_alias_of_a_removed_file() {
        // The second removal fails (a directory is no file). The first file
        // is gone, so its entry, under any spelling, must go too.
        let tmp = tempfile::TempDir::new().unwrap();
        let (old, mut newer) = case_renamed(&tmp, "// v1\n", "// v2\n");
        let blocker = tmp.path().join("src/models/zz.rs");
        fs::create_dir_all(&blocker).unwrap();
        newer.create(blocker, "// zz\n");

        let result = newer.revert(Flags {
            force: true,
            ..Flags::default()
        });

        assert!(result.is_err(), "removing a directory as a file fails");
        assert!(!old.exists());
        assert!(!provenance::Provenance::load(tmp.path()).contains("src/models/Foo.rs"));
    }

    #[test]
    fn a_case_only_rename_with_new_contents_removes_the_untouched_file() {
        // On a case-insensitive host the normal pass removes it. On a
        // case-sensitive host the sweep does.
        let tmp = tempfile::TempDir::new().unwrap();
        let (old, newer) = case_renamed(&tmp, "// v1\n", "// v2\n");

        newer.revert(Flags::default()).unwrap();

        assert!(!old.exists());
        assert!(
            !tmp.path().join(provenance::MANIFEST_PATH).exists(),
            "no stale entry"
        );
    }

    #[test]
    fn a_case_only_rename_with_same_contents_drops_the_recorded_entry() {
        let tmp = tempfile::TempDir::new().unwrap();
        let (old, newer) = case_renamed(&tmp, "// same\n", "// same\n");

        newer.revert(Flags::default()).unwrap();

        assert!(!old.exists());
        assert!(
            !tmp.path().join(provenance::MANIFEST_PATH).exists(),
            "no stale entry"
        );
    }

    #[test]
    fn a_case_only_rename_still_keeps_an_edited_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        let (old, newer) = case_renamed(&tmp, "// v1\n", "// v2\n");
        fs::write(&old, "// mine\n").unwrap();
        let one_entry = tmp.path().join("src/models/foo.rs").exists();

        let result = newer.revert(Flags::default());

        if one_entry {
            assert!(matches!(result, Err(GenerateError::Diverged(_))));
        } else {
            result.unwrap(); // the sweep keeps it with a warning.
        }
        assert!(old.exists());
        assert!(provenance::Provenance::load(tmp.path()).contains("src/models/Foo.rs"));
    }

    #[test]
    fn a_claimed_execute_records_owned_and_shared_scopes() {
        let (tmp, plan) = fixture();
        let mut plan = sole(plan);
        plan.create(tmp.path().join("a.rs"), "a");
        plan.create_bytes(tmp.path().join("b.png"), vec![1]);
        plan.create_if_absent(tmp.path().join("c.html"), "c");
        plan.execute(Flags::default()).unwrap();

        let recorded = provenance::Provenance::load(tmp.path());
        let mut scopes: Vec<_> = recorded
            .recorded_by(&plan.invocation)
            .map(|r| (r.key.to_owned(), r.scope))
            .collect();
        scopes.sort();
        assert_eq!(
            scopes,
            vec![
                ("a.rs".to_owned(), Some(provenance::Scope::Owned)),
                ("b.png".to_owned(), Some(provenance::Scope::Owned)),
                ("c.html".to_owned(), Some(provenance::Scope::Shared)),
            ]
        );
    }

    #[test]
    fn an_unclaimed_execute_records_no_scope() {
        let (tmp, mut plan) = fixture();
        plan.create(tmp.path().join("a.rs"), "a");
        plan.execute(Flags::default()).unwrap();

        let recorded = provenance::Provenance::load(tmp.path());
        let scopes: Vec<_> = recorded
            .recorded_by(&plan.invocation)
            .map(|r| r.scope)
            .collect();
        assert_eq!(scopes, vec![None]);
    }

    #[test]
    fn destroy_removes_a_file_the_templates_have_since_renamed() {
        let tmp = tempfile::TempDir::new().unwrap();
        let (old, kept) = generated_v1(&tmp);

        renamed_v2(&tmp).revert(Flags::default()).unwrap();

        assert!(!old.exists(), "the stranded file must go");
        assert!(!kept.exists());
        assert!(
            !tmp.path().join("src/widgets").exists(),
            "the emptied directory is pruned"
        );
        assert!(
            !tmp.path().join(provenance::MANIFEST_PATH).exists(),
            "no entry outlives its file"
        );
    }

    #[test]
    fn destroy_keeps_an_edited_renamed_file_even_with_force() {
        let tmp = tempfile::TempDir::new().unwrap();
        let (old, _) = generated_v1(&tmp);
        fs::write(&old, "// mine\n").unwrap();

        renamed_v2(&tmp)
            .revert(Flags {
                force: true,
                dry_run: false,
            })
            .unwrap();

        assert!(old.exists(), "an edit is never swept");
        assert!(provenance::Provenance::load(tmp.path()).contains("src/widgets/old.rs"));
    }

    #[test]
    fn a_dry_run_lists_the_sweep_and_touches_nothing() {
        let tmp = tempfile::TempDir::new().unwrap();
        let (old, _) = generated_v1(&tmp);
        let v2 = renamed_v2(&tmp);

        let plan = v2.compute_revert_plan(false);
        assert_eq!(plan.swept.keys().collect::<Vec<_>>(), vec![&old]);

        v2.revert(Flags {
            dry_run: true,
            force: false,
        })
        .unwrap();
        assert!(old.exists());
        assert!(provenance::Provenance::load(tmp.path()).contains("src/widgets/old.rs"));
    }

    #[test]
    fn a_swept_file_edited_after_planning_refuses_the_whole_destroy() {
        let tmp = tempfile::TempDir::new().unwrap();
        let (old, kept) = generated_v1(&tmp);
        let v2 = renamed_v2(&tmp);
        let plan = v2.compute_revert_plan(false);
        fs::write(&old, "// saved late\n").unwrap();

        let mut touched = Vec::new();
        let mut removed = Removed::default();
        let err = v2
            .apply_revert(&plan, &mut touched, &mut removed)
            .unwrap_err();

        assert!(matches!(err, GenerateError::Diverged(ref paths) if paths == &vec![old.clone()]));
        assert!(old.exists() && kept.exists(), "nothing is changed");
    }

    #[test]
    fn a_refused_destroy_sweeps_nothing() {
        let tmp = tempfile::TempDir::new().unwrap();
        let (old, kept) = generated_v1(&tmp);
        fs::write(&kept, "// mine\n").unwrap();

        let err = renamed_v2(&tmp).revert(Flags::default()).unwrap_err();

        assert!(matches!(err, GenerateError::Diverged(_)));
        assert!(old.exists(), "a refused destroy removes nothing");
    }

    #[test]
    fn an_unclaimed_destroy_never_sweeps() {
        // The shape of the "destroying one of two resources" tests: two
        // resources from one process share one argv.
        let tmp = tempfile::TempDir::new().unwrap();
        let mut first = Plan::new(tmp.path());
        first.create(tmp.path().join("src/jobs/a.rs"), "a");
        first.execute(Flags::default()).unwrap();
        let mut second = Plan::new(tmp.path());
        second.create(tmp.path().join("src/jobs/b.rs"), "b");
        second.execute(Flags::default()).unwrap();

        second.revert(Flags::default()).unwrap();

        assert!(tmp.path().join("src/jobs/a.rs").exists());
    }

    #[test]
    fn a_claimed_destroy_never_sweeps_an_unclaimed_entry() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut first = Plan::new(tmp.path());
        first.create(tmp.path().join("src/jobs/a.rs"), "a");
        first.execute(Flags::default()).unwrap();
        let mut second = sole(Plan::new(tmp.path()));
        second.create(tmp.path().join("src/jobs/b.rs"), "b");

        second.revert(Flags::default()).unwrap();

        assert!(tmp.path().join("src/jobs/a.rs").exists());
    }

    #[test]
    fn a_missing_orphan_loses_its_entry() {
        let tmp = tempfile::TempDir::new().unwrap();
        let (old, _) = generated_v1(&tmp);
        fs::remove_file(&old).unwrap();

        renamed_v2(&tmp).revert(Flags::default()).unwrap();

        assert!(!tmp.path().join(provenance::MANIFEST_PATH).exists());
    }

    #[test]
    fn a_stale_entry_alone_is_still_pruned() {
        // Nothing to remove, but the entry for a missing file must go.
        let tmp = tempfile::TempDir::new().unwrap();
        let old = tmp.path().join("src/old.rs");
        let mut v1 = sole(Plan::new(tmp.path()));
        v1.create(old.clone(), "x");
        v1.execute(Flags::default()).unwrap();
        fs::remove_file(&old).unwrap();

        sole(Plan::new(tmp.path()))
            .revert(Flags::default())
            .unwrap();

        assert!(!tmp.path().join(provenance::MANIFEST_PATH).exists());
    }

    #[test]
    fn a_swept_file_no_longer_keeps_a_dependency_alive() {
        // `old.rs` used the crate. It goes with this destroy, so it is not
        // evidence that the crate is still needed.
        no_db_env(|| {
            let tmp = tempfile::TempDir::new().unwrap();
            let cargo = tmp.path().join("Cargo.toml");
            fs::write(
                &cargo,
                "[package]\nname = \"app\"\n\n[dependencies]\nfoo-crate = \"1\"\n",
            )
            .unwrap();
            let mut v1 = sole(Plan::new(tmp.path()));
            v1.create(tmp.path().join("src/old.rs"), "use foo_crate::X;\n");
            v1.execute(Flags::default()).unwrap();

            let mut v2 = sole(Plan::new(tmp.path()));
            v2.create(tmp.path().join("src/new.rs"), "// v2\n");
            v2.push_revert(Revert::CargoDeps {
                path: cargo.clone(),
                names: vec!["foo-crate".to_owned()],
                owner_dir: tmp.path().join("src/models"),
            });
            v2.revert(Flags::default()).unwrap();

            assert!(!tmp.path().join("src/old.rs").exists());
            assert!(
                !fs::read_to_string(&cargo).unwrap().contains("foo-crate"),
                "the dependency must go with its last user"
            );
        });
    }

    #[test]
    fn only_the_first_claim_in_a_process_is_sole() {
        let claimed = AtomicBool::new(false);
        let (_tmp, mut first) = fixture();
        let (_tmp2, mut second) = fixture();

        assert!(first.claim_with(&claimed));
        assert!(first.sole_resource);
        assert!(!second.claim_with(&claimed), "one plan per process");
        assert!(!second.sole_resource);
    }
}