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
//! Project scaffolding for `autumn new <name>`.
//!
//! Generates a complete Autumn project directory from embedded templates.

use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::Path;

use autumn_web::credentials::{MasterKey, encrypt};

pub mod templates {
    pub const CARGO_TOML: &str = include_str!("templates/Cargo.toml.tmpl");
    /// JSON-first API flavor (`autumn new --api`): drops the HTML/CSS view
    /// stack (`maud`) and disables `autumn-web`'s default view features.
    pub const CARGO_API_TOML: &str = include_str!("templates/Cargo.api.toml.tmpl");
    pub const README: &str = include_str!("templates/README.md.tmpl");
    pub const MAIN_RS: &str = include_str!("templates/main.rs.tmpl");
    /// JSON-first API flavor: `Json<...>` handlers, no `maud`/layout/HTML.
    pub const MAIN_API_RS: &str = include_str!("templates/main.api.rs.tmpl");
    pub const AUTUMN_TOML: &str = include_str!("templates/autumn.toml.tmpl");
    pub const DOCKERFILE: &str = include_str!("templates/Dockerfile.tmpl");
    /// JSON-first API flavor: no Tailwind download / CSS build / static copy.
    pub const DOCKERFILE_API: &str = include_str!("templates/Dockerfile.api.tmpl");
    pub const DOCKERIGNORE: &str = include_str!("templates/.dockerignore.tmpl");
    pub const BUILD_RS: &str = include_str!("templates/build.rs.tmpl");
    /// JSON-first API flavor: build provenance only, no Tailwind CSS step.
    pub const BUILD_API_RS: &str = include_str!("templates/build.api.rs.tmpl");
    pub const INPUT_CSS: &str = include_str!("templates/input.css.tmpl");
    pub const TAILWIND_CONFIG: &str = include_str!("templates/tailwind.config.js.tmpl");
    pub const GITIGNORE: &str = include_str!("templates/gitignore.tmpl");
    pub const ENV_EXAMPLE: &str = include_str!("templates/env.example.tmpl");
    pub const SEED_RS: &str = include_str!("templates/seed.rs.tmpl");
    pub const SEED_CARGO_TOML: &str = include_str!("templates/seed_Cargo.toml.tmpl");
    pub const INTEGRATION_TEST: &str = include_str!("templates/tests/integration_test.rs.tmpl");
    pub const CI_WORKFLOW: &str = include_str!("templates/.github/workflows/ci.yml.tmpl");
    pub const POSTURE_GATE_WORKFLOW: &str =
        include_str!("templates/.github/workflows/posture-gate.yml.tmpl");
    /// Dependency advisory policy read by the generated CI's `cargo deny check
    /// advisories` gate (issue #1600). Deliberately *not* framework-owned — see
    /// [`super::framework_owned_files`].
    pub const DENY_TOML: &str = include_str!("templates/deny.toml.tmpl");
    pub const RUST_TOOLCHAIN: &str = include_str!("templates/rust-toolchain.toml.tmpl");
    pub const RUSTFMT: &str = include_str!("templates/rustfmt.toml.tmpl");
    pub const CLIPPY: &str = include_str!("templates/clippy.toml.tmpl");
    pub const CARGO_CONFIG: &str = include_str!("templates/cargo-config.toml.tmpl");
}

/// Variables substituted into project and starter template files.
///
/// Shared by the base `autumn new` scaffold and the starter render path so both
/// honour the exact same substitution tokens (issue #993 reuses the existing
/// `new` render path for starters).
pub struct TemplateVars<'a> {
    /// The project name exactly as given on the CLI (e.g. `my-app`).
    pub project_name: &'a str,
    /// The Rust crate name (`project_name` with `-` replaced by `_`).
    pub crate_name: &'a str,
    /// The `autumn-web` version this CLI was built against.
    pub autumn_version: &'a str,
    /// The MSRV stamped into generated `Cargo.toml` files.
    pub rust_version: &'a str,
}

/// Render a single embedded template, substituting the standard `{{…}}` tokens.
///
/// Templates are embedded at compile time and may be checked out with CRLF line
/// endings on Windows (git autocrlf); normalising to LF first keeps the
/// `\n`-anchored rewrites (and the generated output) deterministic across hosts.
pub fn render_template(content: &str, vars: &TemplateVars<'_>) -> String {
    content
        .replace("\r\n", "\n")
        .replace("{{project_name}}", vars.project_name)
        .replace("{{crate_name}}", vars.crate_name)
        .replace("{{autumn_version}}", vars.autumn_version)
        .replace("{{rust_version}}", vars.rust_version)
}

/// Errors that can occur during project generation.
#[derive(Debug, thiserror::Error)]
pub enum NewError {
    /// The project name is not a valid Rust package name.
    #[error("invalid project name '{0}': {1}")]
    InvalidName(String, String),

    /// A directory with this name already exists.
    #[error("directory '{0}' already exists")]
    AlreadyExists(String),

    /// The requested option combination is not supported.
    #[error("incompatible options: {0}")]
    IncompatibleOptions(String),

    /// Filesystem error during project creation.
    #[error("failed to create project: {0}")]
    Io(#[from] std::io::Error),
}

/// Entry point called from `main.rs` and delegates to [`generate_with`].
pub fn run(name: &str, opts: GenerateOptions) {
    let cwd = std::env::current_dir().unwrap_or_else(|e| {
        eprintln!("Error: cannot determine current directory: {e}");
        std::process::exit(1);
    });
    let result = if opts == GenerateOptions::default() {
        generate(name, &cwd)
    } else {
        generate_with(name, &cwd, opts)
    };
    if let Err(e) = result {
        eprintln!("Error: {e}");
        std::process::exit(1);
    }
}

/// Optional toggles applied to project generation.
// Independent on/off scaffolding toggles; a bitflags/enum here would be less
// clear than named booleans at the (few) call sites.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
pub struct GenerateOptions {
    /// Scaffold the optional i18n module (`i18n/en.ftl`, `[i18n]` block,
    /// `i18n` feature flag on `autumn-web`).
    pub with_i18n: bool,
    /// Scaffold the optional seed binary and enable `autumn-web/seed`.
    pub with_seed: bool,
    /// Daemon-flavored starter: a model-free app that builds with **no** Postgres
    /// (drops the default `db` feature and migrations), ready for `autumn serve`.
    pub with_daemon: bool,
    /// Managed/bundled-Postgres daemon starter: keeps `db`, enables the
    /// `managed-pg` feature, and wires a managed local Postgres provider.
    /// Implies [`Self::with_daemon`]-style serve usage. Mutually exclusive with a
    /// DB-free daemon.
    pub with_bundled_pg: bool,
    /// JSON-first API flavor (`autumn new --api`): emit a lean skeleton with no
    /// HTML/CSS/Tailwind artifacts. Handlers return `Json<...>`; the `maud`
    /// dependency and `autumn-web`'s view features (maud/htmx/tailwind) are
    /// dropped, and the Tailwind/CSS build step, `input.css`, `tailwind.config.js`,
    /// and vendored JS/static assets are not scaffolded. Keeps `db`/migrations so
    /// database features still work. Mutually exclusive with the daemon flavors.
    pub with_api: bool,
}

/// Reject `--with` on the DB-free daemon starter.
///
/// Plugins depend on `autumn-web` with default features. Cargo unifies them,
/// so the database stack returns to a daemon that must not have it.
///
/// # Errors
///
/// [`NewError::IncompatibleOptions`] when `plugins` is not zero and the
/// starter is the DB-free daemon.
pub fn check_with_plugins(opts: GenerateOptions, plugins: usize) -> Result<(), NewError> {
    if plugins > 0 && opts.with_daemon && !opts.with_bundled_pg {
        return Err(NewError::IncompatibleOptions(
            "--daemon scaffolds a database-free app, so --with is not supported. \
             Plugins enable the database features again. Use --bundled-pg for a \
             daemon with a managed Postgres, or remove --with"
                .to_owned(),
        ));
    }
    Ok(())
}

/// Generate a new Autumn project under `parent_dir/name` with default options.
pub fn generate(name: &str, parent_dir: &Path) -> Result<(), NewError> {
    generate_with(name, parent_dir, GenerateOptions::default())
}

/// Reject unsupported flag combinations before any files are written.
pub fn check_option_combination(opts: GenerateOptions) -> Result<(), NewError> {
    // The API flavor and the daemon flavors are different app shapes with
    // conflicting `autumn-web` feature sets: `--api` drops the view stack
    // (maud/htmx/tailwind) for a pure-JSON app, while `--daemon`/`--bundled-pg`
    // keep it. Composing them would produce contradictory Cargo features, so
    // reject the combination rather than scaffolding an incoherent project.
    // (`--api` still composes with `--with-i18n` and `--with-seed`.)
    if opts.with_api && (opts.with_daemon || opts.with_bundled_pg) {
        return Err(NewError::IncompatibleOptions(
            "--api scaffolds a JSON-first app without the HTML/CSS view stack, so \
             it cannot be combined with --daemon or --bundled-pg (which scaffold \
             daemon apps that keep the view stack)"
                .to_owned(),
        ));
    }
    // The DB-free daemon starter builds with no database, so a seed binary
    // (which needs `autumn_web::seed::SeedContext` and the `db` feature) cannot
    // compile. Reject the combination rather than scaffolding a broken project.
    if opts.with_daemon && !opts.with_bundled_pg && opts.with_seed {
        return Err(NewError::IncompatibleOptions(
            "--daemon scaffolds a database-free app, so --with-seed is not \
             supported (seeding requires a database; use --bundled-pg for a \
             daemon with a managed Postgres)"
                .to_owned(),
        ));
    }
    // A managed-Postgres daemon owns its database URL at runtime (chosen by the
    // provider); the `autumn seed` CLI is a separate process that only reads
    // env/config URLs, so it can't reach the managed DB. Reject the combo.
    if opts.with_bundled_pg && opts.with_seed {
        return Err(NewError::IncompatibleOptions(
            "--bundled-pg manages Postgres inside the daemon, so the `autumn \
             seed` CLI cannot reach its database; --with-seed is not supported \
             with --bundled-pg. Seed from the app instead (e.g. a startup hook)."
                .to_owned(),
        ));
    }
    Ok(())
}

/// Generate a new Autumn project under `parent_dir/name`, honouring `opts`.
///
/// Prints a human-readable creation summary to stdout. Callers that need clean
/// stdout (e.g. machine-readable output) should use [`generate_with_quiet`].
pub fn generate_with(name: &str, parent_dir: &Path, opts: GenerateOptions) -> Result<(), NewError> {
    generate_inner(name, parent_dir, opts, false)
}

/// Like [`generate_with`] but suppresses the stdout creation summary.
///
/// Used by tooling that emits machine-readable output on stdout (e.g. the
/// cold-start benchmark with `--json`), where the scaffold summary would
/// otherwise corrupt the output stream.
pub fn generate_with_quiet(
    name: &str,
    parent_dir: &Path,
    opts: GenerateOptions,
) -> Result<(), NewError> {
    generate_inner(name, parent_dir, opts, true)
}

#[allow(clippy::too_many_lines)]
fn generate_inner(
    name: &str,
    parent_dir: &Path,
    opts: GenerateOptions,
    quiet: bool,
) -> Result<(), NewError> {
    validate_name(name)?;
    check_option_combination(opts)?;

    let project_dir = parent_dir.join(name);
    if project_dir.exists() {
        return Err(NewError::AlreadyExists(name.to_owned()));
    }

    let crate_name = name.replace('-', "_");
    let autumn_version = env!("CARGO_PKG_VERSION");
    let rust_version = crate::MSRV;

    fs::create_dir_all(project_dir.join("src"))?;
    // The JSON-first API flavor ships no CSS/JS assets, so it has no `static/`
    // tree; the fullstack scaffold seeds `static/css` + `static/js`.
    if !opts.with_api {
        fs::create_dir_all(project_dir.join("static/css"))?;
        fs::create_dir_all(project_dir.join("static/js"))?;
    }
    fs::create_dir_all(project_dir.join("migrations"))?;
    fs::create_dir_all(project_dir.join("tests"))?;
    fs::create_dir_all(project_dir.join("config/credentials"))?;
    fs::create_dir_all(project_dir.join(".github/workflows"))?;
    if opts.with_i18n {
        fs::create_dir_all(project_dir.join("i18n"))?;
    }

    let vars = TemplateVars {
        project_name: name,
        crate_name: &crate_name,
        autumn_version,
        rust_version,
    };
    let render = |template: &str| -> String { render_template(template, &vars) };

    let cargo_template = if opts.with_api {
        templates::CARGO_API_TOML
    } else {
        templates::CARGO_TOML
    };
    let cargo_toml = render_cargo_toml(
        opts,
        autumn_version,
        render(cargo_template),
        &render(templates::SEED_CARGO_TOML),
    );
    fs::write(project_dir.join("Cargo.toml"), cargo_toml)?;

    fs::write(
        project_dir.join("README.md"),
        render_readme(render(templates::README), opts, &vars),
    )?;

    // The dependency advisory policy the generated CI enforces (issue #1600).
    // Written here rather than through `framework_owned_files` because its
    // waiver list is the app author's to grow: a file the developer is *asked*
    // to edit would otherwise come back as a scaffold-reconciliation conflict
    // on every `autumn upgrade`, exactly like `Cargo.toml` would.
    fs::write(project_dir.join("deny.toml"), render(templates::DENY_TOML))?;

    // Linker remedy for the Windows PDB symbol limit (issue #2448). Written
    // here, not as a framework-owned file: the app author may extend it.
    fs::create_dir_all(project_dir.join(".cargo"))?;
    fs::write(
        project_dir.join(".cargo/config.toml"),
        templates::CARGO_CONFIG,
    )?;

    let main_template = if opts.with_api {
        templates::MAIN_API_RS
    } else {
        templates::MAIN_RS
    };
    let mut main_rs = match (opts.with_api, opts.with_i18n) {
        (true, true) => inject_i18n_api(&render(main_template)),
        (false, true) => inject_i18n(&render(main_template)),
        (_, false) => render(main_template),
    };
    if opts.with_bundled_pg {
        // Managed-Postgres daemon: keep migrations, install the pool provider.
        main_rs = inject_managed_pg(&main_rs);
    } else if opts.with_daemon {
        // DB-free daemon: the `migrate` module is db-gated, so drop migrations.
        main_rs = strip_migrations(&main_rs);
    }
    fs::write(project_dir.join("src/main.rs"), main_rs)?;

    // Every framework-owned file comes from one renderer, shared with `autumn
    // upgrade`'s scaffold reconciliation (issue #1593). Writing them from a
    // second, parallel code path here is how the two would silently disagree —
    // and a byte of disagreement reads to the reconciler as a permanent
    // conflict in every project ever generated.
    let owned = framework_owned_files(&vars, opts);
    for (relative, contents) in &owned {
        fs::write(project_dir.join(relative), contents)?;
    }
    // Record what this release wrote, so a later `autumn upgrade` can tell a
    // template that moved from a file the developer edited (issue #1593). Best
    // effort by design: the manifest only ever *sharpens* a later upgrade, and
    // failing a scaffold over bookkeeping would be a worse trade than losing
    // conflict precision.
    let _ = crate::upgrade::scaffold::Manifest::for_files(autumn_version, opts, &owned)
        .save(&project_dir);
    fs::write(project_dir.join("migrations/.gitkeep"), "")?;

    // The API flavor serves no HTML, so it needs no vendored htmx/SSE JS or the
    // static asset manifest — skip the whole `static/` vendoring step.
    if !opts.with_api {
        scaffold_vendor_assets(&project_dir)?;
    }
    scaffold_credentials(&project_dir, name)?;
    fs::write(
        project_dir.join("tests/integration_test.rs"),
        render(templates::INTEGRATION_TEST),
    )?;

    write_optional_scaffold_files(&project_dir, name, opts, &render)?;

    if !quiet {
        print_scaffold_summary(name, opts);
    }

    Ok(())
}

/// Every framework-owned file `autumn new` writes outside the application's own
/// source, rendered for `opts`.
///
/// This is the single definition of "what the current release's scaffold looks
/// like". [`generate_inner`] writes these files, and `autumn upgrade`'s
/// scaffold reconciliation (issue #1593) compares an existing project against
/// exactly the same rendering — so the two cannot drift apart, which is the one
/// bug that would make the reconciler report a conflict in every project on
/// earth.
///
/// # What is *not* here
///
/// The set is an allowlist, not "everything `autumn new` writes", and two
/// exclusions are load bearing:
///
/// - **`src/**`.** Application source is out of bounds for the reconciler
///   (issue #1593); `src/main.rs` and the optional seed binary are the app's,
///   not the framework's, the moment the project exists. Enforced by the
///   assertion below, not just by convention.
/// - **Files the framework generates but does not own thereafter**:
///   `Cargo.toml` (the app's dependencies), `README.md` (the app's prose),
///   `tests/`, `migrations/`, `i18n/`, `config/credentials/` (secrets), and the
///   vendored `static/js/` assets, which `autumn assets` — not this — keeps
///   current.
///
/// Keys are project-relative and always `/`-separated, so they are equally
/// valid as `Path` joins and as the keys of the provenance manifest on every
/// host.
#[must_use]
pub fn framework_owned_files(
    vars: &TemplateVars<'_>,
    opts: GenerateOptions,
) -> BTreeMap<&'static str, String> {
    let render = |template: &str| -> String { render_template(template, vars) };

    let mut autumn_toml = if opts.with_i18n {
        let mut s = render(templates::AUTUMN_TOML);
        s.push_str("\n[i18n]\ndefault_locale = \"en\"\nsupported_locales = [\"en\"]\n");
        s
    } else {
        render(templates::AUTUMN_TOML)
    };
    if opts.with_daemon && !opts.with_bundled_pg {
        autumn_toml.push_str(
            "\n# Daemon starter: this app uses no database. Run it as a local\n\
             # daemon with `autumn serve --daemon` (no Postgres required).\n",
        );
    }
    if opts.with_bundled_pg {
        // The managed cluster is private to this daemon and has no URL outside
        // the provider, so `autumn migrate` can't reach it and `--release` runs
        // under the `prod` profile (where migrations are otherwise only logged).
        // Apply embedded migrations automatically so a fresh release data dir
        // doesn't come up with missing tables.
        autumn_toml.push_str(
            "\n# Managed local Postgres (`autumn serve --bundled-pg`): the cluster is\n\
             # owned by the daemon, so apply embedded migrations automatically even\n\
             # under the production profile (a fresh data dir would otherwise start\n\
             # with no tables).\n\
             [database]\n\
             auto_migrate_in_production = true\n",
        );
    }

    let dockerfile = if opts.with_api {
        // The `--api` Dockerfile carries i18n `COPY` anchors resolved by flag:
        // ship the `i18n/` sidecar into the image for `--with-i18n`, or strip
        // the anchors so a non-i18n build context (which has no `i18n/` dir)
        // still builds.
        inject_i18n_dockerfile_api(&render(templates::DOCKERFILE_API), opts.with_i18n)
    } else {
        // The fullstack `Dockerfile.tmpl` carries the same i18n `COPY` anchors:
        // ship the `i18n/` sidecar into the image for `--with-i18n`, or strip
        // the anchors so a non-i18n build context (which has no `i18n/` dir)
        // still builds.
        inject_i18n_dockerfile(&render(templates::DOCKERFILE), opts.with_i18n)
    };

    let build_rs = if opts.with_api {
        render(templates::BUILD_API_RS)
    } else {
        render(templates::BUILD_RS)
    };

    let ci_yml = if opts.with_api {
        strip_ci_tailwind_note(&render(templates::CI_WORKFLOW))
    } else {
        render(templates::CI_WORKFLOW)
    };

    let mut files = BTreeMap::new();
    files.insert("autumn.toml", autumn_toml);
    files.insert("Dockerfile", dockerfile);
    files.insert(".dockerignore", render(templates::DOCKERIGNORE));
    files.insert("build.rs", build_rs);
    files.insert(".gitignore", render(templates::GITIGNORE));
    files.insert(".env.example", render(templates::ENV_EXAMPLE));
    files.insert(".github/workflows/ci.yml", ci_yml);
    // The security posture gate (issue #1624) is a separate workflow rather
    // than another job in `ci.yml`: it needs `pull-requests: write` to post the
    // diff, and that permission has no business on the job that runs the test
    // suite.
    files.insert(
        ".github/workflows/posture-gate.yml",
        render(templates::POSTURE_GATE_WORKFLOW),
    );
    files.insert("rust-toolchain.toml", render(templates::RUST_TOOLCHAIN));
    files.insert("rustfmt.toml", render(templates::RUSTFMT));
    files.insert("clippy.toml", render(templates::CLIPPY));
    // The API flavor has no Tailwind/CSS pipeline, so it owns no CSS input and
    // no Tailwind config (there is no `static/css` directory either).
    if !opts.with_api {
        files.insert("tailwind.config.js", render(templates::TAILWIND_CONFIG));
        files.insert("static/css/input.css", render(templates::INPUT_CSS));
    }

    debug_assert!(
        files.keys().all(|path| !path.starts_with("src/")),
        "application source is out of bounds for scaffold reconciliation"
    );
    files
}

/// Rewrite a rendered workflow for one workspace member.
///
/// `dir` is the member path from the git root, with `/` separators. `ci.yml`
/// runs in `dir`, so `cargo` selects the member. `posture-gate.yml` runs from
/// the git root, so it gets the member path and `-p <package>`.
///
/// Returns `None` for any other file. Returns `None` too if a value is not
/// plain, or if a template anchor is missing or not unique. The caller then
/// plans no file. A wrong workflow is worse than none.
#[must_use]
pub fn member_workflow(path: &str, rendered: &str, package: &str, dir: &str) -> Option<String> {
    let plain = |text: &str| {
        !text.is_empty()
            && text
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-' | '/'))
    };
    if !plain(package) || !plain(dir) {
        return None;
    }
    let swap = |text: &str, from: &str, to: &str| {
        (text.matches(from).count() == 1).then(|| text.replace(from, to))
    };
    match path {
        ".github/workflows/ci.yml" => {
            let with_dir = swap(
                rendered,
                "\njobs:\n",
                &format!(
                    "\n# Set by `autumn upgrade`: this app is a workspace member.\n\
                     defaults:\n  run:\n    # Quoted, so a name such as `null` stays a string.\n    working-directory: \"{dir}\"\n\njobs:\n"
                ),
            )?;
            swap(
                &with_dir,
                "cargo fmt --all -- --check",
                &format!("cargo fmt -p {package} -- --check"),
            )
        }
        ".github/workflows/posture-gate.yml" => {
            let with_manifest = swap(
                rendered,
                "POSTURE_MANIFEST: security-posture.json\n",
                &format!("POSTURE_MANIFEST: {dir}/security-posture.json\n"),
            )?;
            swap(
                &with_manifest,
                "POSTURE_AUDIT_FLAGS: --release\n",
                &format!("POSTURE_AUDIT_FLAGS: --release -p {package}\n"),
            )
        }
        _ => None,
    }
}

fn scaffold_vendor_assets(project_dir: &Path) -> Result<(), NewError> {
    let htmx_bytes = autumn_web::HTMX_JS;
    let htmx_version = autumn_web::HTMX_VERSION;
    let htmx_source =
        format!("https://cdn.jsdelivr.net/npm/htmx.org@{htmx_version}/dist/htmx.min.js");
    let htmx_file = "js/htmx.min.js";
    let integrity = crate::assets::compute_sri(htmx_bytes);

    fs::write(project_dir.join("static").join(htmx_file), htmx_bytes)?;

    let sse_bytes = autumn_web::HTMX_SSE_JS;
    let sse_source = "https://unpkg.com/htmx-ext-sse@2.2.2/sse.js".to_owned();
    let sse_file = "js/htmx-ext-sse.min.js";
    let sse_integrity = crate::assets::compute_sri(sse_bytes);

    fs::write(project_dir.join("static").join(sse_file), sse_bytes)?;

    let mut assets = std::collections::BTreeMap::new();
    assets.insert(
        "htmx".to_owned(),
        crate::assets::VendorAsset {
            version: htmx_version.to_owned(),
            source: htmx_source,
            file: htmx_file.to_owned(),
            integrity,
        },
    );
    assets.insert(
        "htmx-ext-sse".to_owned(),
        crate::assets::VendorAsset {
            version: "2.2.2".to_owned(),
            source: sse_source,
            file: sse_file.to_owned(),
            integrity: sse_integrity,
        },
    );
    let manifest = crate::assets::VendorManifest {
        version: "1".to_owned(),
        assets,
    };
    let manifest_path = project_dir.join("static").join(".autumn-assets.json");
    crate::assets::save_manifest(&manifest_path, &manifest)
        .map_err(|e| std::io::Error::other(e.to_string()))?;

    Ok(())
}

fn scaffold_credentials(project_dir: &Path, name: &str) -> Result<(), NewError> {
    let master_key = MasterKey::generate();
    let key_path = project_dir.join("config/master.key");

    if let Some(parent) = key_path.parent() {
        fs::create_dir_all(parent)?;
    }

    let mut options = fs::OpenOptions::new();
    options.write(true).create(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut f = options.open(&key_path)?;
    f.write_all(master_key.to_hex().as_bytes())?;

    let template = format!(
        "# Encrypted credentials for '{name}'\n\
         # Run `autumn credentials edit` to update these values.\n\
         # Do NOT commit config/master.key to version control.\n\
         \n\
         # stripe_secret_key = \"sk_live_...\"\n\
         # sendgrid_api_key = \"SG...\"\n\
         # s3_access_key_id = \"AKIA...\"\n"
    );
    let ciphertext = encrypt(&master_key, template.as_bytes());
    fs::write(
        project_dir.join("config/credentials/development.toml.enc"),
        ciphertext,
    )?;

    Ok(())
}

fn print_scaffold_summary(name: &str, opts: GenerateOptions) {
    println!("  Created {name}/");
    println!("  Created {name}/Cargo.toml");
    println!("  Created {name}/README.md");
    println!("  Created {name}/autumn.toml");
    println!("  Created {name}/Dockerfile");
    println!("  Created {name}/.dockerignore");
    println!("  Created {name}/build.rs");
    println!("  Created {name}/src/main.rs");
    if opts.with_seed {
        println!("  Created {name}/src/bin/seed.rs");
    }
    // The JSON-first API flavor ships no CSS/Tailwind pipeline.
    if !opts.with_api {
        println!("  Created {name}/static/css/input.css");
        println!("  Created {name}/tailwind.config.js");
    }
    println!("  Created {name}/.gitignore");
    println!("  Created {name}/.env.example");
    println!("  Created {name}/rust-toolchain.toml");
    println!("  Created {name}/rustfmt.toml");
    println!("  Created {name}/clippy.toml");
    // Named with its purpose attached: when the advisory gate first fires, a
    // developer who does not know this file exists reaches for disabling the CI
    // step instead of recording a waiver here.
    println!("  Created {name}/deny.toml (dependency advisory policy — CI audits against it)");
    println!("  Created {name}/migrations/");
    println!("  Created {name}/tests/integration_test.rs");
    println!("  Created {name}/config/master.key (keep secret — never commit)");
    println!("  Created {name}/config/credentials/development.toml.enc");
    // Named with its purpose attached: it is the only generated file whose
    // value depends entirely on being committed, and the only one a developer
    // would otherwise be tempted to gitignore as machine bookkeeping.
    println!("  Created {name}/.autumn/scaffold.toml (commit it — `autumn upgrade` reads it)");
    if opts.with_i18n {
        println!("  Created {name}/i18n/en.ftl");
    }
    println!();
    println!("Get started:");
    println!("  cd {name}");
    println!("  cargo run");
    println!();
    println!("Your app will be available at http://localhost:3000");
    if opts.with_i18n {
        println!();
        println!("i18n: edit i18n/en.ftl, add more locales as i18n/<tag>.ftl,");
        println!("      and use the t!() macro in handlers — see docs/guide/i18n.md.");
    }
    if opts.with_seed {
        println!();
        println!("Seed your database:");
        println!("  autumn migrate && autumn seed");
    }
}

/// Replace `from` with `to`, asserting the anchor exists first.
///
/// The scaffold generators below patch the generated `main.rs` by string
/// replacement against anchors in `main.rs.tmpl`. If the template and an anchor
/// drift out of sync, a plain `.replace()` silently no-ops and produces a
/// broken scaffold (this exact class of bug has bitten the mailer wiring once
/// already). Asserting the anchor turns that into a loud, test-caught failure.
fn replace_anchor(src: &str, from: &str, to: &str) -> String {
    assert!(
        src.contains(from),
        "scaffold template anchor not found: {from:?} — src/templates/main.rs.tmpl and the \
         inject_* helpers in new.rs have drifted out of sync"
    );
    src.replace(from, to)
}

/// Enable i18n in a generated `main.rs`: call `.i18n_auto()` and embed the
/// `i18n/` locale bundles alongside the static assets for single-binary deploys.
fn inject_i18n(main_rs: &str) -> String {
    let with_locale = replace_anchor(
        main_rs,
        "        .routes(routes![index, hello, hello_name, consent_accept, consent_reject, consent_manage])",
        "        .i18n_auto()\n        .routes(routes![index, hello, hello_name, consent_accept, consent_reject, consent_manage])",
    );
    let with_static = replace_anchor(
        &with_locale,
        "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();",
        "static EMBEDDED_STATIC: autumn_web::include_dir::Dir = autumn_web::embed_static!();\n\
         #[cfg(feature = \"embed-assets\")]\n\
         static EMBEDDED_LOCALES: autumn_web::include_dir::Dir = autumn_web::embed_locales!();",
    );
    replace_anchor(
        &with_static,
        "    let app = app.embedded_static(&EMBEDDED_STATIC);\n",
        "    let app = app.embedded_static(&EMBEDDED_STATIC);\n\
         \x20   #[cfg(feature = \"embed-assets\")]\n\
         \x20   let app = app.embedded_locales(&EMBEDDED_LOCALES);\n",
    )
}

/// i18n variant of [`inject_i18n`] for the JSON-first API scaffold's `main.rs`,
/// which has no HTML/static asset layer. Enables locale auto-detection with
/// `.i18n_auto()` and embeds the `i18n/` locale bundles into the binary (behind
/// the `embed-assets` feature) for single-binary deploys.
fn inject_i18n_api(main_rs: &str) -> String {
    let with_locale_call = replace_anchor(
        main_rs,
        "        .routes(routes![index, hello_name])",
        "        .i18n_auto()\n        .routes(routes![index, hello_name])",
    );
    let with_locales_static = replace_anchor(
        &with_locale_call,
        "const MIGRATIONS: EmbeddedMigrations = embed_migrations!();\n",
        "const MIGRATIONS: EmbeddedMigrations = embed_migrations!();\n\n\
         #[cfg(feature = \"embed-assets\")]\n\
         static EMBEDDED_LOCALES: autumn_web::include_dir::Dir = autumn_web::embed_locales!();\n",
    );
    replace_anchor(
        &with_locales_static,
        "        .migrations(MIGRATIONS);\n\n    app\n",
        "        .migrations(MIGRATIONS);\n\n\
         \x20   #[cfg(feature = \"embed-assets\")]\n\
         \x20   let app = app.embedded_locales(&EMBEDDED_LOCALES);\n\n    app\n",
    )
}

/// Anchor: the builder-stage i18n `COPY` insertion point in
/// `Dockerfile.api.tmpl` (an otherwise-inert comment line). Replaced with a
/// `COPY i18n ./i18n` line for `--api --with-i18n`, or stripped entirely
/// otherwise so a non-i18n project's build context has no missing `i18n/` dir.
const DOCKERFILE_API_I18N_BUILDER_ANCHOR: &str = "# __AUTUMN_I18N_BUILDER_COPY__\n";
/// Anchor: the runtime-stage i18n `COPY` insertion point in
/// `Dockerfile.api.tmpl`. Replaced with a `COPY --from=builder /app/i18n
/// /app/i18n` line for `--api --with-i18n`, or stripped otherwise.
const DOCKERFILE_API_I18N_RUNTIME_ANCHOR: &str = "# __AUTUMN_I18N_RUNTIME_COPY__\n";

/// Resolve the two i18n `COPY` anchors in the rendered `--api` Dockerfile.
///
/// The `--api` scaffold's `main.rs` calls `.i18n_auto()` when `--with-i18n`,
/// which loads `i18n/en.ftl` from disk at startup and panics if it is missing.
/// The API image must therefore ship the `i18n/` sidecar into both the builder
/// (so `cargo build` sees it for any embed) and the runtime stage (so the
/// running binary can read it). The `COPY` lines are gated on `with_i18n`: an
/// unconditional `COPY i18n ./i18n` would break `docker build` for non-i18n
/// projects, whose build context has no `i18n/` directory. When `with_i18n` is
/// false the anchors are stripped, leaving the Dockerfile byte-for-byte as it
/// was before this wiring (no leftover anchor markers).
fn inject_i18n_dockerfile_api(dockerfile: &str, with_i18n: bool) -> String {
    if with_i18n {
        let with_builder = replace_anchor(
            dockerfile,
            DOCKERFILE_API_I18N_BUILDER_ANCHOR,
            "COPY i18n ./i18n\n",
        );
        replace_anchor(
            &with_builder,
            DOCKERFILE_API_I18N_RUNTIME_ANCHOR,
            "COPY --from=builder /app/i18n /app/i18n\n",
        )
    } else {
        let no_builder = replace_anchor(dockerfile, DOCKERFILE_API_I18N_BUILDER_ANCHOR, "");
        replace_anchor(&no_builder, DOCKERFILE_API_I18N_RUNTIME_ANCHOR, "")
    }
}

/// Anchor: the builder-stage i18n `COPY` insertion point in the fullstack
/// `Dockerfile.tmpl` (an otherwise-inert comment line). Replaced with a
/// `COPY i18n ./i18n` line for `--with-i18n`, or stripped entirely otherwise so
/// a non-i18n project's build context has no missing `i18n/` dir.
const DOCKERFILE_I18N_BUILDER_ANCHOR: &str = "# __AUTUMN_I18N_BUILDER_COPY__\n";
/// Anchor: the runtime-stage i18n `COPY` insertion point in the fullstack
/// `Dockerfile.tmpl`. Replaced with a `COPY --from=builder /app/i18n /app/i18n`
/// line for `--with-i18n`, or stripped otherwise.
const DOCKERFILE_I18N_RUNTIME_ANCHOR: &str = "# __AUTUMN_I18N_RUNTIME_COPY__\n";

/// Resolve the two i18n `COPY` anchors in the rendered fullstack Dockerfile.
///
/// The default (fullstack) scaffold's `main.rs` calls `.i18n_auto()` when
/// `--with-i18n`, which loads `i18n/en.ftl` from disk at startup and panics if
/// it is missing. The image must therefore ship the `i18n/` sidecar into both
/// the builder (so `cargo build` sees it for any embed) and the runtime stage
/// (so the running binary can read it). The `COPY` lines are gated on
/// `with_i18n`: an unconditional `COPY i18n ./i18n` would break `docker build`
/// for non-i18n projects, whose build context has no `i18n/` directory. When
/// `with_i18n` is false the anchors are stripped, leaving the Dockerfile
/// byte-for-byte as it was before this wiring (no leftover anchor markers).
/// Mirrors [`inject_i18n_dockerfile_api`] for the `--api` scaffold.
fn inject_i18n_dockerfile(dockerfile: &str, with_i18n: bool) -> String {
    if with_i18n {
        let with_builder = replace_anchor(
            dockerfile,
            DOCKERFILE_I18N_BUILDER_ANCHOR,
            "COPY i18n ./i18n\n",
        );
        replace_anchor(
            &with_builder,
            DOCKERFILE_I18N_RUNTIME_ANCHOR,
            "COPY --from=builder /app/i18n /app/i18n\n",
        )
    } else {
        let no_builder = replace_anchor(dockerfile, DOCKERFILE_I18N_BUILDER_ANCHOR, "");
        replace_anchor(&no_builder, DOCKERFILE_I18N_RUNTIME_ANCHOR, "")
    }
}

/// Anchor: the Tailwind CI extension note in `ci.yml.tmpl`. The JSON-first API
/// scaffold has no Tailwind/CSS step, so this note is stripped for `--api` (it
/// is also the only `tailwind` mention in the generated tree).
const CI_TAILWIND_NOTE: &str = "#   - Tailwind: add `autumn setup --tailwind` and run the downloaded binary\n\
     #     before `cargo build` to compile CSS in CI.\n";

/// Remove the Tailwind CI extension note from a rendered `ci.yml` for the API
/// scaffold (which ships no CSS pipeline).
fn strip_ci_tailwind_note(ci_yml: &str) -> String {
    replace_anchor(ci_yml, CI_TAILWIND_NOTE, "")
}

/// Inject a managed-Postgres pool provider plus a shutdown hook into a
/// generated `main.rs` so the bundled cluster is supervised by the daemon.
fn inject_managed_pg(main_rs: &str) -> String {
    replace_anchor(
        main_rs,
        "    let app = autumn_web::app()\n",
        "    let pg = autumn_web::managed_pg::ManagedPostgresPoolProvider::new();\n\
         \x20   let pg_shutdown = pg.clone();\n\
         \x20   let app = autumn_web::app()\n\
         \x20       .with_pool_provider(pg)\n\
         \x20       .on_shutdown(move || {\n\
         \x20           let pg = pg_shutdown.clone();\n\
         \x20           async move {\n\
         \x20               pg.stop().await;\n\
         \x20           }\n\
         \x20       })\n",
    )
}

/// Remove the diesel-migrations wiring from a generated `main.rs` so a DB-free
/// app compiles without the db-gated `migrate` module.
fn strip_migrations(main_rs: &str) -> String {
    let no_use = replace_anchor(
        main_rs,
        "use autumn_web::migrate::{EmbeddedMigrations, embed_migrations};\n",
        "",
    );
    let no_const = replace_anchor(
        &no_use,
        "const MIGRATIONS: EmbeddedMigrations = embed_migrations!();\n\n",
        "",
    );
    replace_anchor(&no_const, "\n        .migrations(MIGRATIONS)", "")
}

/// The DB-free daemon feature set (issue #2309): default `autumn-web`
/// features minus `db`, `cache-moka`, and `http-client`.
///
/// The daemon starter has no cache. It makes no outbound HTTP call (no auth,
/// no webhooks). `cache-moka` and `http-client` are unused for it. Both are
/// dropped here, not just `db`. Dropping `http-client` also drops `reqwest`
/// and its TLS stack from the build.
///
/// `reporting` stays on. It adds no extra dependency, and it drives the
/// panic-catch middleware every app should keep by default.
const DAEMON_NO_DB_FEATURES: &[&str] = &["maud", "htmx", "tailwind", "reporting"];

/// Default `autumn-web` features minus the HTML view stack (`maud`/`htmx`/
/// `tailwind`) — the JSON-first API (`--api`) feature set. Keeps `db` and its
/// `postgres` backend so migrations and database features still work.
const API_FEATURES: &[&str] = &[
    "db",
    "postgres",
    "cache-moka",
    "http-client",
    "reporting",
    "flash",
];

/// Anchor: first line of the DB-specific prerequisites/steps block in
/// `README.md.tmpl` (the `- **A reachable Postgres**` bullet). Everything from
/// here up to [`README_TAIL_ANCHOR`] is the default DB-first golden path and is
/// swapped out for daemon / bundled-Postgres app shapes.
const README_DB_BODY_ANCHOR: &str = "- **A reachable Postgres**";
/// Anchor: start of the shared CLI-reference tail in `README.md.tmpl`.
const README_TAIL_ANCHOR: &str = "## CLI reference";
/// The CLI-reference row documenting `autumn migrate`, stripped from the daemon
/// / bundled-Postgres READMEs (a DB-free daemon has no migrations to apply, and
/// a bundled-Postgres daemon applies them automatically inside the process).
const README_MIGRATE_ROW: &str = "| `autumn migrate` | Apply pending database migrations. |\n";
/// The CLI-reference row documenting `autumn generate scaffold`, stripped from
/// the **DB-free daemon** README only. `generate scaffold` emits Diesel
/// models/repositories/migrations and re-enables `db-diesel2-postgres`, so the
/// code it produces cannot compile in a `--daemon` scaffold (which disables the
/// `db` feature). The bundled-Postgres shape keeps the `db` feature, so the verb
/// stays valid there and this row is retained.
const README_SCAFFOLD_ROW: &str = "| `autumn generate scaffold <Name> field:Type …` | Scaffold a CRUD resource — model, migration, routes, and views. |\n";
/// The project-layout row documenting the `migrations/` directory, stripped from
/// the DB-free daemon README (that scaffold has no migrations directory).
const README_MIGRATIONS_LAYOUT_ROW: &str =
    "| `migrations/` | Diesel migrations — one directory per migration. |\n";
/// Anchor: the Tailwind binary prerequisite bullet in `README.md.tmpl`. The
/// JSON-first API scaffold has no CSS pipeline, so this bullet is removed for
/// `--api` (it is the only `tailwind` mention in the generated README).
const README_TAILWIND_PREREQ: &str =
    "- **The Tailwind binary** (downloaded by `autumn setup`):\n  ```sh\n  autumn setup\n  ```\n";
/// Anchor: the `static/` project-layout row in `README.md.tmpl`. The API
/// scaffold ships no `static/` directory, so the row is removed for `--api`.
const README_STATIC_LAYOUT_ROW: &str = "| `static/` | Static assets served under `/static/`. |\n";

/// Render the project README, tailoring the golden path to the app shape and
/// appending flag-specific sections.
///
/// The template body is the default **DB-first** golden path (configure
/// `[database]`, `autumn migrate`, `autumn dev`). For the daemon app shapes the
/// DB-bootstrap block is swapped for prose that matches what the scaffold
/// actually produces:
///
/// * `--daemon` builds with **no** database (the `db` feature is off and
///   migrations are stripped), so it must not tell users to install `libpq`,
///   configure Postgres, or run `autumn migrate` — it runs via `autumn serve`.
/// * `--bundled-pg` embeds and manages its own Postgres, so there is no external
///   server to configure and migrations apply automatically — it runs via
///   `autumn serve --bundled-pg`.
///
/// `render_template` only substitutes the four fixed `{{…}}` tokens, so the
/// flag-aware quickstart notes are built here in Rust rather than gated inside
/// the template. Text produced here must not introduce any new `{{…}}` token —
/// `no_unsubstituted_placeholders` walks the generated tree and would flag it
/// (crate/project names are interpolated from `vars`, not left as tokens).
fn render_readme(rendered: String, opts: GenerateOptions, vars: &TemplateVars<'_>) -> String {
    // The JSON-first API scaffold shares the DB-first golden path (it keeps
    // `db`/migrations) but has no Tailwind/CSS pipeline and no `static/` tree,
    // so strip the Tailwind prerequisite and the `static/` layout row.
    if opts.with_api {
        let mut readme = rendered.replace(README_TAILWIND_PREREQ, "");
        readme = readme.replace(README_STATIC_LAYOUT_ROW, "");
        append_optional_readme_sections(&mut readme, opts);
        return readme;
    }
    // `--bundled-pg` implies `with_daemon`, so test it first.
    let mut readme = if opts.with_bundled_pg {
        // Bundled Postgres keeps the `db` feature, so `generate scaffold` and the
        // `migrations/` layout stay valid — only the hand-run `migrate` row goes.
        rewrite_readme_body(&rendered, &bundled_pg_readme_body(vars), false)
    } else if opts.with_daemon {
        // Pure DB-free daemon: also strip the DB-coupled CLI/layout rows.
        rewrite_readme_body(&rendered, &daemon_readme_body(vars), true)
    } else {
        rendered
    };
    append_optional_readme_sections(&mut readme, opts);
    readme
}

/// Append the `--with-i18n` and `--with-seed` README sections when those flags
/// are set. Shared by every app shape (fullstack, daemon, and `--api`) so the
/// flag-specific guidance is identical regardless of the golden-path body.
fn append_optional_readme_sections(readme: &mut String, opts: GenerateOptions) {
    if opts.with_i18n {
        readme.push_str(
            "\n## Internationalization (i18n)\n\
             \n\
             This project was generated with `--with-i18n`. Fluent translations\n\
             live in `i18n/en.ftl`; add more locales by dropping additional files\n\
             like `i18n/es.ftl`. Reach translations from your handlers by taking a\n\
             `Locale` extractor and passing it to the `t!()` macro — e.g.\n\
             `t!(locale, \"welcome.title\")` — and use the `[i18n]` block in\n\
             `autumn.toml` to set the default and supported locales. See\n\
             `docs/guide/i18n.md` for the full guide.\n",
        );
    }
    if opts.with_seed {
        readme.push_str(
            "\n## Seed data\n\
             \n\
             This project was generated with `--with-seed`. Edit `src/bin/seed.rs`\n\
             to insert representative data, then seed the database (after applying\n\
             migrations):\n\
             \n\
             ```sh\n\
             autumn migrate && autumn seed\n\
             ```\n",
        );
    }
}

/// Replace the default DB-first golden-path block (from
/// [`README_DB_BODY_ANCHOR`] up to [`README_TAIL_ANCHOR`]) with `new_body`, then
/// drop the CLI-reference `autumn migrate` row — neither daemon shape runs it by
/// hand. `new_body` supplies the app-shape-specific prerequisites and run steps.
///
/// When `db_free` is set (the pure `--daemon` shape, which disables the `db`
/// feature), the DB-coupled CLI/layout rows are stripped too: `generate scaffold`
/// (it emits Diesel code that needs the disabled `db` feature) and the
/// `migrations/` layout row (no migrations directory exists). The
/// bundled-Postgres shape keeps `db`, so it passes `db_free = false` and retains
/// those rows.
fn rewrite_readme_body(rendered: &str, new_body: &str, db_free: bool) -> String {
    let start = rendered.find(README_DB_BODY_ANCHOR).unwrap_or_else(|| {
        panic!(
            "README.md.tmpl anchor not found: {README_DB_BODY_ANCHOR:?} — the template and \
             render_readme have drifted out of sync"
        )
    });
    let tail = rendered.find(README_TAIL_ANCHOR).unwrap_or_else(|| {
        panic!(
            "README.md.tmpl anchor not found: {README_TAIL_ANCHOR:?} — the template and \
             render_readme have drifted out of sync"
        )
    });
    let spliced = format!("{}{}{}", &rendered[..start], new_body, &rendered[tail..]);
    // The daemon shapes have no hand-run migration step; drop the reference row
    // so the CLI table stays consistent with the golden path above it.
    let mut out = spliced.replace(README_MIGRATE_ROW, "");
    if db_free {
        // The DB-free daemon disables the `db` feature, so `generate scaffold`
        // would emit code that cannot compile, and there is no `migrations/`
        // directory. Drop both rows so the reference matches what actually works.
        out = out.replace(README_SCAFFOLD_ROW, "");
        out = out.replace(README_MIGRATIONS_LAYOUT_ROW, "");
    }
    out
}

/// DB-free daemon (`--daemon`) golden-path body: no Postgres, no `libpq`, no
/// migrations — the app runs via `autumn serve`.
fn daemon_readme_body(vars: &TemplateVars<'_>) -> String {
    format!(
        "\n### 2. Run the server\n\
         \n\
         This project was generated with `--daemon`: it builds with **no** database — the\n\
         `db` feature is off and there are no migrations — so there is no Postgres to\n\
         install, no database client library to link, and nothing in `autumn.toml` to\n\
         configure. Run it locally with:\n\
         \n\
         ```sh\n\
         autumn dev\n\
         ```\n\
         \n\
         Then visit **http://localhost:3000** — you should get a `200` with\n\
         \"Welcome to {project}!\". Health endpoints are auto-mounted at `/health`\n\
         and `/actuator/health`.\n\
         \n\
         For production, `autumn serve --daemon` supervises it in the background as a\n\
         managed daemon (`autumn serve status`, `autumn serve stop`, and `autumn serve\n\
         restart` manage the process). Unlike `autumn dev`, the daemon binds a private\n\
         **Unix domain socket**, not a TCP port — so it is *not* reachable at\n\
         `http://localhost:3000`. Run `autumn serve status` to print its socket address;\n\
         see `docs/guide/daemon.md` for the socket transport and lifecycle details.\n\
         \n\
         Need a database later? Re-enable `autumn-web`'s default features (turn the\n\
         `db` feature back on) in `Cargo.toml` to unlock the database-backed\n\
         workflow — migrations and CRUD scaffolding — that the default (non-daemon)\n\
         starter documents.\n\
         \n\
         ",
        project = vars.project_name,
    )
}

/// Bundled/managed-Postgres daemon (`--bundled-pg`) golden-path body: the app
/// owns its Postgres and auto-applies migrations, so there is no external server
/// to configure — it runs via `autumn serve --bundled-pg`. It keeps the `db`
/// feature, so `libpq` is still linked at build time.
fn bundled_pg_readme_body(vars: &TemplateVars<'_>) -> String {
    format!(
        "- **The PostgreSQL client library (`libpq`).** This starter keeps the `db`\n\
         \x20 feature, so the binary links `libpq` at build time — install it with your\n\
         \x20 package manager (e.g. `libpq-dev` on Debian/Ubuntu, `libpq` via Homebrew on\n\
         \x20 macOS).\n\
         \n\
         ### 2. Run the server\n\
         \n\
         This project was generated with `--bundled-pg`: it embeds and manages its own\n\
         Postgres. You do **not** install a server, edit the `[database]` block, or run\n\
         migrations by hand — the app provisions the cluster on startup and applies the\n\
         embedded migrations automatically (see the `[database]` note in `autumn.toml`).\n\
         Run it locally with:\n\
         \n\
         ```sh\n\
         autumn dev\n\
         ```\n\
         \n\
         Then visit **http://localhost:3000** — you should get a `200` with\n\
         \"Welcome to {project}!\". Health endpoints are auto-mounted at `/health`\n\
         and `/actuator/health`.\n\
         \n\
         For production, `autumn serve --bundled-pg` supervises the app and its managed\n\
         Postgres in the background as a daemon (`autumn serve status`, `autumn serve stop`,\n\
         and `autumn serve restart` manage the process). Unlike `autumn dev`, the daemon\n\
         binds a private **Unix domain socket**, not a TCP port — so it is *not* reachable\n\
         at `http://localhost:3000`. Run `autumn serve status` to print its socket address;\n\
         see `docs/guide/daemon.md` for the socket transport, lifecycle, and bundled-Postgres\n\
         details.\n\
         \n\
         ",
        project = vars.project_name,
    )
}

fn render_cargo_toml(
    opts: GenerateOptions,
    autumn_version: &str,
    mut cargo_toml: String,
    seed_bin_toml: &str,
) -> String {
    use std::fmt::Write;

    // JSON-first API starter: drop the HTML view stack (maud/htmx/tailwind) by
    // switching off default features and pinning the lean API feature set. The
    // API `Cargo.toml` template ships a plain `autumn-web = "…"` dep (no `maud`
    // line), so rewrite it to the explicit `default-features = false` table.
    if opts.with_api {
        let plain_dep = format!(r#"autumn-web = "{autumn_version}""#);
        let mut features: Vec<&str> = API_FEATURES.to_vec();
        if opts.with_i18n {
            features.push("i18n");
        }
        if opts.with_seed {
            features.push("seed");
        }
        let features_str = features
            .iter()
            .map(|f| format!(r#""{f}""#))
            .collect::<Vec<_>>()
            .join(", ");
        let dep = format!(
            r#"autumn-web = {{ version = "{autumn_version}", default-features = false, features = [{features_str}] }}"#
        );
        cargo_toml = cargo_toml.replace(&plain_dep, &dep);
        if opts.with_seed {
            cargo_toml.push('\n');
            cargo_toml.push_str(seed_bin_toml);
        }
        return cargo_toml;
    }

    // DB-free daemon starter: switch off default features (drops `db`) so the
    // binary links no Postgres, and remove the diesel migrations dependency.
    if opts.with_daemon && !opts.with_bundled_pg {
        let plain_dep = format!(r#"autumn-web = "{autumn_version}""#);
        let mut features: Vec<&str> = DAEMON_NO_DB_FEATURES.to_vec();
        if opts.with_i18n {
            features.push("i18n");
        }
        let features_str = features
            .iter()
            .map(|f| format!(r#""{f}""#))
            .collect::<Vec<_>>()
            .join(", ");
        let dep = format!(
            r#"autumn-web = {{ version = "{autumn_version}", default-features = false, features = [{features_str}] }}"#
        );
        cargo_toml = cargo_toml.replace(&plain_dep, &dep);
        cargo_toml = cargo_toml.replace("diesel_migrations = \"2\"\n", "");
        return cargo_toml;
    }

    let mut features = Vec::new();
    if opts.with_bundled_pg {
        // Single-binary mode: embed Postgres in the executable.
        features.push("managed-pg-bundled");
    }
    if opts.with_i18n {
        features.push("i18n");
    }
    if opts.with_seed {
        features.push("seed");
    }
    if !features.is_empty() {
        let plain_dep = format!(r#"autumn-web = "{autumn_version}""#);
        // âš¡ Bolt optimization: Pre-allocate capacity for comma-separated feature strings
        let mut features_str = String::with_capacity(features.len() * 10);
        for (i, feature) in features.iter().enumerate() {
            if i > 0 {
                features_str.push_str(", ");
            }
            write!(features_str, r#""{feature}""#).unwrap();
        }
        let feature_dep = format!(
            r#"autumn-web = {{ version = "{autumn_version}", features = [{features_str}] }}"#
        );
        cargo_toml = cargo_toml.replace(&plain_dep, &feature_dep);
    }
    if opts.with_seed {
        cargo_toml.push('\n');
        cargo_toml.push_str(seed_bin_toml);
    }
    cargo_toml
}

fn write_optional_scaffold_files(
    project_dir: &Path,
    name: &str,
    opts: GenerateOptions,
    render: &impl Fn(&str) -> String,
) -> Result<(), NewError> {
    if opts.with_i18n {
        fs::write(
            project_dir.join("i18n/en.ftl"),
            "# Default-locale translations for {{project_name}}.\n\
             # Add more locales by dropping additional files like `i18n/es.ftl`.\n\
             welcome.title = Welcome to Autumn!\n\
             welcome.greeting = Hello, { $name }!\n"
                .replace("{{project_name}}", name),
        )?;
    }

    if opts.with_seed {
        fs::create_dir_all(project_dir.join("src/bin"))?;
        fs::write(
            project_dir.join("src/bin/seed.rs"),
            render(templates::SEED_RS),
        )?;
    }

    Ok(())
}

/// Rust keywords that would be invalid crate names.
const KEYWORDS: &[&str] = &[
    "Self", "abstract", "as", "async", "await", "become", "box", "break", "const", "continue",
    "crate", "do", "dyn", "else", "enum", "extern", "false", "final", "fn", "for", "if", "impl",
    "in", "let", "loop", "macro", "match", "mod", "move", "mut", "override", "priv", "pub", "ref",
    "return", "self", "static", "struct", "super", "trait", "true", "try", "type", "typeof",
    "unsafe", "unsized", "use", "virtual", "where", "while", "yield",
];

/// Validate that a name is a valid Rust package name.
pub fn validate_name(name: &str) -> Result<(), NewError> {
    if name.is_empty() {
        return Err(NewError::InvalidName(
            name.to_owned(),
            "name cannot be empty".into(),
        ));
    }

    let first = name.chars().next().expect("checked non-empty");
    if !first.is_ascii_alphabetic() {
        return Err(NewError::InvalidName(
            name.to_owned(),
            "must start with a letter".into(),
        ));
    }

    if let Some(bad) = name
        .chars()
        .find(|c| !c.is_ascii_alphanumeric() && *c != '-' && *c != '_')
    {
        return Err(NewError::InvalidName(
            name.to_owned(),
            format!("contains invalid character '{bad}'"),
        ));
    }

    if KEYWORDS.contains(&name) {
        return Err(NewError::InvalidName(
            name.to_owned(),
            format!("'{name}' is a Rust keyword"),
        ));
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn valid_name_simple() {
        assert!(validate_name("myapp").is_ok());
    }

    #[test]
    fn valid_name_with_hyphens() {
        assert!(validate_name("my-app").is_ok());
    }

    #[test]
    fn valid_name_with_underscores() {
        assert!(validate_name("my_app").is_ok());
    }

    #[test]
    fn valid_name_with_digits() {
        assert!(validate_name("app2").is_ok());
    }

    #[test]
    fn empty_name_rejected() {
        let err = validate_name("").unwrap_err();
        assert!(err.to_string().contains("empty"));
    }

    #[test]
    fn starts_with_digit_rejected() {
        let err = validate_name("3app").unwrap_err();
        assert!(err.to_string().contains("start with a letter"));
    }

    #[test]
    fn starts_with_hyphen_rejected() {
        let err = validate_name("-app").unwrap_err();
        assert!(err.to_string().contains("start with a letter"));
    }

    #[test]
    fn special_chars_rejected() {
        let err = validate_name("my app!").unwrap_err();
        assert!(err.to_string().contains("invalid character"));
    }

    #[test]
    fn keyword_rejected() {
        let err = validate_name("fn").unwrap_err();
        assert!(err.to_string().contains("keyword"));
    }

    #[test]
    fn keyword_async_rejected() {
        let err = validate_name("async").unwrap_err();
        assert!(err.to_string().contains("keyword"));
    }

    #[test]
    fn generates_all_expected_files() {
        let tmp = TempDir::new().unwrap();
        generate("test-app", tmp.path()).unwrap();

        let p = tmp.path().join("test-app");
        assert!(p.join("Cargo.toml").is_file());
        assert!(p.join("README.md").is_file());
        assert!(p.join("src/main.rs").is_file());
        assert!(p.join("autumn.toml").is_file());
        assert!(p.join("Dockerfile").is_file());
        assert!(p.join(".dockerignore").is_file());
        let dockerignore = std::fs::read_to_string(p.join(".dockerignore")).unwrap();
        assert!(
            dockerignore.contains("/config/master.key")
                || dockerignore.contains("config/master.key"),
            ".dockerignore must exclude config/master.key: {dockerignore}"
        );
        assert!(p.join("build.rs").is_file());
        assert!(p.join(".gitignore").is_file());
        assert!(p.join(".env.example").is_file());
        assert!(p.join("static/css/input.css").is_file());
        assert!(p.join("tailwind.config.js").is_file());
        assert!(p.join("migrations/.gitkeep").is_file());
        assert!(!p.join("src/lib.rs").exists());
        assert!(!p.join("src/client.rs").exists());
    }

    // `autumn new` must generate a tests/ directory with a smoke test.
    #[test]
    fn generates_tests_directory_with_smoke_test() {
        let tmp = TempDir::new().unwrap();
        generate("smoke-test-app", tmp.path()).unwrap();
        let p = tmp.path().join("smoke-test-app");
        assert!(
            p.join("tests").is_dir(),
            "`autumn new` should create a tests/ directory"
        );
        assert!(
            p.join("tests/integration_test.rs").is_file(),
            "`autumn new` should generate tests/integration_test.rs"
        );
    }

    // `autumn new` must scaffold a working cookie-consent banner (issue
    // #1214): a policy-version constant the app owner can bump to re-prompt,
    // the auto-injecting middleware wired into the app, and the accept/reject
    // routes it posts to.
    #[test]
    fn generates_consent_banner_wiring_in_main_rs() {
        let tmp = TempDir::new().unwrap();
        generate("consent-app", tmp.path()).unwrap();
        let main_rs = fs::read_to_string(tmp.path().join("consent-app/src/main.rs")).unwrap();
        assert!(
            main_rs.contains("CONSENT_POLICY_VERSION"),
            "generated main.rs must declare a bump-to-reprompt policy version constant: {main_rs}"
        );
        assert!(
            main_rs.contains("autumn_web::consent::inject_consent_banner"),
            "generated main.rs must wire the consent-banner middleware: {main_rs}"
        );
        assert!(
            main_rs.contains("consent_accept") && main_rs.contains("consent_reject"),
            "generated main.rs must define consent_accept/consent_reject routes: {main_rs}"
        );
        assert!(
            main_rs.contains("\"/consent/accept\"") && main_rs.contains("\"/consent/reject\""),
            "generated main.rs must mount the accept/reject routes at their documented paths: {main_rs}"
        );
        assert!(
            main_rs.contains(
                "routes![index, hello, hello_name, consent_accept, consent_reject, consent_manage]"
            ),
            "the new consent routes must be registered alongside the existing routes: {main_rs}"
        );
        assert!(
            main_rs.contains("\"/consent/manage\"")
                && main_rs.contains("autumn_web::consent::consent_banner_markup"),
            "generated main.rs must scaffold a preferences route reusing the consent-banner \
             widget (GDPR Art. 7(3): withdrawing consent must be as easy as giving it): {main_rs}"
        );
        assert!(
            main_rs.contains("href=\"/consent/manage\""),
            "the shared layout's footer must link to the withdrawal route so it's \
             reachable from every page: {main_rs}"
        );
        assert!(
            main_rs.contains("autumn_web::consent::DEFAULT_CSRF_COOKIE_NAME"),
            "the middleware wiring must pass the CSRF cookie name explicitly: {main_rs}"
        );
        assert!(
            main_rs.contains("autumn_web::consent::DEFAULT_CSRF_FORM_FIELD"),
            "the middleware wiring must pass the CSRF form-field name explicitly: {main_rs}"
        );
    }

    // `/consent/manage` must stay a side-effect-free `GET`: it renders the
    // consent-banner widget so the visitor can make a new choice, but the
    // actual state change goes through the existing CSRF-protected
    // `POST /consent/accept` / `POST /consent/reject` handlers. If the GET
    // handler itself mutated the consent cookie (e.g. by calling
    // `expire_consent_cookie` directly), a same-origin prefetcher, browser
    // extension, or cross-site top-level navigation following the footer
    // link could silently reset a visitor's consent, since `GET` is
    // CSRF-exempt by definition.
    #[test]
    fn consent_manage_route_does_not_mutate_state_on_get() {
        let tmp = TempDir::new().unwrap();
        generate("consent-manage-app", tmp.path()).unwrap();
        let main_rs =
            fs::read_to_string(tmp.path().join("consent-manage-app/src/main.rs")).unwrap();
        let start = main_rs
            .find("async fn consent_manage")
            .expect("consent_manage handler must exist");
        let body = &main_rs[start..];
        let end = body[1..]
            .find("\n#[")
            .map_or(body.len(), |offset| offset + 1);
        let handler_body = &body[..end];
        assert!(
            !handler_body.contains("expire_consent_cookie") && !handler_body.contains("SET_COOKIE"),
            "the GET /consent/manage handler must not itself set or expire any cookie: {handler_body}"
        );
    }

    // The JSON-first `--api` flavor has no HTML/layout to show a banner in —
    // it must not scaffold the consent-banner wiring at all.
    #[test]
    fn api_flavor_does_not_scaffold_consent_banner() {
        let tmp = TempDir::new().unwrap();
        generate_with(
            "consent-api-app",
            tmp.path(),
            GenerateOptions {
                with_api: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();
        let main_rs = fs::read_to_string(tmp.path().join("consent-api-app/src/main.rs")).unwrap();
        assert!(
            !main_rs.contains("inject_consent_banner"),
            "the --api flavor ships no HTML layout, so it must not scaffold the banner: {main_rs}"
        );
    }

    // The generated `--with-i18n` main.rs must still compile-shape correctly:
    // the i18n injection anchors must stay in sync with the new routes! list
    // (see `inject_i18n`'s anchor constant).
    #[test]
    fn with_i18n_still_wires_consent_routes() {
        let tmp = TempDir::new().unwrap();
        generate_with(
            "consent-i18n-app",
            tmp.path(),
            GenerateOptions {
                with_i18n: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();
        let main_rs = fs::read_to_string(tmp.path().join("consent-i18n-app/src/main.rs")).unwrap();
        assert!(
            main_rs.contains(
                "routes![index, hello, hello_name, consent_accept, consent_reject, consent_manage]"
            ),
            "i18n injection must not drop the consent routes from the routes! list: {main_rs}"
        );
        assert!(main_rs.contains("i18n_auto"));
    }

    // The generated Cargo.toml must have [dev-dependencies] with tokio
    // so that #[tokio::test] compiles without the user adding anything.
    #[test]
    fn generated_cargo_toml_has_dev_deps_for_testing() {
        let tmp = TempDir::new().unwrap();
        generate("dev-dep-app", tmp.path()).unwrap();
        let content = fs::read_to_string(tmp.path().join("dev-dep-app/Cargo.toml")).unwrap();
        assert!(
            content.contains("[dev-dependencies]"),
            "generated Cargo.toml must have [dev-dependencies]"
        );
        assert!(
            content.contains("tokio"),
            "generated Cargo.toml must include tokio in dev-dependencies for #[tokio::test]"
        );
    }

    #[test]
    fn cargo_toml_has_project_name() {
        let tmp = TempDir::new().unwrap();
        generate("my-cool-app", tmp.path()).unwrap();

        let content = fs::read_to_string(tmp.path().join("my-cool-app/Cargo.toml")).unwrap();
        assert!(content.contains(r#"name = "my-cool-app""#));
        assert!(content.contains("autumn-web = "));
    }

    #[test]
    fn cargo_toml_has_autumn_version() {
        let tmp = TempDir::new().unwrap();
        generate("ver-check", tmp.path()).unwrap();

        let content = fs::read_to_string(tmp.path().join("ver-check/Cargo.toml")).unwrap();
        let expected = format!(r#"autumn-web = "{}""#, env!("CARGO_PKG_VERSION"));
        assert!(content.contains(&expected));
    }

    #[test]
    fn main_rs_has_sample_routes() {
        let tmp = TempDir::new().unwrap();
        generate("route-check", tmp.path()).unwrap();

        let content = fs::read_to_string(tmp.path().join("route-check/src/main.rs")).unwrap();
        assert!(content.contains(r#"#[get("/")]"#));
        assert!(content.contains(r#"#[get("/hello")]"#));
        assert!(content.contains(r#"#[get("/hello/{name}")]"#));
        assert!(content.contains("#[autumn_web::main]"));
        assert!(content.contains("autumn_web::app()"));
    }

    // ── nav_bar scaffold layout (#1137) ─────────────────────────────

    #[test]
    fn main_template_uses_nav_bar_widget() {
        assert!(
            templates::MAIN_RS.contains("nav_bar("),
            "main.rs.tmpl should render its nav via nav_bar(), got:\n{}",
            templates::MAIN_RS
        );
        assert!(
            templates::MAIN_RS.contains("NavBarConfig::new()"),
            "main.rs.tmpl should build a NavBarConfig, got:\n{}",
            templates::MAIN_RS
        );
        assert!(
            !templates::MAIN_RS.contains(r#"nav aria-label="Main navigation""#),
            "main.rs.tmpl should no longer hand-roll its <nav>, got:\n{}",
            templates::MAIN_RS
        );
    }

    #[test]
    fn main_template_layout_takes_current_path() {
        assert!(
            templates::MAIN_RS.contains("current_path: &str"),
            "layout() should take current_path so nav_bar can mark the active link, got:\n{}",
            templates::MAIN_RS
        );
        assert!(
            templates::MAIN_RS.contains("CurrentPath"),
            "index() should extract CurrentPath to pass to layout(), got:\n{}",
            templates::MAIN_RS
        );
    }

    #[test]
    fn main_template_nav_keeps_descriptive_aria_label() {
        // The old hand-rolled <nav> had aria-label="Main navigation"; nav_bar's
        // own default is just "Main", so the template must call .aria_label(...)
        // explicitly or the landmark's accessible name silently degrades.
        assert!(
            templates::MAIN_RS.contains(r#".aria_label("Main navigation")"#),
            "layout()'s NavBarConfig should keep the descriptive \"Main navigation\" \
             aria-label instead of nav_bar's generic \"Main\" default, got:\n{}",
            templates::MAIN_RS
        );
    }

    #[test]
    fn input_css_mobile_nav_collapse_wraps_below_header() {
        // .autumn-nav is a flex row (nowrap by default) and .autumn-nav__collapse
        // is one of its flex items; giving that item `basis-full` only drops it
        // to a new row if the row itself is allowed to wrap. Without flex-wrap
        // on the enhanced root, the opened mobile menu squeezes/overflows onto
        // the same row as the brand and toggle instead of appearing below them.
        //
        // This rule now ships from the framework itself (#1215), not the
        // per-project input.css.tmpl — assert against the shared stylesheet.
        let css = autumn_web::ui::WIDGETS_COMPONENT_CSS;
        let rule_body = css_rule_body(css, ".autumn-nav--enhanced {");
        assert!(
            rule_body.contains("flex-wrap"),
            "the mobile media query must set flex-wrap on .autumn-nav--enhanced itself \
             so .autumn-nav__collapse's basis-full can actually start a new row, got:\n{css}"
        );
    }

    /// Extract the declaration block (without the braces) of the first CSS
    /// rule whose selector text starts with `selector_prefix` (which must
    /// include the trailing ` {`). Scans by byte position rather than
    /// matching a literal multi-line blob, so it doesn't depend on the
    /// source file's line-ending style — this repo checks out `*.tmpl` as
    /// `text=auto`, which normalizes to CRLF on Windows, and a pattern with
    /// an embedded `\n` would never match the CRLF-containing string
    /// `include_str!` reads back on that platform.
    fn css_rule_body<'a>(css: &'a str, selector_prefix: &str) -> &'a str {
        let rule_start = css
            .find(selector_prefix)
            .unwrap_or_else(|| panic!("no bare `{selector_prefix}` rule found in input.css.tmpl"));
        let rest = &css[rule_start..];
        &rest[..rest
            .find('}')
            .unwrap_or_else(|| panic!("unterminated `{selector_prefix}` rule"))]
    }

    #[test]
    fn input_css_nav_collapse_is_flex_row_so_trailing_items_align_right() {
        // .autumn-nav__collapse wraps both the primary .autumn-nav__items
        // list and the .autumn-nav__items--trailing list; without collapse
        // itself being a flex row (and growing to fill the nav's remaining
        // width), the trailing list's ml-auto has no flex row to push
        // against — the two lists just stack vertically as ordinary block
        // children instead of sitting side by side with trailing pinned to
        // the far right, as nav_bar's trailing-slot design intends.
        //
        // This rule now ships from the framework itself (#1215), not the
        // per-project input.css.tmpl — assert against the shared stylesheet.
        let css = autumn_web::ui::WIDGETS_COMPONENT_CSS;
        let rule_body = css_rule_body(css, ".autumn-nav__collapse {");
        assert!(
            rule_body.contains("flex") && !rule_body.contains("flex-col"),
            "the base (non-mobile) .autumn-nav__collapse rule must be a flex row \
             so .autumn-nav__items--trailing's ml-auto can push it to the right \
             edge of the nav, got:\n{css}"
        );
    }

    #[test]
    fn autumn_toml_has_defaults() {
        let tmp = TempDir::new().unwrap();
        generate("cfg-check", tmp.path()).unwrap();

        let content = fs::read_to_string(tmp.path().join("cfg-check/autumn.toml")).unwrap();
        assert!(content.contains("port = 3000"));
        assert!(content.contains(r#"host = "127.0.0.1""#));
        assert!(content.contains(r#"level = "info""#));
        assert!(content.contains(r#"path = "/health""#));
    }

    #[test]
    fn autumn_toml_has_crate_name_in_db_url() {
        let tmp = TempDir::new().unwrap();
        generate("my-db-app", tmp.path()).unwrap();

        let content = fs::read_to_string(tmp.path().join("my-db-app/autumn.toml")).unwrap();
        assert!(content.contains("my_db_app"));
    }

    #[test]
    fn gitignore_excludes_target_and_css() {
        let tmp = TempDir::new().unwrap();
        generate("gi-check", tmp.path()).unwrap();

        let content = fs::read_to_string(tmp.path().join("gi-check/.gitignore")).unwrap();
        assert!(content.contains("/target"));
        assert!(content.contains("static/css/autumn.css"));
        assert!(!content.contains("static/autumn/"));
        // `.env` (and local variants) are gitignored, but the committable
        // `.env.example` template is not.
        assert!(content.lines().any(|l| l.trim() == ".env"));
        assert!(!content.lines().any(|l| l.trim() == ".env.example"));
    }

    #[test]
    fn scaffolds_env_example_and_gitignores_env() {
        let tmp = TempDir::new().unwrap();
        generate("dotenv-check", tmp.path()).unwrap();
        let p = tmp.path().join("dotenv-check");

        // `.env.example` is scaffolded and documents the DB URL env key.
        let example = fs::read_to_string(p.join(".env.example")).unwrap();
        assert!(
            example.contains("AUTUMN_DATABASE__URL"),
            ".env.example must document AUTUMN_DATABASE__URL:\n{example}"
        );
        // crate_name token is substituted into the example URL.
        assert!(example.contains("dotenv_check"), "got:\n{example}");

        // `.gitignore` ignores `.env` but the committable `.env.example` remains
        // in the project (and is not ignored).
        let gitignore = fs::read_to_string(p.join(".gitignore")).unwrap();
        assert!(gitignore.lines().any(|l| l.trim() == ".env"));
        assert!(p.join(".env.example").is_file());
    }

    #[test]
    fn generated_build_rs_reruns_on_css_input_changes() {
        let tmp = TempDir::new().unwrap();
        generate("css-watch-check", tmp.path()).unwrap();

        let content = fs::read_to_string(tmp.path().join("css-watch-check/build.rs")).unwrap();
        assert!(content.contains("cargo:rerun-if-changed=static/css/input.css"));
        // The Tailwind binary's watch path is resolved at build time (issue
        // #2457: a package-relative literal can never agree with wherever
        // `CARGO_TARGET_DIR`/a target triple actually put it), not printed
        // literally in the template — assert the resolution machinery is
        // there instead of a path string that no longer appears verbatim.
        assert!(content.contains("fn find_tailwind_cli"));
        assert!(content.contains("fn candidate_target_dirs"));
        assert!(content.contains("cargo:rerun-if-changed={}"));
        assert!(content.contains("cargo:rerun-if-env-changed=PATH"));
        assert!(content.contains("cargo:rerun-if-env-changed=CARGO_TARGET_DIR"));
    }

    #[test]
    fn generated_build_rs_bakes_build_and_git_provenance() {
        // AC #4 of issue #1242: apps created by `autumn new` capture build + git
        // provenance with zero developer action — the generated build.rs emits
        // the AUTUMN_BUILD_* env vars that `#[autumn_web::main]` reads.
        let tmp = TempDir::new().unwrap();
        generate("provenance-check", tmp.path()).unwrap();

        let content = fs::read_to_string(tmp.path().join("provenance-check/build.rs")).unwrap();
        assert!(content.contains("emit_build_provenance"));
        assert!(content.contains("cargo:rustc-env=AUTUMN_BUILD_TIMESTAMP="));
        assert!(content.contains("cargo:rustc-env=AUTUMN_BUILD_GIT_SHA="));
        assert!(content.contains("cargo:rustc-env=AUTUMN_BUILD_GIT_SHA_SHORT="));
        assert!(content.contains("cargo:rustc-env=AUTUMN_BUILD_GIT_BRANCH="));
        assert!(content.contains("cargo:rustc-env=AUTUMN_BUILD_GIT_DIRTY="));
        // Best-effort git: never fails the build outside a checkout.
        assert!(content.contains("rev-parse"));
        // Re-run when HEAD *moves* (commit/amend/reset all rewrite logs/HEAD),
        // not only when HEAD/index files change.
        assert!(content.contains("logs/HEAD"));
        // Gitdir is resolved by asking git itself, so nested/monorepo apps whose
        // package root has no `.git` still register the parent checkout's rerun
        // triggers. `--git-common-dir` covers linked worktrees where `logs/HEAD`
        // lives in the common dir.
        assert!(content.contains("--git-dir"));
        assert!(content.contains("--git-common-dir"));
        // Linked worktrees: `--amend`/`reset` rewrites the per-worktree reflog
        // (`<git-dir>/logs/HEAD`) but not the shared common-dir reflog, so the
        // generated build.rs must watch the per-worktree reflog too — otherwise
        // Cargo never re-runs after an amend in a worktree and `/actuator/info`
        // reports a stale SHA.
        assert!(content.contains("git_dir.join(\"logs/HEAD\")"));
        // Reproducible builds: honor and watch SOURCE_DATE_EPOCH.
        assert!(content.contains("SOURCE_DATE_EPOCH"));
        assert!(content.contains("cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH"));
    }

    #[test]
    fn generated_build_rs_prefers_build_arg_provenance_over_git() {
        // Issue #1676: containerized builds exclude `/.git` from the build
        // context, so the generated build.rs must prefer `AUTUMN_BUILD_*` build
        // args (Docker `--build-arg`/`ENV` passthrough) when set, falling back
        // to git only for local checkout builds. Without this, production images
        // report `git.*` as `null` on `/actuator/info`.
        let tmp = TempDir::new().unwrap();
        generate("build-arg-provenance-check", tmp.path()).unwrap();

        let content =
            fs::read_to_string(tmp.path().join("build-arg-provenance-check/build.rs")).unwrap();
        // A dedicated helper reads the passthrough env vars.
        assert!(content.contains("fn build_arg("));
        // Each git field prefers the build arg, then falls back to git.
        assert!(content.contains("build_arg(\"AUTUMN_BUILD_GIT_SHA\").or_else(|| git("));
        assert!(content.contains("build_arg(\"AUTUMN_BUILD_GIT_SHA_SHORT\")"));
        assert!(content.contains("build_arg(\"AUTUMN_BUILD_GIT_BRANCH\")"));
        assert!(content.contains("build_arg(\"AUTUMN_BUILD_GIT_DIRTY\")"));
        // Timestamp passthrough wins over the computed timestamp.
        assert!(
            content
                .contains("build_arg(\"AUTUMN_BUILD_TIMESTAMP\").unwrap_or_else(build_timestamp)")
        );
        // Re-run when a passthrough build arg changes so deploys re-bake it.
        assert!(content.contains("cargo:rerun-if-env-changed={var}"));
    }

    #[test]
    fn generated_build_rs_reports_unknown_dirty_as_absent_not_false() {
        // Codex P2 / issue #1676 regression: a container build supplies
        // `AUTUMN_BUILD_GIT_SHA` but leaves `AUTUMN_BUILD_GIT_DIRTY` blank, and
        // the Dockerfile excludes `/.git` so `git status` cannot run. The dirty
        // state is then genuinely UNKNOWN and must be reported as absent/null on
        // `/actuator/info`, NOT collapsed to a misleading `false`.
        //
        // Prove it end-to-end at the producer: compile the generated `build.rs`
        // (which is verbatim Rust, no placeholders) and run its provenance
        // emitter under a controlled environment. Env is passed to the child
        // process (never mutated in-process), so this is isolated from other
        // concurrently running tests.
        let tmp = TempDir::new().unwrap();
        generate("dirty-unknown-check", tmp.path()).unwrap();
        let project = tmp.path().join("dirty-unknown-check");
        let build_rs = project.join("build.rs");

        // Compile the generated build.rs to a standalone binary. `--cap-lints
        // allow` keeps a stray warning from failing under a strict RUSTFLAGS,
        // and RUSTFLAGS is cleared for the same reason.
        let rustc = std::env::var("RUSTC").unwrap_or_else(|_| "rustc".to_string());
        let bin = project.join("provenance_probe");
        let compile = std::process::Command::new(&rustc)
            .arg(&build_rs)
            .arg("--edition")
            .arg("2021")
            .arg("--cap-lints")
            .arg("allow")
            .arg("-o")
            .arg(&bin)
            .env_remove("RUSTFLAGS")
            .output()
            .expect("failed to spawn rustc");
        assert!(
            compile.status.success(),
            "generated build.rs failed to compile:\n{}",
            String::from_utf8_lossy(&compile.stderr)
        );

        // Run the emitter with a cleared environment (so `PATH` is unset and no
        // `git` binary is reachable → git is genuinely unavailable), plus only
        // the provenance env vars under test. Returns the emitted stdout.
        let run = |vars: &[(&str, &str)]| -> String {
            let mut cmd = std::process::Command::new(&bin);
            cmd.current_dir(&project).env_clear();
            for (k, v) in vars {
                cmd.env(k, v);
            }
            let out = cmd.output().expect("failed to run provenance probe");
            assert!(
                out.status.success(),
                "provenance probe exited non-zero:\n{}",
                String::from_utf8_lossy(&out.stderr)
            );
            String::from_utf8(out.stdout).unwrap()
        };

        let has_dirty = |stdout: &str, value: &str| {
            stdout
                .lines()
                .any(|l| l == format!("cargo:rustc-env=AUTUMN_BUILD_GIT_DIRTY={value}"))
        };
        let emits_any_dirty = |stdout: &str| {
            stdout
                .lines()
                .any(|l| l.starts_with("cargo:rustc-env=AUTUMN_BUILD_GIT_DIRTY="))
        };

        // 1. SHA passthrough, dirty blank, no git → dirty is UNKNOWN → the var
        //    is omitted entirely (consumer renders `git.dirty` as null).
        let unknown = run(&[
            (
                "AUTUMN_BUILD_GIT_SHA",
                "0123456789abcdef0123456789abcdef01234567",
            ),
            ("AUTUMN_BUILD_GIT_DIRTY", ""),
        ]);
        assert!(
            unknown.lines().any(|l| l
                == "cargo:rustc-env=AUTUMN_BUILD_GIT_SHA=0123456789abcdef0123456789abcdef01234567"),
            "SHA passthrough should still be emitted:\n{unknown}"
        );
        assert!(
            !emits_any_dirty(&unknown),
            "unknown dirty state must NOT emit AUTUMN_BUILD_GIT_DIRTY (would render as `false`):\n{unknown}"
        );

        // 2. Explicit dirty=true round-trips even with no git.
        let dirty_true = run(&[
            ("AUTUMN_BUILD_GIT_SHA", "abc123"),
            ("AUTUMN_BUILD_GIT_DIRTY", "true"),
        ]);
        assert!(
            has_dirty(&dirty_true, "true"),
            "explicit dirty=true must round-trip:\n{dirty_true}"
        );

        // 3. Explicit dirty=false round-trips (a genuinely clean, known build).
        let dirty_false = run(&[
            ("AUTUMN_BUILD_GIT_SHA", "abc123"),
            ("AUTUMN_BUILD_GIT_DIRTY", "false"),
        ]);
        assert!(
            has_dirty(&dirty_false, "false"),
            "explicit dirty=false must round-trip:\n{dirty_false}"
        );
    }

    /// The first unsubstituted **autumn** template token in `content`, if any.
    ///
    /// Autumn's tokens are `{{lower_snake}}`; GitHub Actions expressions are
    /// `${{ github.token }}`. Both contain `{{`, so a bare `contains("{{")`
    /// would forbid every scaffolded workflow from using an Actions expression.
    /// This looks for our shape specifically, which is what the check was ever
    /// about.
    fn unsubstituted_token(content: &str) -> Option<String> {
        let bytes = content.as_bytes();
        let mut from = 0;
        while let Some(offset) = content[from..].find("{{") {
            let open = from + offset;
            // `${{ … }}` is a GitHub Actions expression, not ours.
            let escaped = open > 0 && bytes[open - 1] == b'$';
            if !escaped && let Some(len) = content[open + 2..].find("}}") {
                let token = &content[open + 2..open + 2 + len];
                if !token.is_empty()
                    && token
                        .chars()
                        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
                {
                    return Some(token.to_owned());
                }
            }
            from = open + 2;
        }
        None
    }

    #[test]
    fn placeholder_scanner_tells_our_tokens_from_actions_expressions() {
        assert_eq!(
            unsubstituted_token("name: ${{ github.token }} and {{project_name}}").as_deref(),
            Some("project_name"),
            "an Actions expression is fine; ours is not"
        );
        assert_eq!(
            unsubstituted_token("${{ github.event.pull_request.number }}"),
            None
        );
        assert_eq!(
            unsubstituted_token("run: exit ${{ steps.diff.outputs.status }}"),
            None
        );
        assert_eq!(unsubstituted_token("nothing templated here"), None);
    }

    #[test]
    fn no_unsubstituted_placeholders() {
        let tmp = TempDir::new().unwrap();
        generate("placeholder-check", tmp.path()).unwrap();

        let p = tmp.path().join("placeholder-check");
        for entry in walkdir(&p) {
            let content = fs::read_to_string(&entry).unwrap();
            assert!(
                unsubstituted_token(&content).is_none(),
                "unsubstituted placeholder {:?} in {}",
                unsubstituted_token(&content),
                entry.display()
            );
        }
    }

    #[test]
    fn daemon_readme_has_no_unsubstituted_placeholders() {
        // The daemon / bundled-pg README bodies are built in Rust (not the
        // template), so guard them against reintroducing `{{…}}` tokens.
        for opts in [daemon_opts(), bundled_pg_opts()] {
            let tmp = TempDir::new().unwrap();
            generate_with("ph-daemon-app", tmp.path(), opts).unwrap();
            let readme = fs::read_to_string(tmp.path().join("ph-daemon-app/README.md")).unwrap();
            assert!(
                !readme.contains("{{"),
                "unsubstituted placeholder in daemon/bundled README (opts {opts:?}):\n{readme}"
            );
        }
    }

    #[test]
    fn daemon_readme_drops_db_bootstrap() {
        // A DB-free daemon must not tell users to run migrations or configure a
        // database; it runs via `autumn serve`.
        let tmp = TempDir::new().unwrap();
        generate_with("daemon-readme", tmp.path(), daemon_opts()).unwrap();
        let readme = fs::read_to_string(tmp.path().join("daemon-readme/README.md")).unwrap();
        assert!(!readme.contains("autumn migrate"), "got:\n{readme}");
        assert!(!readme.contains("libpq"), "got:\n{readme}");
        assert!(readme.contains("autumn serve"), "got:\n{readme}");
        // Project name still substituted.
        assert!(readme.contains("daemon-readme"), "got:\n{readme}");
    }

    #[test]
    fn bundled_pg_readme_documents_managed_db() {
        // A bundled-pg daemon manages its own Postgres and auto-applies
        // migrations; it runs via `autumn serve --bundled-pg`.
        let tmp = TempDir::new().unwrap();
        generate_with("bundled-readme", tmp.path(), bundled_pg_opts()).unwrap();
        let readme = fs::read_to_string(tmp.path().join("bundled-readme/README.md")).unwrap();
        assert!(!readme.contains("autumn migrate"), "got:\n{readme}");
        assert!(
            readme.contains("autumn serve --bundled-pg"),
            "got:\n{readme}"
        );
    }

    #[test]
    fn default_readme_db_bootstrap_does_not_dead_end_on_release_init() {
        // The default golden path must bootstrap a local Postgres
        // with `docker run` (which always works), not lead with
        // `release init --target docker-compose` (which file-errors on a fresh
        // scaffold). The AC-required pointer is still present for deployment.
        let tmp = TempDir::new().unwrap();
        generate("dockerrun-app", tmp.path()).unwrap();
        let readme = fs::read_to_string(tmp.path().join("dockerrun-app/README.md")).unwrap();
        assert!(
            readme.contains("docker run") && readme.contains("postgres:16"),
            "default README must offer a `docker run … postgres:16` DB bootstrap, got:\n{readme}"
        );
        // Codex P2: the runnable `docker run -d …` helper must appear exactly once
        // (in step 2), not be duplicated in the prerequisites — a second identical
        // command dead-ends on a `{crate}-pg` container-name-in-use error.
        assert_eq!(
            readme.matches("docker run -d").count(),
            1,
            "default README must contain the runnable `docker run -d …` helper exactly once, \
             got:\n{readme}"
        );
        assert!(
            readme.contains("autumn release init --target docker-compose"),
            "default README must still point at `release init --target docker-compose`, \
             got:\n{readme}"
        );
    }

    #[test]
    fn already_exists_error() {
        let tmp = TempDir::new().unwrap();
        generate("dupe-check", tmp.path()).unwrap();
        let err = generate("dupe-check", tmp.path()).unwrap_err();
        assert!(matches!(err, NewError::AlreadyExists(_)));
        assert!(err.to_string().contains("already exists"));
    }

    #[test]
    fn invalid_name_error() {
        let tmp = TempDir::new().unwrap();
        let err = generate("123bad", tmp.path()).unwrap_err();
        assert!(matches!(err, NewError::InvalidName(_, _)));
    }

    // ── --with-i18n scaffold ─────────────────────────────────────

    #[test]
    fn default_does_not_scaffold_i18n() {
        let tmp = TempDir::new().unwrap();
        generate("plain-app", tmp.path()).unwrap();
        let p = tmp.path().join("plain-app");
        assert!(!p.join("i18n").exists());
        let cargo = fs::read_to_string(p.join("Cargo.toml")).unwrap();
        assert!(!cargo.contains("features = [\"i18n\"]"));
        let toml = fs::read_to_string(p.join("autumn.toml")).unwrap();
        assert!(!toml.contains("[i18n]"));
        let main = fs::read_to_string(p.join("src/main.rs")).unwrap();
        assert!(!main.contains(".i18n_auto()"));
    }

    fn daemon_opts() -> GenerateOptions {
        GenerateOptions {
            with_daemon: true,
            ..GenerateOptions::default()
        }
    }

    /// Windows PDB files cap public symbols (LNK4319, issue #2448). Every
    /// starter shape must set a reduced dev profile, for the app and for its
    /// dependencies.
    #[test]
    fn every_generated_shape_scaffolds_reduced_dev_debug_info() {
        let shapes = [
            ("shape-default", GenerateOptions::default()),
            ("shape-bundled", bundled_pg_opts()),
            ("shape-daemon", daemon_opts()),
            (
                "shape-seed",
                GenerateOptions {
                    with_seed: true,
                    ..GenerateOptions::default()
                },
            ),
            (
                "shape-api-i18n",
                GenerateOptions {
                    with_api: true,
                    with_i18n: true,
                    ..GenerateOptions::default()
                },
            ),
            (
                "shape-api",
                GenerateOptions {
                    with_api: true,
                    ..GenerateOptions::default()
                },
            ),
        ];
        for (name, opts) in shapes {
            let tmp = TempDir::new().unwrap();
            generate_with(name, tmp.path(), opts).unwrap();
            let raw = fs::read_to_string(tmp.path().join(name).join("Cargo.toml")).unwrap();
            let doc: toml::Table = raw.parse().unwrap();
            let dev = doc
                .get("profile")
                .and_then(|p| p.get("dev"))
                .unwrap_or_else(|| panic!("{name}: no [profile.dev]: {raw}"));
            assert_eq!(
                dev["debug"].as_str(),
                Some("line-tables-only"),
                "{name}: {raw}"
            );
            assert_eq!(
                dev["package"]["*"]["debug"].as_str(),
                Some("line-tables-only"),
                "{name}: dependencies need their own setting: {raw}"
            );
        }
    }

    /// The profile alone does not clear LNK4319 on Windows (issue #2448).
    /// Every shape also needs the linker's own remedy for MSVC targets.
    #[test]
    fn every_generated_shape_scaffolds_long_symbol_truncate() {
        let shapes = [
            ("lst-default", GenerateOptions::default()),
            ("lst-bundled", bundled_pg_opts()),
            ("lst-daemon", daemon_opts()),
            (
                "lst-api",
                GenerateOptions {
                    with_api: true,
                    ..GenerateOptions::default()
                },
            ),
        ];
        for (name, opts) in shapes {
            let tmp = TempDir::new().unwrap();
            generate_with(name, tmp.path(), opts).unwrap();
            let path = tmp.path().join(name).join(".cargo/config.toml");
            let raw = fs::read_to_string(&path)
                .unwrap_or_else(|e| panic!("{name}: no .cargo/config.toml: {e}"));
            let doc: toml::Table = raw.parse().unwrap();
            for triple in ["x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc"] {
                let flags = doc["target"][triple]["rustflags"].as_array().unwrap();
                assert!(
                    flags
                        .iter()
                        .any(|f| f.as_str() == Some("-Clink-arg=/DEBUG:LongSymbolTruncate")),
                    "{name}: {triple} lacks LongSymbolTruncate: {raw}"
                );
            }
        }
    }

    #[test]
    fn daemon_with_seed_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let err = generate_with(
            "daemon-seed-app",
            tmp.path(),
            GenerateOptions {
                with_daemon: true,
                with_seed: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap_err();
        assert!(matches!(err, NewError::IncompatibleOptions(_)));
        // Nothing should be scaffolded on rejection.
        assert!(!tmp.path().join("daemon-seed-app").exists());
    }

    #[test]
    fn daemon_with_plugins_is_rejected() {
        let err = check_with_plugins(daemon_opts(), 1).unwrap_err();
        assert!(matches!(err, NewError::IncompatibleOptions(_)));
    }

    #[test]
    fn daemon_without_plugins_is_accepted() {
        assert!(check_with_plugins(daemon_opts(), 0).is_ok());
    }

    #[test]
    fn plugins_with_a_database_flavor_are_accepted() {
        let bundled = GenerateOptions {
            with_bundled_pg: true,
            with_daemon: true,
            ..GenerateOptions::default()
        };
        assert!(check_with_plugins(bundled, 2).is_ok());
        assert!(check_with_plugins(GenerateOptions::default(), 2).is_ok());
    }

    #[test]
    fn bundled_pg_with_seed_is_rejected() {
        let tmp = TempDir::new().unwrap();
        let err = generate_with(
            "pg-seed-app",
            tmp.path(),
            GenerateOptions {
                with_bundled_pg: true,
                with_daemon: true,
                with_seed: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap_err();
        assert!(matches!(err, NewError::IncompatibleOptions(_)));
        assert!(!tmp.path().join("pg-seed-app").exists());
    }

    #[test]
    fn daemon_starter_omits_db_feature() {
        let tmp = TempDir::new().unwrap();
        generate_with("daemon-app", tmp.path(), daemon_opts()).unwrap();
        let cargo = fs::read_to_string(tmp.path().join("daemon-app/Cargo.toml")).unwrap();
        assert!(
            cargo.contains("default-features = false"),
            "daemon starter must disable default features (drop db): {cargo}"
        );
        assert!(
            !cargo.contains("\"db\""),
            "daemon starter must not enable db"
        );
        assert!(
            !cargo.contains("\"postgres\""),
            "daemon starter must not enable postgres"
        );
        assert!(
            !cargo.contains("diesel_migrations"),
            "daemon starter must not depend on diesel_migrations"
        );
    }

    #[test]
    fn daemon_starter_main_has_no_migrations() {
        let tmp = TempDir::new().unwrap();
        generate_with("daemon-main-app", tmp.path(), daemon_opts()).unwrap();
        let main = fs::read_to_string(tmp.path().join("daemon-main-app/src/main.rs")).unwrap();
        assert!(
            !main.contains(".migrations("),
            "daemon main must not call .migrations()"
        );
        assert!(
            !main.contains("embed_migrations"),
            "daemon main must not embed migrations"
        );
    }

    #[test]
    fn daemon_starter_autumn_toml_documents_zero_db() {
        let tmp = TempDir::new().unwrap();
        generate_with("daemon-cfg-app", tmp.path(), daemon_opts()).unwrap();
        let toml = fs::read_to_string(tmp.path().join("daemon-cfg-app/autumn.toml")).unwrap();
        assert!(toml.contains("autumn serve"));
    }

    fn bundled_pg_opts() -> GenerateOptions {
        GenerateOptions {
            with_bundled_pg: true,
            with_daemon: true,
            ..GenerateOptions::default()
        }
    }

    #[test]
    fn bundled_pg_starter_enables_managed_feature_and_keeps_db() {
        let tmp = TempDir::new().unwrap();
        generate_with("pg-app", tmp.path(), bundled_pg_opts()).unwrap();
        let cargo = fs::read_to_string(tmp.path().join("pg-app/Cargo.toml")).unwrap();
        assert!(
            cargo.contains("managed-pg-bundled"),
            "bundled starter must enable managed-pg-bundled: {cargo}"
        );
        assert!(
            !cargo.contains("default-features = false"),
            "bundled starter keeps the database (default features on)"
        );
    }

    #[test]
    fn bundled_pg_autumn_toml_enables_auto_migrate_in_production() {
        let tmp = TempDir::new().unwrap();
        generate_with("pg-cfg-app", tmp.path(), bundled_pg_opts()).unwrap();
        let toml = fs::read_to_string(tmp.path().join("pg-cfg-app/autumn.toml")).unwrap();
        // A `--release` daemon runs under the prod profile and the managed DB is
        // unreachable to `autumn migrate`, so migrations must apply automatically.
        assert!(
            toml.contains("[database]") && toml.contains("auto_migrate_in_production = true"),
            "bundled starter must auto-migrate in production: {toml}"
        );
        // Still valid TOML (no duplicate tables with the commented template).
        toml::from_str::<toml::Table>(&toml).expect("generated autumn.toml parses");
    }

    #[test]
    fn bundled_pg_main_installs_provider_and_shutdown_hook() {
        let tmp = TempDir::new().unwrap();
        generate_with("pg-main-app", tmp.path(), bundled_pg_opts()).unwrap();
        let main = fs::read_to_string(tmp.path().join("pg-main-app/src/main.rs")).unwrap();
        assert!(main.contains("ManagedPostgresPoolProvider"));
        assert!(main.contains(".with_pool_provider("));
        assert!(main.contains(".on_shutdown("));
        // Database present: migrations kept.
        assert!(main.contains(".migrations("));
    }

    #[test]
    fn default_generation_has_no_managed_pg() {
        let tmp = TempDir::new().unwrap();
        generate("plain2-app", tmp.path()).unwrap();
        let main = fs::read_to_string(tmp.path().join("plain2-app/src/main.rs")).unwrap();
        assert!(!main.contains("with_pool_provider"));
        let cargo = fs::read_to_string(tmp.path().join("plain2-app/Cargo.toml")).unwrap();
        assert!(!cargo.contains("managed-pg"));
    }

    #[test]
    fn default_generation_still_has_db() {
        let tmp = TempDir::new().unwrap();
        generate("plain-app", tmp.path()).unwrap();
        let cargo = fs::read_to_string(tmp.path().join("plain-app/Cargo.toml")).unwrap();
        // Default keeps the simple full-default dependency and migrations.
        assert!(cargo.contains(r#"autumn-web = ""#));
        assert!(!cargo.contains("default-features = false"));
        assert!(cargo.contains("diesel_migrations"));
        let main = fs::read_to_string(tmp.path().join("plain-app/src/main.rs")).unwrap();
        assert!(main.contains(".migrations("));
    }

    #[test]
    fn with_i18n_scaffolds_translation_dir_and_stub_file() {
        let tmp = TempDir::new().unwrap();
        generate_with(
            "i18n-app",
            tmp.path(),
            GenerateOptions {
                with_i18n: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();
        let p = tmp.path().join("i18n-app");
        assert!(p.join("i18n").is_dir(), "i18n/ dir not created");
        assert!(
            p.join("i18n/en.ftl").is_file(),
            "i18n/en.ftl stub not created"
        );
        let stub = fs::read_to_string(p.join("i18n/en.ftl")).unwrap();
        assert!(stub.contains("welcome.title"));
        assert!(stub.contains("welcome.greeting"));
    }

    #[test]
    fn with_i18n_enables_feature_flag_in_cargo_toml() {
        let tmp = TempDir::new().unwrap();
        generate_with(
            "feat-app",
            tmp.path(),
            GenerateOptions {
                with_i18n: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();
        let cargo = fs::read_to_string(tmp.path().join("feat-app/Cargo.toml")).unwrap();
        assert!(
            cargo.contains(r#"features = ["i18n"]"#),
            "Cargo.toml should enable i18n feature: {cargo}"
        );
    }

    #[test]
    fn with_i18n_adds_block_to_autumn_toml() {
        let tmp = TempDir::new().unwrap();
        generate_with(
            "cfg-app",
            tmp.path(),
            GenerateOptions {
                with_i18n: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();
        let cfg = fs::read_to_string(tmp.path().join("cfg-app/autumn.toml")).unwrap();
        assert!(cfg.contains("[i18n]"));
        assert!(cfg.contains("default_locale = \"en\""));
        assert!(cfg.contains("supported_locales = [\"en\"]"));
    }

    #[test]
    fn with_i18n_calls_i18n_auto_in_main() {
        let tmp = TempDir::new().unwrap();
        generate_with(
            "main-app",
            tmp.path(),
            GenerateOptions {
                with_i18n: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();
        let main = fs::read_to_string(tmp.path().join("main-app/src/main.rs")).unwrap();
        assert!(
            main.contains(".i18n_auto()"),
            "main.rs should call .i18n_auto(): {main}"
        );
    }

    #[test]
    fn with_i18n_copies_i18n_into_fullstack_docker_image() {
        // The fullstack (non-`--api`) scaffold's `main.rs` calls `.i18n_auto()`
        // for `--with-i18n`, which loads `i18n/en.ftl` from disk at startup and
        // panics if missing. The image must therefore ship the `i18n/` sidecar
        // into both the builder and runtime stages (issue #1865, mirroring the
        // `--api` fix in #1847).
        let tmp = TempDir::new().unwrap();
        generate_with(
            "i18n-docker-app",
            tmp.path(),
            GenerateOptions {
                with_i18n: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();
        let dockerfile = fs::read_to_string(tmp.path().join("i18n-docker-app/Dockerfile")).unwrap();
        assert!(
            dockerfile.contains("COPY i18n ./i18n"),
            "--with-i18n fullstack Dockerfile must copy i18n/ into the builder stage:\n{dockerfile}"
        );
        assert!(
            dockerfile.contains("COPY --from=builder /app/i18n /app/i18n"),
            "--with-i18n fullstack Dockerfile must copy i18n/ into the runtime stage:\n{dockerfile}"
        );
        assert!(
            !dockerfile.contains("__AUTUMN_I18N"),
            "--with-i18n fullstack Dockerfile must not leave anchor markers:\n{dockerfile}"
        );
    }

    #[test]
    fn without_i18n_fullstack_docker_image_has_no_i18n_copy() {
        // A non-i18n fullstack Dockerfile must carry NO i18n `COPY` lines (an
        // unconditional `COPY i18n ./i18n` would break `docker build`, whose
        // context has no `i18n/` dir) and no leftover anchor markers.
        let tmp = TempDir::new().unwrap();
        generate("no-i18n-docker-app", tmp.path()).unwrap();
        let dockerfile =
            fs::read_to_string(tmp.path().join("no-i18n-docker-app/Dockerfile")).unwrap();
        assert!(
            !dockerfile.contains("COPY i18n ./i18n"),
            "non-i18n fullstack Dockerfile must not copy i18n/ (build context has no i18n/ dir):\n{dockerfile}"
        );
        assert!(
            !dockerfile.contains("/app/i18n"),
            "non-i18n fullstack Dockerfile must not reference /app/i18n:\n{dockerfile}"
        );
        assert!(
            !dockerfile.contains("__AUTUMN_I18N"),
            "non-i18n fullstack Dockerfile must not leave anchor markers:\n{dockerfile}"
        );
    }

    fn walkdir(dir: &Path) -> Vec<std::path::PathBuf> {
        let mut files = Vec::new();
        if let Ok(entries) = fs::read_dir(dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    files.extend(walkdir(&path));
                } else {
                    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
                    if ext != "enc" {
                        files.push(path);
                    }
                }
            }
        }
        files
    }

    // ── --with-seed tests ──────────────────────────────────────────────────

    #[test]
    fn no_seed_bin_without_flag() {
        let tmp = TempDir::new().unwrap();
        generate("no-seed-app", tmp.path()).unwrap();
        assert!(!tmp.path().join("no-seed-app/src/bin/seed.rs").exists());
    }

    #[test]
    fn generates_seed_bin_when_with_seed() {
        let tmp = TempDir::new().unwrap();
        generate_with(
            "seed-app",
            tmp.path(),
            GenerateOptions {
                with_seed: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();
        assert!(tmp.path().join("seed-app/src/bin/seed.rs").is_file());
    }

    #[test]
    fn with_seed_cargo_toml_has_bin_entry_and_seed_feature() {
        let tmp = TempDir::new().unwrap();
        generate_with(
            "seed-cargo",
            tmp.path(),
            GenerateOptions {
                with_seed: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();
        let content = fs::read_to_string(tmp.path().join("seed-cargo/Cargo.toml")).unwrap();
        assert!(
            content.contains("[[bin]]"),
            "Cargo.toml should have [[bin]]"
        );
        assert!(
            content.contains("seed"),
            "Cargo.toml [[bin]] entry should mention 'seed'"
        );
        // The seed feature must be enabled on autumn-web so src/bin/seed.rs
        // can import autumn_web::seed::SeedContext without manual edits.
        assert!(
            content.contains(r#"features = ["seed"]"#),
            "autumn-web dependency should include the seed feature, got:\n{content}"
        );
    }

    #[test]
    fn with_i18n_and_seed_combines_feature_flags() {
        let tmp = TempDir::new().unwrap();
        generate_with(
            "combo-app",
            tmp.path(),
            GenerateOptions {
                with_i18n: true,
                with_seed: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();

        let p = tmp.path().join("combo-app");
        let cargo = fs::read_to_string(p.join("Cargo.toml")).unwrap();
        assert!(
            cargo.contains(r#"features = ["i18n", "seed"]"#),
            "Cargo.toml should preserve both optional features: {cargo}"
        );
        assert!(p.join("i18n/en.ftl").is_file());
        assert!(p.join("src/bin/seed.rs").is_file());
    }

    #[test]
    fn no_bin_entry_in_cargo_toml_without_flag() {
        let tmp = TempDir::new().unwrap();
        generate("plain-cargo", tmp.path()).unwrap();
        let content = fs::read_to_string(tmp.path().join("plain-cargo/Cargo.toml")).unwrap();
        assert!(
            !content.contains("[[bin]]"),
            "Cargo.toml should not have [[bin]] when --with-seed is off"
        );
    }

    #[test]
    fn with_seed_no_unsubstituted_placeholders() {
        let tmp = TempDir::new().unwrap();
        generate_with(
            "seed-placeholder-check",
            tmp.path(),
            GenerateOptions {
                with_seed: true,
                ..GenerateOptions::default()
            },
        )
        .unwrap();

        let p = tmp.path().join("seed-placeholder-check");
        for entry in walkdir(&p) {
            let content = fs::read_to_string(&entry).unwrap();
            assert!(
                unsubstituted_token(&content).is_none(),
                "unsubstituted placeholder {:?} in {}",
                unsubstituted_token(&content),
                entry.display()
            );
        }
    }

    // ── credentials scaffolding tests ─────────────────────────────────────

    #[test]
    fn generates_config_credentials_directory() {
        let tmp = TempDir::new().unwrap();
        generate("cred-app", tmp.path()).unwrap();
        let p = tmp.path().join("cred-app");
        assert!(
            p.join("config/credentials").is_dir(),
            "config/credentials/ directory must be created by autumn new"
        );
    }

    #[test]
    fn generates_development_enc_file() {
        let tmp = TempDir::new().unwrap();
        generate("cred-enc-app", tmp.path()).unwrap();
        let p = tmp.path().join("cred-enc-app");
        assert!(
            p.join("config/credentials/development.toml.enc").is_file(),
            "config/credentials/development.toml.enc must be created by autumn new"
        );
    }

    #[test]
    fn generates_master_key_file() {
        let tmp = TempDir::new().unwrap();
        generate("key-app", tmp.path()).unwrap();
        let p = tmp.path().join("key-app");
        assert!(
            p.join("config/master.key").is_file(),
            "config/master.key must be created by autumn new"
        );
    }

    #[test]
    fn master_key_file_contains_64_hex_chars() {
        let tmp = TempDir::new().unwrap();
        generate("key-hex-app", tmp.path()).unwrap();
        let key = fs::read_to_string(tmp.path().join("key-hex-app/config/master.key")).unwrap();
        let key = key.trim();
        assert_eq!(key.len(), 64, "master.key must contain 64 hex chars");
        assert!(
            key.chars().all(|c| c.is_ascii_hexdigit()),
            "master.key must be valid hex"
        );
    }

    #[test]
    fn gitignore_includes_master_key() {
        let tmp = TempDir::new().unwrap();
        generate("gi-key-app", tmp.path()).unwrap();
        let content = fs::read_to_string(tmp.path().join("gi-key-app/.gitignore")).unwrap();
        assert!(
            content.contains("config/master.key"),
            ".gitignore must exclude config/master.key, got:\n{content}"
        );
    }

    #[test]
    fn gitignore_does_not_exclude_enc_files() {
        let tmp = TempDir::new().unwrap();
        generate("gi-enc-app", tmp.path()).unwrap();
        let content = fs::read_to_string(tmp.path().join("gi-enc-app/.gitignore")).unwrap();
        assert!(
            !content.contains("*.enc"),
            ".gitignore must NOT exclude .enc files (they're safe to commit), got:\n{content}"
        );
    }

    #[test]
    fn development_enc_file_is_decryptable_with_master_key() {
        use autumn_web::credentials::{MasterKey, decrypt};
        let tmp = TempDir::new().unwrap();
        generate("roundtrip-cred-app", tmp.path()).unwrap();
        let p = tmp.path().join("roundtrip-cred-app");
        let key_hex = fs::read_to_string(p.join("config/master.key")).unwrap();
        let key = MasterKey::from_hex_pub(key_hex.trim()).expect("master.key should be valid hex");
        let ct = fs::read(p.join("config/credentials/development.toml.enc")).unwrap();
        let pt = decrypt(&key, &ct).expect("development.toml.enc should decrypt with master.key");
        let s = String::from_utf8(pt).unwrap();
        assert!(
            s.contains("stripe_secret_key") || s.contains('#'),
            "decrypted content should have placeholder comments"
        );
    }

    // ── rust-toolchain.toml / rustfmt.toml / clippy.toml scaffolding ─────────

    #[test]
    fn generates_rust_toolchain_toml() {
        let tmp = TempDir::new().unwrap();
        generate("toolchain-app", tmp.path()).unwrap();
        let p = tmp.path().join("toolchain-app");
        assert!(
            p.join("rust-toolchain.toml").is_file(),
            "`autumn new` must write rust-toolchain.toml"
        );
    }

    #[test]
    fn rust_toolchain_pins_channel_to_msrv() {
        let tmp = TempDir::new().unwrap();
        generate("toolchain-ver-app", tmp.path()).unwrap();
        let content =
            fs::read_to_string(tmp.path().join("toolchain-ver-app/rust-toolchain.toml")).unwrap();
        assert!(
            content.contains("channel"),
            "rust-toolchain.toml must set channel: {content}"
        );
        assert!(
            content.contains("1.97.0"),
            "rust-toolchain.toml channel must match the Cargo.toml rust-version (1.97.0): {content}"
        );
    }

    #[test]
    fn rust_toolchain_lists_rustfmt_and_clippy_components() {
        let tmp = TempDir::new().unwrap();
        generate("toolchain-comp-app", tmp.path()).unwrap();
        let content =
            fs::read_to_string(tmp.path().join("toolchain-comp-app/rust-toolchain.toml")).unwrap();
        assert!(
            content.contains("rustfmt"),
            "rust-toolchain.toml must list rustfmt in components: {content}"
        );
        assert!(
            content.contains("clippy"),
            "rust-toolchain.toml must list clippy in components: {content}"
        );
    }

    #[test]
    fn generates_rustfmt_toml() {
        let tmp = TempDir::new().unwrap();
        generate("fmt-app", tmp.path()).unwrap();
        let p = tmp.path().join("fmt-app");
        assert!(
            p.join("rustfmt.toml").is_file(),
            "`autumn new` must write rustfmt.toml"
        );
    }

    #[test]
    fn rustfmt_toml_has_correct_edition_and_max_width() {
        let tmp = TempDir::new().unwrap();
        generate("fmt-cfg-app", tmp.path()).unwrap();
        let content = fs::read_to_string(tmp.path().join("fmt-cfg-app/rustfmt.toml")).unwrap();
        assert!(
            content.contains(r#"edition = "2024""#),
            "rustfmt.toml must set edition = \"2024\": {content}"
        );
        assert!(
            content.contains("max_width = 100"),
            "rustfmt.toml must set max_width = 100: {content}"
        );
    }

    #[test]
    fn generates_clippy_toml() {
        let tmp = TempDir::new().unwrap();
        generate("clippy-app", tmp.path()).unwrap();
        let p = tmp.path().join("clippy-app");
        assert!(
            p.join("clippy.toml").is_file(),
            "`autumn new` must write clippy.toml"
        );
    }

    #[test]
    fn clippy_toml_msrv_matches_rust_version() {
        let tmp = TempDir::new().unwrap();
        generate("clippy-msrv-app", tmp.path()).unwrap();
        let content = fs::read_to_string(tmp.path().join("clippy-msrv-app/clippy.toml")).unwrap();
        assert!(
            content.contains("msrv"),
            "clippy.toml must set msrv: {content}"
        );
        assert!(
            content.contains("1.97.0"),
            "clippy.toml msrv must match Cargo.toml rust-version (1.97.0): {content}"
        );
    }

    #[test]
    fn gitignore_does_not_exclude_toolchain_files() {
        let tmp = TempDir::new().unwrap();
        generate("gi-toolchain-app", tmp.path()).unwrap();
        let content = fs::read_to_string(tmp.path().join("gi-toolchain-app/.gitignore")).unwrap();
        assert!(
            !content.contains("rust-toolchain"),
            ".gitignore must NOT exclude rust-toolchain.toml: {content}"
        );
        assert!(
            !content.contains("rustfmt.toml"),
            ".gitignore must NOT exclude rustfmt.toml: {content}"
        );
        assert!(
            !content.contains("clippy.toml"),
            ".gitignore must NOT exclude clippy.toml: {content}"
        );
    }

    #[test]
    fn scaffold_summary_mentions_toolchain_files() {
        let tmp = TempDir::new().unwrap();
        // Use generate_with (non-quiet) and capture stdout.
        // We can't easily capture stdout in unit tests, so we verify the files
        // exist and the summary helper doesn't strip them — this is covered by
        // the file-existence tests above. This test verifies print_scaffold_summary
        // is at least called without panic for the default case.
        generate("summary-toolchain-app", tmp.path()).unwrap();
        let p = tmp.path().join("summary-toolchain-app");
        assert!(p.join("rust-toolchain.toml").is_file());
        assert!(p.join("rustfmt.toml").is_file());
        assert!(p.join("clippy.toml").is_file());
    }

    #[test]
    fn two_new_projects_get_different_master_keys() {
        let tmp1 = TempDir::new().unwrap();
        let tmp2 = TempDir::new().unwrap();
        generate("app-a", tmp1.path()).unwrap();
        generate("app-b", tmp2.path()).unwrap();
        let k1 = fs::read_to_string(tmp1.path().join("app-a/config/master.key")).unwrap();
        let k2 = fs::read_to_string(tmp2.path().join("app-b/config/master.key")).unwrap();
        assert_ne!(
            k1.trim(),
            k2.trim(),
            "each project must get a unique master key"
        );
    }

    #[cfg(unix)]
    #[test]
    fn master_key_file_has_secure_permissions() {
        use std::os::unix::fs::MetadataExt;
        let tmp = TempDir::new().unwrap();
        generate("secure-key-app", tmp.path()).unwrap();
        let p = tmp.path().join("secure-key-app/config/master.key");
        let meta = fs::metadata(&p).unwrap();
        let mode = meta.mode() & 0o777;
        assert_eq!(
            mode, 0o600,
            "master.key permissions must be 0o600, got {mode:#o}"
        );
    }

    // ── Vendor asset scaffolding ─────────────────────────────────────────────

    #[test]
    fn scaffold_writes_htmx_js_file() {
        let tmp = TempDir::new().unwrap();
        generate("asset-app", tmp.path()).unwrap();
        let htmx = tmp.path().join("asset-app/static/js/htmx.min.js");
        assert!(
            htmx.is_file(),
            "static/js/htmx.min.js must be created by `autumn new`"
        );
        let bytes = fs::read(&htmx).unwrap();
        assert!(!bytes.is_empty(), "htmx.min.js must not be empty");
    }

    #[test]
    fn scaffold_writes_vendor_manifest() {
        let tmp = TempDir::new().unwrap();
        generate("manifest-app", tmp.path()).unwrap();
        let manifest_path = tmp.path().join("manifest-app/static/.autumn-assets.json");
        assert!(
            manifest_path.is_file(),
            "static/.autumn-assets.json must be created by `autumn new`"
        );
        let content = fs::read_to_string(&manifest_path).unwrap();
        let manifest: serde_json::Value =
            serde_json::from_str(&content).expect("manifest must be valid JSON");
        assert_eq!(manifest["version"], "1", "manifest must have version=1");
        let htmx = &manifest["assets"]["htmx"];
        assert!(!htmx.is_null(), "manifest must contain an htmx entry");
        assert!(
            htmx["version"].as_str().unwrap_or("").contains('.'),
            "htmx version must look like a semver: {}",
            htmx["version"]
        );
        let integrity = htmx["integrity"].as_str().unwrap_or("");
        assert!(
            integrity.starts_with("sha384-"),
            "htmx integrity must be a sha384 SRI hash: {integrity}"
        );

        let sse = &manifest["assets"]["htmx-ext-sse"];
        assert!(
            !sse.is_null(),
            "manifest must contain an htmx-ext-sse entry"
        );
        assert!(
            sse["version"].as_str().unwrap_or("").contains('.'),
            "htmx-ext-sse version must look like a semver: {}",
            sse["version"]
        );
        let sse_integrity = sse["integrity"].as_str().unwrap_or("");
        assert!(
            sse_integrity.starts_with("sha384-"),
            "htmx-ext-sse integrity must be a sha384 SRI hash: {sse_integrity}"
        );
    }

    #[test]
    fn manifest_integrity_matches_vendored_file() {
        let tmp = TempDir::new().unwrap();
        generate("sri-app", tmp.path()).unwrap();
        let p = tmp.path().join("sri-app");

        let htmx_bytes = fs::read(p.join("static/js/htmx.min.js")).unwrap();
        let computed = crate::assets::compute_sri(&htmx_bytes);

        let manifest_raw = fs::read_to_string(p.join("static/.autumn-assets.json")).unwrap();
        let manifest: serde_json::Value = serde_json::from_str(&manifest_raw).unwrap();
        let recorded = manifest["assets"]["htmx"]["integrity"].as_str().unwrap();

        assert_eq!(
            computed, recorded,
            "SRI hash in manifest must match the vendored htmx.min.js"
        );

        let sse_bytes = fs::read(p.join("static/js/htmx-ext-sse.min.js")).unwrap();
        let computed_sse = crate::assets::compute_sri(&sse_bytes);
        let recorded_sse = manifest["assets"]["htmx-ext-sse"]["integrity"]
            .as_str()
            .unwrap();

        assert_eq!(
            computed_sse, recorded_sse,
            "SRI hash in manifest must match the vendored htmx-ext-sse.min.js"
        );
    }

    #[test]
    fn generated_main_rs_uses_javascript_include_tag() {
        let tmp = TempDir::new().unwrap();
        generate("helper-app", tmp.path()).unwrap();
        let content = fs::read_to_string(tmp.path().join("helper-app/src/main.rs")).unwrap();
        assert!(
            content.contains("javascript_include_tag(\"htmx\")"),
            "generated main.rs must use javascript_include_tag(\"htmx\"), got:\n{content}"
        );
    }

    #[test]
    fn generated_main_rs_has_no_hardcoded_htmx_script_src() {
        let tmp = TempDir::new().unwrap();
        generate("no-hardcode-app", tmp.path()).unwrap();
        let content = fs::read_to_string(tmp.path().join("no-hardcode-app/src/main.rs")).unwrap();
        assert!(
            !content.contains("/static/js/htmx.min.js"),
            "generated main.rs must not hardcode /static/js/htmx.min.js, got:\n{content}"
        );
    }

    // --- issue #1593: the framework-owned file set `autumn upgrade` reconciles ---

    /// The fixed `autumn_version` `owned()` renders its fixtures with —
    /// deliberately independent of this crate's own `CARGO_PKG_VERSION`, so
    /// this test module does not need touching on every release. Assertions
    /// that check a rendered workflow does *not* pin to "this app's autumn
    /// version" must check against this constant, not `CARGO_PKG_VERSION`:
    /// the two happen to match today, but only this one is what `owned()`
    /// actually renders with.
    const FIXTURE_AUTUMN_VERSION: &str = "0.7.0";

    fn owned(opts: GenerateOptions) -> std::collections::BTreeMap<&'static str, String> {
        let vars = TemplateVars {
            project_name: "demo",
            crate_name: "demo",
            autumn_version: FIXTURE_AUTUMN_VERSION,
            rust_version: "1.88.0",
        };
        framework_owned_files(&vars, opts)
    }

    /// A workflow rendered for the member `demo` at `apps/demo`.
    fn member(path: &str) -> String {
        let files = owned(GenerateOptions::default());
        member_workflow(path, &files[path], "demo", "apps/demo").expect("a workflow")
    }

    #[test]
    fn a_member_ci_workflow_runs_in_the_member_directory() {
        let ci = member(".github/workflows/ci.yml");
        assert!(
            ci.contains("working-directory: \"apps/demo\"\n\njobs:"),
            "{ci}"
        );
        assert!(ci.contains("cargo fmt -p demo -- --check"), "{ci}");
        assert!(!ci.contains("cargo fmt --all"), "{ci}");
    }

    #[test]
    fn a_member_posture_gate_names_its_manifest_and_package() {
        let gate = member(".github/workflows/posture-gate.yml");
        assert!(
            gate.contains("POSTURE_MANIFEST: apps/demo/security-posture.json"),
            "{gate}"
        );
        assert!(
            gate.contains("POSTURE_AUDIT_FLAGS: --release -p demo"),
            "{gate}"
        );
    }

    #[test]
    fn a_member_rewrite_refuses_values_yaml_could_misread() {
        let files = owned(GenerateOptions::default());
        let ci = &files[".github/workflows/ci.yml"];
        assert_eq!(
            member_workflow(".github/workflows/ci.yml", ci, "demo", "a b: c"),
            None
        );
        assert_eq!(
            member_workflow(".github/workflows/ci.yml", ci, "de mo", "apps"),
            None
        );
        // An anchor that is not unique is a template bug, not a guess.
        let doubled = format!("{ci}\njobs:\n");
        assert_eq!(
            member_workflow(".github/workflows/ci.yml", &doubled, "demo", "apps"),
            None
        );
    }

    #[test]
    fn a_member_rewrite_leaves_other_files_alone() {
        let files = owned(GenerateOptions::default());
        assert_eq!(
            member_workflow("Dockerfile", &files["Dockerfile"], "demo", "apps/demo"),
            None
        );
    }

    #[test]
    fn framework_owned_set_covers_the_fullstack_scaffold() {
        let files = owned(GenerateOptions::default());
        for expected in [
            "autumn.toml",
            "Dockerfile",
            ".dockerignore",
            "build.rs",
            ".gitignore",
            ".env.example",
            ".github/workflows/ci.yml",
            ".github/workflows/posture-gate.yml",
            "rust-toolchain.toml",
            "rustfmt.toml",
            "clippy.toml",
            "tailwind.config.js",
            "static/css/input.css",
        ] {
            assert!(
                files.contains_key(expected),
                "missing {expected}: {:?}",
                files.keys()
            );
        }
    }

    /// The posture gate (issue #1624) ships turned on, and the pieces that make
    /// it a *gate* rather than a report are all present: the fresh manifest, a
    /// staleness check that compares postures rather than bytes, the
    /// base-branch side read out of git, an acknowledgment harvest restricted
    /// to accounts with real write permission, and a final step that actually
    /// fails the job.
    #[test]
    fn the_scaffolded_posture_gate_is_wired_end_to_end() {
        let files = owned(GenerateOptions::default());
        let workflow = files
            .get(".github/workflows/posture-gate.yml")
            .expect("scaffolded by default");

        assert!(workflow.contains("autumn routes audit $POSTURE_AUDIT_FLAGS --manifest"));
        assert!(workflow.contains("autumn routes posture diff"));
        assert!(
            workflow.contains("--allow-missing-base"),
            "first run must not break a repo"
        );
        assert!(workflow.contains("--ack-dir \"$RUNNER_TEMP/acks\""));
        // Every scratch path lives outside the PR-controlled checkout, so a
        // committed symlink cannot redirect one write onto another file.
        for scratch in [
            "base-posture.json",
            "committed-posture.json",
            "acks/",
            "posture-diff.md",
            "head-posture/posture-manifest.json",
        ] {
            assert!(
                !workflow.contains(&format!(" {scratch}"))
                    || workflow.contains(&format!("$RUNNER_TEMP/{scratch}")),
                "{scratch} must be written under $RUNNER_TEMP: {workflow}"
            );
        }
        assert!(
            workflow.contains("pull-requests: write"),
            "posting the diff needs it"
        );
        assert!(
            !workflow.contains("contents: write"),
            "the gate never writes to the repository"
        );
    }

    /// Who may acknowledge is the only authorization control in the feature, so
    /// it must ask GitHub for a real repository permission — `author_association`
    /// reports organization affiliation, and would let any org member with read
    /// access unblock a widening.
    #[test]
    fn the_scaffolded_gate_checks_real_write_permission_to_acknowledge() {
        let files = owned(GenerateOptions::default());
        let workflow = files
            .get(".github/workflows/posture-gate.yml")
            .expect("scaffolded");
        assert!(
            workflow.contains("collaborators/${login}/permission"),
            "must resolve each commenter's actual permission: {workflow}"
        );
        assert!(
            !workflow.contains("select(.author_association"),
            "affiliation is not permission — it may be named in a comment \
             explaining why, never used as the filter"
        );
        assert!(
            workflow.contains("admin|write|maintain"),
            "and only write-or-better may acknowledge"
        );
    }

    /// `routes posture` did not exist in every release. The verdict job
    /// tries the pinned CLI, falls back to the latest published release if
    /// that lacks the command (#2495), and — even then — says which command
    /// is missing rather than failing with an unknown-subcommand error, and
    /// fails rather than skipping, because a gate that waves a pull request
    /// through when its own tooling is too old is worse than a red one.
    #[test]
    fn the_gate_names_the_release_when_the_latest_cli_is_too_old() {
        let files = owned(GenerateOptions::default());
        let workflow = files
            .get(".github/workflows/posture-gate.yml")
            .expect("scaffolded");

        let verdict: &str = workflow
            .split("Security posture diff")
            .last()
            .expect("the verdict job");
        assert!(
            verdict.contains("routes posture --help"),
            "the verdict job must check the CLI can run this gate: {verdict}"
        );
        let probe = verdict
            .split("routes posture --help")
            .last()
            .expect("after the probe");
        assert!(
            probe.contains("::error::") && probe.contains("exit 1"),
            "and fail loudly rather than skipping: {probe}"
        );
    }

    /// Issue #2495: `routes posture` can postdate the release pinned to this
    /// app's own autumn-web version — but always installing "latest" instead
    /// would run this security gate under a CLI this project's own
    /// compatibility check (`doctor.rs::check_version_compat`) calls
    /// incompatible the moment a minor release ships, and the gap would only
    /// ever grow as later, unrelated releases ship. So the verdict job tries
    /// the pinned, compatible CLI first and, only when it lacks the command,
    /// probes forward through a bounded run of candidate releases — landing
    /// on the closest one that has it, not a moving "latest" — for that run
    /// alone. The `manifest` job — which compiles the pull request's own
    /// code — gets no such fallback at all: nothing in it may run under a
    /// CLI this project calls incompatible.
    #[test]
    fn the_posture_gate_prefers_the_pinned_compatible_cli_and_falls_back_only_when_needed() {
        let files = owned(GenerateOptions::default());
        let workflow = files
            .get(".github/workflows/posture-gate.yml")
            .expect("scaffolded");

        let pinned = format!("v{FIXTURE_AUTUMN_VERSION}");
        assert!(
            workflow.contains(&pinned),
            "posture-gate.yml must still install the CLI pinned to this \
             app's autumn version as the default: {workflow}"
        );

        let (build_job, verdict_job) = workflow
            .split_once("  posture:")
            .expect("two jobs: the build and the verdict");
        assert!(
            !build_job.contains("for bump in"),
            "the manifest job compiles the pull request's own code and must \
             never fall back to a CLI this project's own compatibility \
             check would call incompatible: {build_job}"
        );
        assert!(
            verdict_job.contains("for bump in") && verdict_job.contains("::warning::"),
            "the verdict job must probe forward for the closest compatible \
             release, visibly, when the pinned CLI lacks routes posture: \
             {verdict_job}"
        );
        assert!(
            !verdict_job.contains("trunk-dev"),
            "the fallback must land on a specific, bounded candidate \
             release, not an unbounded, ever-drifting \"latest\": \
             {verdict_job}"
        );
    }

    /// A missing baseline is a bootstrap exactly once — on the pull request
    /// that adds the gate. Once the workflow is on the base branch, "no
    /// baseline committed" is not a repository adopting the gate, it is a
    /// repository whose gate passes everything while the required check reads
    /// green. `autumn new` does not generate the manifest, so this is the
    /// default state of a project that scaffolds the workflow and stops.
    #[test]
    fn a_missing_baseline_bootstraps_only_while_the_gate_is_new() {
        let files = owned(GenerateOptions::default());
        let workflow = files
            .get(".github/workflows/posture-gate.yml")
            .expect("scaffolded");

        let step = workflow
            .split("Check the committed manifest is up to date")
            .last()
            .expect("the staleness step");
        let bootstrap = step
            .split("no posture baseline")
            .next()
            .expect("before the bootstrap notice");
        assert!(
            bootstrap.contains("posture-gate.yml") && bootstrap.contains("exit 1"),
            "a missing baseline must be fatal once the gate is on the base branch: {bootstrap}"
        );
    }

    /// The boundary between harvested comment bodies must not be forgeable
    /// (#2472). Each body goes to its own file, so the file boundary is the
    /// comment boundary and no text in a body can fake one.
    #[test]
    fn the_harvest_writes_one_file_per_comment() {
        let files = owned(GenerateOptions::default());
        let workflow = files
            .get(".github/workflows/posture-gate.yml")
            .expect("scaffolded");

        let harvest = workflow
            .split("- name: Harvest acknowledgments")
            .nth(1)
            .and_then(|rest| rest.split("- name:").next())
            .expect("the harvest step");
        let after_decode = harvest
            .split_once("base64 -d")
            .expect("bodies are decoded")
            .1;
        assert!(
            after_decode
                .trim_start_matches(|c: char| c.is_whitespace() || c == '\\')
                .starts_with("> \"$RUNNER_TEMP/acks/$(printf '%06d' \"$n\").md\""),
            "each decoded body must go to its own file: {harvest}"
        );
        assert!(
            !workflow.contains("autumn:ack-source"),
            "no in-band separator is left to forge: {workflow}"
        );
    }

    /// The gate audits the build that ships (#2472). Both scaffolded
    /// Dockerfiles build `--release`, so the gate audits `--release`. Every
    /// `routes audit` the workflow runs, or tells a user to run, uses the
    /// same flags, so the staleness check compares the same build.
    #[test]
    fn the_gate_audits_the_build_that_ships() {
        let files = owned(GenerateOptions::default());
        let workflow = files
            .get(".github/workflows/posture-gate.yml")
            .expect("scaffolded");

        for dockerfile in [
            include_str!("templates/Dockerfile.tmpl"),
            include_str!("templates/Dockerfile.api.tmpl"),
        ] {
            // `lines()` drops the `\r` of a CRLF checkout on Windows.
            assert!(
                dockerfile
                    .lines()
                    .any(|line| line == "RUN cargo build --release"),
                "the image build changed; change POSTURE_AUDIT_FLAGS with it"
            );
        }
        assert!(
            workflow.contains("\n  POSTURE_AUDIT_FLAGS: --release\n"),
            "{workflow}"
        );
        let commands: Vec<&str> = workflow
            .match_indices("autumn routes audit ")
            .map(|(at, _)| &workflow[at..])
            .collect();
        assert!(commands.len() >= 3, "{workflow}");
        for command in commands {
            assert!(
                command.starts_with("autumn routes audit $POSTURE_AUDIT_FLAGS "),
                "every audit must select the shipped build: {}",
                &command[..command.len().min(80)]
            );
        }
    }

    /// The job that compiles the pull request holds no write permission and
    /// reaches no verdict; the job that decides never runs application code.
    /// A malicious build script therefore cannot replace the binary that later
    /// computes the diff, resolves acknowledgments, and sets the exit code.
    #[test]
    fn the_gate_decides_in_a_job_that_never_compiles_the_pull_request() {
        let files = owned(GenerateOptions::default());
        let workflow = files
            .get(".github/workflows/posture-gate.yml")
            .expect("scaffolded");

        let (build_job, verdict_job) = workflow
            .split_once("  posture:")
            .expect("two jobs: the build and the verdict");

        assert!(
            build_job.contains("autumn routes audit $POSTURE_AUDIT_FLAGS --manifest"),
            "the build job is the one that compiles: {build_job}"
        );
        assert!(
            !build_job.contains("pull-requests: write"),
            "the job that runs the pull request's build scripts gets no write token"
        );
        assert!(
            !build_job.contains("routes posture diff"),
            "and reaches no verdict"
        );

        // Structural, not textual: the verdict job's comments and diagnostics
        // legitimately *mention* `autumn routes audit`. What it must not do is
        // set up a toolchain or run the build step.
        assert!(
            !verdict_job.contains("dtolnay/rust-toolchain")
                && !verdict_job.contains("Swatinem/rust-cache")
                && !verdict_job.contains("Build this commit's posture manifest"),
            "the verdict job must never compile the pull request: {verdict_job}"
        );
        assert!(verdict_job.contains("routes posture diff"));
        assert!(
            verdict_job.contains("download-artifact"),
            "it reads the manifest as data"
        );
        assert!(
            verdict_job.contains("Install the autumn CLI"),
            "with a CLI it installs itself, not one the build job left behind"
        );
    }

    /// Bypasses the review found, each pinned by the thing that closes it.
    #[test]
    fn the_scaffolded_gate_closes_its_own_bypasses() {
        let files = owned(GenerateOptions::default());
        let workflow = files
            .get(".github/workflows/posture-gate.yml")
            .expect("scaffolded");

        // Editing the gate in the pull request the gate is judging — but NOT
        // the pull request that adds it, which is how a repository adopts the
        // gate at all (`autumn upgrade --apply`).
        assert!(workflow.contains("Refuse a pull request that edits this gate"));
        assert!(
            workflow.contains("adding the security posture gate for the first time"),
            "the adoption pull request must not be refused by the gate it adds: {workflow}"
        );
        // Deleting the baseline in this pull request, to disarm the gate — and
        // to brick it for everyone afterwards.
        assert!(
            workflow.contains("this pull request deletes the committed posture baseline"),
            "deleting the baseline must fail here: {workflow}"
        );
        // …but a baseline that went missing some other way must not lock the
        // repository out, including the pull request that restores it.
        assert!(
            workflow.contains("::warning::${POSTURE_MANIFEST} existed on origin/"),
            "a baseline missing for other reasons warns and bootstraps: {workflow}"
        );
        // A failing build must not skip the verdict: GitHub counts a skipped
        // required check as satisfied.
        assert!(
            workflow.contains("if: always()") && workflow.contains("needs.manifest.result"),
            "the verdict job runs even when the manifest job fails: {workflow}"
        );
        // A base ref that is not in the checkout at all.
        assert!(workflow.contains("git rev-parse --verify"));
        // Rewriting someone else's comment, or updating a quoted copy.
        assert!(workflow.contains("github-actions[bot]"));
        // A failed comment post (every fork pull request) swallowing the verdict.
        assert!(
            workflow.contains("if: always() && steps.diff.outcome == 'success'"),
            "the verdict must survive a failed comment post: {workflow}"
        );
        // One comment per pull request, not one per concurrent push.
        assert!(workflow.contains("cancel-in-progress: true"));
        // One comment's unbalanced code fence swallowing another's marker:
        // each comment is its own file.
        assert!(workflow.contains("--ack-dir \"$RUNNER_TEMP/acks\""));
    }

    /// It is a workflow of its own, not another job on `ci.yml`: `ci.yml` must
    /// not acquire the `pull-requests: write` token the gate needs.
    #[test]
    fn the_posture_gate_does_not_widen_the_ci_workflows_permissions() {
        let files = owned(GenerateOptions::default());
        let ci = files.get(".github/workflows/ci.yml").expect("scaffolded");
        assert!(!ci.contains("pull-requests: write"));
    }

    /// Every flavor gets the same waivers. `managed-pg-bundled` no longer
    /// pulls `instant` (RUSTSEC-2024-0384), so no flavor waives it.
    #[test]
    fn the_advisory_policy_is_the_same_for_every_flavor() {
        let vars = TemplateVars {
            project_name: "demo",
            crate_name: "demo",
            autumn_version: "0.7.0",
            rust_version: "1.97.0",
        };
        let policy = render_template(templates::DENY_TOML, &vars);
        assert!(
            !policy.contains("autumn:bundled-pg-waiver"),
            "no template anchor may reach a generated project:\n{policy}"
        );
        assert!(
            !policy.contains("RUSTSEC-2024-0384"),
            "no flavor reaches `instant` any more:\n{policy}"
        );
        assert!(
            policy.contains("RUSTSEC-2023-0071"),
            "every flavor keeps the default `jwt` feature, so its tree reaches rsa through jsonwebtoken"
        );
    }

    /// The advisory policy is generated but deliberately *not* reconciled
    /// (issue #1600): its waiver list is the app author's, and a file the
    /// developer is asked to edit would come back as a conflict on every
    /// `autumn upgrade` — the same reason `Cargo.toml` is not owned either.
    #[test]
    fn the_advisory_policy_is_generated_but_not_framework_owned() {
        for opts in [
            GenerateOptions::default(),
            GenerateOptions {
                with_api: true,
                ..GenerateOptions::default()
            },
        ] {
            assert!(
                !owned(opts).contains_key("deny.toml"),
                "deny.toml carries the app's own waivers; reconciling it would \
                 conflict with every waiver its author adds"
            );
        }
        let tmp = TempDir::new().unwrap();
        generate("policy-owner-app", tmp.path()).unwrap();
        assert!(
            tmp.path().join("policy-owner-app/deny.toml").is_file(),
            "…but `autumn new` must still write it"
        );
    }

    #[test]
    fn framework_owned_set_never_reaches_into_src() {
        for opts in [
            GenerateOptions::default(),
            GenerateOptions {
                with_api: true,
                ..GenerateOptions::default()
            },
            GenerateOptions {
                with_i18n: true,
                with_seed: true,
                ..GenerateOptions::default()
            },
        ] {
            for path in owned(opts).keys() {
                assert!(
                    !path.starts_with("src/"),
                    "application source is out of bounds, got {path}"
                );
            }
        }
    }

    #[test]
    fn api_flavor_owns_no_css_or_tailwind() {
        let files = owned(GenerateOptions {
            with_api: true,
            ..GenerateOptions::default()
        });
        assert!(
            !files.contains_key("tailwind.config.js"),
            "{:?}",
            files.keys()
        );
        assert!(
            !files.contains_key("static/css/input.css"),
            "{:?}",
            files.keys()
        );
        // ...but it still owns the common set.
        assert!(files.contains_key("Dockerfile"));
        assert!(files.contains_key("build.rs"));
    }

    #[test]
    fn api_and_fullstack_render_different_dockerfiles_and_build_scripts() {
        let full = owned(GenerateOptions::default());
        let api = owned(GenerateOptions {
            with_api: true,
            ..GenerateOptions::default()
        });
        assert_ne!(full["Dockerfile"], api["Dockerfile"]);
        assert_ne!(full["build.rs"], api["build.rs"]);
    }

    #[test]
    fn i18n_option_is_reflected_in_the_owned_autumn_toml_and_dockerfile() {
        let plain = owned(GenerateOptions::default());
        let i18n = owned(GenerateOptions {
            with_i18n: true,
            ..GenerateOptions::default()
        });
        assert!(!plain["autumn.toml"].contains("[i18n]"));
        assert!(i18n["autumn.toml"].contains("[i18n]"));
        assert_ne!(plain["Dockerfile"], i18n["Dockerfile"]);
        // The unresolved anchors never survive into a generated file.
        assert!(!i18n["Dockerfile"].contains("__AUTUMN_I18N_BUILDER_COPY__"));
        assert!(!plain["Dockerfile"].contains("__AUTUMN_I18N_BUILDER_COPY__"));
    }

    #[test]
    fn daemon_and_bundled_pg_options_reach_the_owned_autumn_toml() {
        let daemon = owned(GenerateOptions {
            with_daemon: true,
            ..GenerateOptions::default()
        });
        assert!(
            daemon["autumn.toml"].contains("uses no database"),
            "{}",
            daemon["autumn.toml"]
        );
        let bundled = owned(GenerateOptions {
            with_daemon: true,
            with_bundled_pg: true,
            ..GenerateOptions::default()
        });
        assert!(
            bundled["autumn.toml"].contains("auto_migrate_in_production = true"),
            "{}",
            bundled["autumn.toml"]
        );
    }

    #[test]
    fn generated_project_files_match_the_framework_owned_rendering() {
        // The reconciler compares a project against `framework_owned_files`, so
        // a byte that `autumn new` writes differently is a permanent phantom
        // conflict. One renderer, one truth.
        let tmp = TempDir::new().unwrap();
        generate("owned-app", tmp.path()).unwrap();
        let vars = TemplateVars {
            project_name: "owned-app",
            crate_name: "owned_app",
            autumn_version: env!("CARGO_PKG_VERSION"),
            rust_version: crate::MSRV,
        };
        for (path, expected) in framework_owned_files(&vars, GenerateOptions::default()) {
            let actual = fs::read_to_string(tmp.path().join("owned-app").join(path))
                .unwrap_or_else(|e| panic!("{path} was not scaffolded: {e}"));
            assert_eq!(actual, expected, "{path} drifted from its rendering");
        }
    }

    #[test]
    fn a_new_project_records_the_release_that_scaffolded_it() {
        use crate::upgrade::scaffold::{MANIFEST_PATH, Manifest};

        let tmp = TempDir::new().unwrap();
        generate("provenance-app", tmp.path()).unwrap();
        let root = tmp.path().join("provenance-app");

        assert!(root.join(MANIFEST_PATH).is_file(), "no scaffold manifest");
        let manifest = Manifest::load(&root).expect("manifest parses");
        assert_eq!(manifest.version.as_deref(), Some(env!("CARGO_PKG_VERSION")));
        assert_eq!(manifest.options, GenerateOptions::default());
        // Every framework-owned file it just wrote has a baseline digest.
        for path in framework_owned_files(
            &TemplateVars {
                project_name: "provenance-app",
                crate_name: "provenance_app",
                autumn_version: env!("CARGO_PKG_VERSION"),
                rust_version: crate::MSRV,
            },
            GenerateOptions::default(),
        )
        .keys()
        {
            assert!(
                manifest.digests.contains_key(*path),
                "no baseline recorded for {path}"
            );
        }
    }

    #[test]
    fn the_recorded_manifest_records_the_options_the_project_was_made_with() {
        use crate::upgrade::scaffold::Manifest;

        let tmp = TempDir::new().unwrap();
        let opts = GenerateOptions {
            with_api: true,
            with_i18n: true,
            ..GenerateOptions::default()
        };
        generate_with("api-provenance", tmp.path(), opts).unwrap();
        let manifest = Manifest::load(&tmp.path().join("api-provenance")).unwrap();
        assert_eq!(manifest.options, opts);
    }

    #[test]
    fn a_new_project_reports_no_scaffold_drift() {
        // The tightest guarantee available: what `autumn new` writes today is
        // exactly what `autumn upgrade` calls current.
        use crate::upgrade::scaffold;

        let tmp = TempDir::new().unwrap();
        generate("fresh-app", tmp.path()).unwrap();
        let report = scaffold::plan(&tmp.path().join("fresh-app"), env!("CARGO_PKG_VERSION"));
        assert!(!report.drifted(), "{}", scaffold::render_text(&report));
    }

    #[test]
    fn the_scaffold_manifest_is_committed_not_ignored() {
        // A manifest that git ignores is a manifest that never reaches the
        // next checkout, which is the only place it has any value.
        let tmp = TempDir::new().unwrap();
        generate("committed-app", tmp.path()).unwrap();
        let gitignore = fs::read_to_string(tmp.path().join("committed-app/.gitignore")).unwrap();
        assert!(!gitignore.contains(".autumn"), "{gitignore}");
    }
}