umbral-cli 0.0.11

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

use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use umbral_casing::pascal_case_from_ident;

/// Error type for scaffolding operations. Wraps I/O and validation
/// failures with enough context for a user-facing message.
#[derive(Debug)]
pub enum ScaffoldError {
    /// The user-provided name isn't valid as a Rust crate / package
    /// identifier (must be ASCII alphanumeric or underscore/hyphen,
    /// can't start with a digit).
    InvalidName(String),
    /// The target directory already exists. We never overwrite —
    /// users move it aside or pick a different name.
    AlreadyExists(PathBuf),
    /// The chosen name collides with a built-in plugin name shipped
    /// by umbral. Both crates would compile, but the user would never
    /// be able to register both `.plugin(<their app>)` and
    /// `.plugin(<built-in>)` without an alias dance, and route /
    /// table-name collisions would land at boot. We reject the name
    /// up front to prevent this confusion.
    ReservedName(String),
    /// The chosen command name is already a framework built-in (`migrate`,
    /// `serve`, …) or a built-in plugin's command (`createsuperuser`, …).
    /// Registering it would shadow the real one at dispatch — the plugin/app
    /// layer is tried before the built-in clap parser — so `migrate` would
    /// stop migrating. Rejected at scaffold time, where the fix is free.
    ReservedCommandName(String),
    /// `startcommand --in <plugin>` named a plugin that isn't under
    /// `plugins/`. Carries the names that ARE there, so the message can
    /// list the real choices instead of just saying no.
    NoSuchPlugin {
        asked: String,
        available: Vec<String>,
    },
    /// `startcommand` needs a project to put the command in, and this
    /// directory has no `src/main.rs` (root) / `src/lib.rs` (plugin).
    NotAProject(PathBuf),
    /// I/O failure during file creation.
    Io(io::Error),
}

/// Built-in plugin names that `umbral startapp` refuses to scaffold over.
/// Adding a new built-in plugin? Add its name here so future
/// `startapp <name>` calls fail fast with a clear message.
pub const RESERVED_PLUGIN_NAMES: &[&str] = &[
    // Every built-in plugin name (each crate under plugins/) — a project
    // plugin named the same would compile but could never register
    // alongside the built-in without aliasing, and its tables would
    // collide at boot. Plus "app" (the reserved implicit-plugin name) and
    // "static" (the storage static side). Keep in sync with plugins/.
    "admin",
    "analytics",
    "app",
    "auth",
    "cache",
    "email",
    "graphql",
    "health",
    "livereload",
    "logs",
    "oauth",
    "openapi",
    "permissions",
    "playground",
    "realtime",
    "rest",
    "rls",
    "security",
    "sessions",
    "signals",
    "static",
    "storage",
    "tasks",
    "tenants",
];

/// Commands shipped by a **built-in plugin**. Unlike the framework's own
/// subcommands, these can't be read off a clap parser — they only exist
/// once the plugin is registered on an App, and `startcommand` runs
/// outside any App. So they're listed.
///
/// Adding a command to a built-in plugin? Add its name here, or a user's
/// `startcommand createsuperuser` will scaffold a command that silently
/// shadows the real one.
pub const RESERVED_PLUGIN_COMMAND_NAMES: &[&str] = &[
    "clearsessions",
    "collectstatic",
    "createsuperuser",
    "gen-client",
    "migrate_schemas",
    "startauthentication",
    "startpagination",
    "startpermission",
    "startthrottle",
    "tasks-beat",
    "tasks-worker",
];

/// Every command name a new command may not take: the framework's own
/// subcommands plus [`RESERVED_PLUGIN_COMMAND_NAMES`].
///
/// The framework half is read off the derived clap parser rather than
/// hand-listed, so adding a subcommand to `Command` in `lib.rs`
/// automatically reserves its name here. A hand-maintained copy would
/// have drifted the first time someone added one.
///
/// This matters because dispatch tries app/plugin commands *before* the
/// built-in parser (`lib.rs`, step 1 vs step 2). A user command named
/// `migrate` wouldn't collide loudly — it would just quietly take over,
/// and their migrations would stop applying.
pub fn reserved_command_names() -> Vec<String> {
    let mut names = crate::builtin_command_names();
    names.extend(RESERVED_PLUGIN_COMMAND_NAMES.iter().map(|s| s.to_string()));
    names.sort();
    names.dedup();
    names
}

impl std::fmt::Display for ScaffoldError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidName(s) => write!(
                f,
                "invalid name `{s}`: must be ASCII alphanumeric, underscore or hyphen, not starting with a digit",
            ),
            Self::AlreadyExists(p) => write!(
                f,
                "an app already exists at `{}`; move it aside or pick a different name",
                p.display()
            ),
            Self::ReservedName(s) => write!(
                f,
                "`{s}` is the name of a built-in umbral plugin; pick a different name to avoid conflicts at registration time. Reserved names: {}.",
                RESERVED_PLUGIN_NAMES.join(", ")
            ),
            Self::ReservedCommandName(s) => write!(
                f,
                "`{s}` is already an umbral command; pick another name. A command you register \
                 is dispatched BEFORE the built-in of the same name, so this one would shadow \
                 it. Taken names: {}.",
                reserved_command_names().join(", ")
            ),
            Self::NoSuchPlugin { asked, available } => {
                if available.is_empty() {
                    write!(
                        f,
                        "no plugin named `{asked}` — this project has no `plugins/` directory yet. \
                         Create one with `umbral startplugin <name>`, or place the command at the \
                         project root with `--in root`."
                    )
                } else {
                    write!(
                        f,
                        "no plugin named `{asked}`. Available: root, {}.",
                        available.join(", ")
                    )
                }
            }
            Self::NotAProject(p) => write!(
                f,
                "`{}` doesn't look like an umbral project — no `src/main.rs`. cd into your \
                 project directory, or pass `--path <dir>`.",
                p.display()
            ),
            Self::Io(e) => write!(f, "{e}"),
        }
    }
}

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

impl From<io::Error> for ScaffoldError {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}

/// The generator primitives in `umbral::codegen` fail with their own error;
/// `startcommand` reports through `ScaffoldError` like the rest of this
/// module. The variants line up one-for-one — they were the same errors, which
/// is why `codegen` exists.
impl From<umbral::codegen::CodegenError> for ScaffoldError {
    fn from(e: umbral::codegen::CodegenError) -> Self {
        use umbral::codegen::CodegenError as C;
        match e {
            C::InvalidName(s) => Self::InvalidName(s),
            C::AlreadyExists(p) => Self::AlreadyExists(p),
            C::NoSuchPlugin { asked, available } => Self::NoSuchPlugin { asked, available },
            C::NotAProject(p) => Self::NotAProject(p),
            C::Io(e) => Self::Io(e),
        }
    }
}

/// Report returned by both scaffolding functions: the paths written,
/// so the binary can print them to the user.
#[derive(Debug, Clone)]
pub struct ScaffoldReport {
    /// Root directory the scaffold landed in (project dir, or
    /// `plugins/<name>/`).
    pub root: PathBuf,
    /// All files written, relative to `root`.
    pub files: Vec<PathBuf>,
    /// Post-scaffold instructions for the user. The binary prints
    /// these after the file list.
    pub next_steps: Vec<String>,
    /// Whether the project's `Cargo.toml` was updated to include the
    /// new plugin as a path dependency. `None` means the operation
    /// wasn't attempted (e.g. `scaffold_project` doesn't auto-register).
    /// `Some(true)` = dep added, `Some(false)` = dep already present
    /// (idempotent — no duplicate written).
    pub cargo_toml_registered: Option<bool>,
    /// Whether the thing that was scaffolded is actually **registered** — the
    /// owner file (`main.rs` / the plugin's `lib.rs`) now reaches it.
    ///
    /// `false` when the tool could not edit the owner file and handed the user
    /// the lines instead. The caller MUST consult this before printing a
    /// success line: `startcommand` used to announce "Registered `x` on the App
    /// builder" purely because the user asked for `--in root`, whether or not
    /// it had managed to wire anything. The user read the success line, ran the
    /// command, and got `unknown command` — the CLI asserted a registration it
    /// knew it had not performed. `None` for scaffolders where registration
    /// isn't a concept (`startproject`).
    pub registered: Option<bool>,
}

/// Validate a name is acceptable as a Rust crate / module identifier.
///
/// Delegates to `umbral::codegen::validate_ident` — the same check every other
/// generator makes. This used to be a private copy of those rules WITHOUT the
/// Rust-keyword guard, which meant `umbral startcommand move` sailed through
/// validation and wrote `pub mod move;` into the user's registry: a syntax
/// error in a file they never touched. The copy also drifted from the one the
/// codegen tests assert on, so the suite read greener than the CLI shipped.
fn validate_name(name: &str) -> Result<(), ScaffoldError> {
    umbral::codegen::validate_ident(name).map_err(Into::into)
}

// `pascal_case` replaced by `umbral_casing::pascal_case_from_ident` (imported
// above) in the gaps2 #77 consolidation refactor.

/// Convert a name to its Rust identifier form (hyphens → underscores).
/// Rewrite git-deps to path-deps anchored at `umbral_repo`. Closes
/// BUG-17 in `bugs/tests/testBugs.md` — `umbral startproject --local
/// /path/to/umbral foo` now produces a `Cargo.toml` that path-deps
/// every umbral crate against the local checkout instead of the
/// published crates.io version. Comments + commented-out optional
/// plugin lines all flow through; any trailing descriptive comment
/// after the dependency spec is preserved.
///
/// Subdirectory mapping mirrors the umbral repo layout: facade
/// crates (`umbral`, `umbral-cli`, `umbral-core`, `umbral-macros`,
/// `umbral-testing`) live under `crates/`; everything else
/// (`umbral-auth`, `umbral-sessions`, `umbral-admin`, …) lives
/// under `plugins/`.
pub(crate) fn localize_deps(text: &str, umbral_repo: &Path) -> String {
    let repo_str = umbral_repo.display().to_string();
    let mut out = String::with_capacity(text.len());
    for line in text.split_inclusive('\n') {
        out.push_str(&rewrite_line(line, &repo_str));
    }
    out
}

/// Rewrite one `Cargo.toml` line: if it declares an umbral dependency
/// (`umbral-xxx = "<version>"` or `umbral-xxx = { ... }`, optionally
/// commented out with a leading `#`), replace the dependency spec with a
/// local `{ path = "<repo>/<subdir>/<crate>" }`. Any other line is
/// returned unchanged, including the otel example comment whose left
/// side is prose, not a bare crate name.
fn rewrite_line(line: &str, repo: &str) -> String {
    // Find the LHS crate name. Strip a leading `#` (commented-out
    // optional plugins) and whitespace, then take the substring up to
    // the first `=`.
    let body_start = line
        .char_indices()
        .find(|(_, c)| !matches!(*c, '#' | ' ' | '\t'))
        .map(|(i, _)| i)
        .unwrap_or(0);
    let body = &line[body_start..];
    let Some(eq_idx) = body.find('=') else {
        return line.to_string();
    };
    let crate_name = body[..eq_idx].trim();
    // Only bare umbral crate names get localized (skips prose comments
    // like the otel example, whose LHS contains spaces/backticks).
    if !crate_name.starts_with("umbral") || crate_name.contains(|c: char| c.is_whitespace()) {
        return line.to_string();
    }
    // The dependency spec follows `=`: either a version string
    // (`"0.0.1"`) or an inline table (`{ ... }`). Find where it ends so
    // any trailing descriptive `# comment` survives verbatim.
    let after_eq = &body[eq_idx + 1..];
    let spec_offset = after_eq.len() - after_eq.trim_start().len();
    let spec = after_eq.trim_start();
    let spec_len = if let Some(rest) = spec.strip_prefix('"') {
        match rest.find('"') {
            Some(i) => 1 + i + 1,
            None => return line.to_string(),
        }
    } else if spec.starts_with('{') {
        match spec.find('}') {
            Some(i) => i + 1,
            None => return line.to_string(),
        }
    } else {
        return line.to_string();
    };
    let spec_start = body_start + eq_idx + 1 + spec_offset;
    let spec_end = spec_start + spec_len;
    let subdir = match crate_name {
        "umbral" | "umbral-cli" | "umbral-core" | "umbral-macros" | "umbral-testing" => "crates",
        _ => "plugins",
    };
    let path = format!("{repo}/{subdir}/{crate_name}");
    let prefix = &line[..spec_start];
    let suffix = &line[spec_end..];
    format!("{prefix}{{ path = \"{path}\" }}{suffix}")
}

fn rust_ident(name: &str) -> String {
    name.replace('-', "_")
}

/// A random 64-hex-char dev secret key, unique per scaffold (audit_2
/// macros-cli #7). Replaces the old shared `umbral-insecure-dev-key-change-me`
/// literal so two scaffolded projects never share a key. Dev-only — production
/// still requires a real key (the boot guard rejects a default/dev key under
/// `environment = "Prod"`). Entropy comes from the OS-seeded `RandomState`; a
/// crypto dependency isn't warranted for a dev-only, prod-boot-guarded value.
fn random_dev_secret_key() -> String {
    use std::hash::{BuildHasher, Hasher};
    // Each `RandomState::new()` pulls a fresh OS-seeded random state, so the
    // key differs across scaffold runs. Fold four seeded hashes into 64 hex
    // chars (256 bits of key material).
    let seed = std::collections::hash_map::RandomState::new();
    let mut out = String::with_capacity(64);
    for i in 0..4u64 {
        let mut h = seed.build_hasher();
        h.write_u64(i);
        h.write_u64(i.wrapping_mul(0x9E37_79B9_7F4A_7C15));
        out.push_str(&format!("{:016x}", h.finish()));
    }
    out
}
/// Where the generated templates point their "Docs" links.
const DOCS_URL: &str = "https://dalmasonto.github.io/umbral/docs/v0.0.1";

/// Write a new umbral project at `parent_dir/<name>/`.
///
/// The generated layout is a complete blog-style demo that exercises every
/// major umbral surface: models with FK, migrations on boot, auth + sessions,
/// `login_required`, REST with filters, admin, templates, transactions, and
/// custom error pages.
///
/// The layout follows the per-concern convention we landed on in
/// `examples/shop` (gaps2 #8): `main.rs` reads like a table of contents
/// and every subsystem lives behind a `mod.rs` re-export/orchestrator
/// layer, so the project opens to something that scales past 1000 lines.
///
/// ```text
/// <name>/
/// ├── Cargo.toml
/// ├── umbral.toml
/// ├── .env
/// ├── .env.example
/// ├── .gitignore
/// ├── README.md
/// ├── src/
/// │   ├── main.rs           # App builder + route table + boot helpers
/// │   ├── views/
/// │   │   ├── mod.rs        # re-export layer (handlers return ApiError)
/// │   │   └── public.rs     # public/unauth handlers
/// │   ├── seed/
/// │   │   ├── mod.rs        # `all()` orchestrator (pins dependency order)
/// │   │   └── credentials.rs# idempotent dev-superuser seed
/// │   └── widgets/
/// │       ├── mod.rs        # per-kind re-export layer
/// │       └── cards.rs      # one builtin admin dashboard widget
/// ├── plugins/
/// │   ├── .gitkeep          # local app plugins land here (umbral startapp)
/// │   └── README.md
/// └── templates/
///     ├── base.html
///     ├── home.html
///     ├── dashboard.html
///     ├── 404.html
///     └── 500.html
/// ```
///
/// `main.rs` wires `umbral_cli::dispatch(app)` so the project's binary
/// hosts the management commands. These directories are a *recommended*
/// convention, not a requirement — the runtime reads `main.rs` directly
/// and doesn't care whether handlers live in `views/`, `handlers/`, or
/// inline.
/// Walk up from `start` looking for an umbral source checkout.
///
/// Identified by `crates/umbral-core/Cargo.toml`, which no consumer project has.
fn find_umbral_checkout(start: &Path) -> Option<PathBuf> {
    start
        .ancestors()
        .find(|d| d.join("crates/umbral-core/Cargo.toml").is_file())
        .map(Path::to_path_buf)
}

/// Warn when `startproject` is run from inside the umbral repo WITHOUT `--local`.
///
/// The generated `Cargo.toml` pins `env!("CARGO_PKG_VERSION")` — the CLI's own version, which
/// during development is the LAST PUBLISHED release. So a `cargo run -p umbral-cli --
/// startproject foo` from a HEAD checkout writes `umbral = "<last release>"` and then
/// generates code against **main's** API. Any surface added since that release makes the new
/// project fail to compile, and the failure looks like a bug in the framework rather than a
/// version skew.
///
/// It heals itself at release (the scaffold and the libs ship together), so end users of a
/// published CLI never see it. The only person who hits it is a contributor testing their own
/// change — which is exactly the person who most needs `--local`, and exactly the person the
/// silence misleads. gaps3 #65.
fn warn_if_run_from_a_source_checkout(name: &str, parent_dir: &Path) {
    let from_cwd = std::env::current_dir()
        .ok()
        .and_then(|d| find_umbral_checkout(&d));
    let Some(repo) = from_cwd.or_else(|| find_umbral_checkout(parent_dir)) else {
        return;
    };
    let version = env!("CARGO_PKG_VERSION");
    let repo = repo.display();
    eprintln!(
        "warning: running `startproject` from an umbral source checkout ({repo}) without `--local`."
    );
    eprintln!();
    eprintln!(
        "  The new project will depend on the PUBLISHED umbral {version}, while your checkout is on"
    );
    eprintln!(
        "  whatever you have got. Any framework surface you have added since {version} was released"
    );
    eprintln!(
        "  will be missing, and the generated project will fail to compile against it — looking for"
    );
    eprintln!("  all the world like a framework bug rather than a version skew.");
    eprintln!();
    eprintln!("  To build against this checkout instead:");
    eprintln!();
    eprintln!("      umbral startproject {name} --local {repo}");
    eprintln!();
}

pub fn scaffold_project(
    name: &str,
    parent_dir: &Path,
    local_umbral_repo: Option<&Path>,
) -> Result<ScaffoldReport, ScaffoldError> {
    validate_name(name)?;

    if local_umbral_repo.is_none() {
        warn_if_run_from_a_source_checkout(name, parent_dir);
    }

    let root = parent_dir.join(name);
    if root.exists() {
        return Err(ScaffoldError::AlreadyExists(root));
    }

    fs::create_dir_all(&root)?;
    fs::create_dir_all(root.join("src"))?;
    fs::create_dir_all(root.join("src/views"))?;
    fs::create_dir_all(root.join("src/seed"))?;
    fs::create_dir_all(root.join("src/widgets"))?;
    fs::create_dir_all(root.join("plugins"))?;
    fs::create_dir_all(root.join("templates"))?;

    let crate_name = rust_ident(name);
    let mut files = Vec::new();

    // ------------------------------------------------------------------ //
    // Cargo.toml                                                           //
    // ------------------------------------------------------------------ //
    let version = env!("CARGO_PKG_VERSION");
    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"

[dependencies]

# ----- Framework core (always required) ------------------------------------
umbral         = "{version}"
umbral-cli     = "{version}"

# ----- Active by default ---------------------------------------------------
# What the generated `src/main.rs` wires in. Comment any of these out only
# if you also remove the matching `.plugin(...)` line.
umbral-auth     = "{version}"
umbral-sessions = "{version}"
umbral-admin    = "{version}"
umbral-rest     = "{version}"
umbral-openapi  = "{version}"
umbral-security = "{version}"
# Observability init helper (structured JSON logging). Enable the `otel`
# feature to ALSO export OpenTelemetry traces over OTLP to a collector
# (Jaeger/Tempo/Honeycomb): `umbral-logs = {{ version = "{version}", features = ["otel"] }}`.
umbral-logs     = "{version}"
# Serves ./static at /static — including the compiled Tailwind bundle this
# project ships. Not optional: the SecurityPlugin's CSP blocks third-party
# script/style CDNs, so an app must serve its own assets.
umbral-storage  = "{version}"

# ----- Available built-ins (uncomment + register in main.rs to enable) -----
# umbral-playground   = "{version}"  # Interactive API playground UI (think mini-Postman) at /playground/.
# umbral-health       = "{version}"  # Liveness + readiness probes at /healthz and /ready. Zero config.
# umbral-tasks        = "{version}"  # DB-backed background task queue with a worker process.
# umbral-graphql      = "{version}"  # A real GraphQL API derived from your models. Expose per model.
# umbral-realtime     = "{version}"  # Server-Sent Events + WebSocket push, with model-change subscriptions.
# umbral-oauth        = "{version}"  # Social login / account connection (Google, GitHub). See auth/oauth docs.
# umbral-permissions  = "{version}"  # ContentType + Group + Permission model.
# umbral-tenants      = "{version}"  # Multi-tenant schema routing (Postgres).
# umbral-rls          = "{version}"  # Postgres row-level security policy registration.
# umbral-cache        = "{version}"  # Per-request caching helper.
# umbral-email        = "{version}"  # SMTP + MIME email composer + sender.
# umbral-analytics    = "{version}"  # Pageview / event analytics (needs an API key).
# umbral-signals      = "{version}"  # Pre/post save/delete signal dispatch.
# umbral-livereload   = "{version}"  # Dev-only browser live-reload (SSE push + file watcher). Add `.plugin(LiveReloadPlugin::new())`.

# ----- Third-party + framework runtime deps --------------------------------
tokio = {{ version = "1", features = ["macros", "rt-multi-thread"] }}
tracing-subscriber = {{ version = "0.3", features = ["env-filter"] }}
serde = {{ version = "1", features = ["derive"] }}
chrono = {{ version = "0.4", features = ["serde"] }}
sqlx = {{ version = "0.8", features = ["macros", "sqlite", "postgres", "chrono", "runtime-tokio"] }}

# Once you `umbral startapp <plugin>` or `umbral startplugin <plugin>`, add
# the plugin crate here:
# {crate_name}-posts = {{ path = "plugins/posts" }}
"#
    );
    // BUG-17 fix: when `--local <PATH>` is set, rewrite every umbral
    // dependency to a `{ path = "<umbral>/<sub>/<crate>" }` form
    // anchored at the supplied umbral-repo path. Comments, active and
    // commented-out dep lines all go through. Without the flag, the
    // published crates.io version deps are kept verbatim, which is what
    // a user installing umbral from crates.io gets.
    let cargo_toml = match local_umbral_repo {
        Some(repo) => localize_deps(&cargo_toml, repo),
        None => cargo_toml,
    };
    write_file(&root, "Cargo.toml", &cargo_toml, &mut files)?;

    // ------------------------------------------------------------------ //
    // src/main.rs — the demo wires every umbral surface in ~100 lines      //
    // ------------------------------------------------------------------ //
    let main_rs = format!(
        r#"//! {name} — application entrypoint.
//!
//! This `main.rs` reads like a table of contents: the App builder lists
//! every model, plugin, and route, and the per-concern submodules below
//! own the detail. As the project grows you slot new handlers into
//! `views/`, new seed steps into `seed/`, and new dashboard widgets into
//! `widgets/` — `main.rs` stays a thin wiring layer.
//!
//!   src/
//!     main.rs      — App builder + route table + boot helpers (this file)
//!     views/       — HTTP handlers, one file per resource grouping
//!     seed/        — first-run data, `seed::all()` pins dependency order
//!     widgets/     — admin dashboard widgets, one file per kind
//!     ../plugins/  — local app plugins (`umbral startapp <name>`)
//!
//! Run with:
//!   cargo run -- migrate   # apply pending migrations (run once after checkout)
//!   cargo run -- serve     # boot the HTTP server
//!
//! Other management commands:
//!   cargo run -- makemigrations
//!   cargo run -- showmigrations
//!   cargo run -- createsuperuser

// --- Per-concern modules (the table of contents) ---------------------------
mod seed;
mod views;
mod widgets;

use umbral::prelude::*;
use umbral::web::{{SlashRedirect}};
use umbral_auth::{{AuthPlugin, AuthUser, login_required_html}};
use umbral_sessions::SessionsPlugin;
use umbral_admin::AdminPlugin;
use umbral_rest::{{RestPlugin, ResourceConfig}};
use umbral_openapi::OpenApiPlugin;
use umbral_security::SecurityPlugin;
use umbral_storage::StoragePlugin;

// ---------------------------------------------------------------------------
// Models
// ---------------------------------------------------------------------------

/// A blog post. `author` is a FK to the built-in `AuthUser` model — the
/// migration engine emits `REFERENCES "auth_user"("id")` automatically.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow, Model)]
pub struct Post {{
    pub id: i64,
    pub title: String,
    pub body: String,
    pub published: bool,
    pub author: ForeignKey<AuthUser>,
    pub created_at: Option<chrono::DateTime<chrono::Utc>>,
}}

// ---------------------------------------------------------------------------
// App wiring
// ---------------------------------------------------------------------------

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {{
    // Observability: structured logging + (under the `otel` feature on
    // `umbral-logs`) OpenTelemetry OTLP trace export. Reads RUST_LOG,
    // UMBRAL_LOG_FORMAT=json, OTEL_EXPORTER_OTLP_ENDPOINT, OTEL_SERVICE_NAME.
    // Keep the guard alive for the whole program: it flushes the OTLP
    // exporter on drop so trailing spans aren't lost at exit.
    let _obs = umbral_logs::observability::init(umbral_logs::ObservabilityConfig::from_env());

    let settings = Settings::from_env()?;
    let pool = umbral::db::connect(&settings.database_url).await?;

    let app = App::builder()
        .settings(settings)
        .database("default", pool)

        // --- Models ----------------------------------------------------------
        // AuthUser and Session are contributed by their plugins below.
        // List your own models here.
        .model::<Post>()

        // --- Plugins ---------------------------------------------------------
        // Auth: user table, password hashing, createsuperuser command.
        // `with_form_routes()` mounts the POST form-action routes under
        // `/auth` (login / logout / signup / …) that the login page below
        // submits to; `AuthPlugin::new()` is the no-turbofish constructor
        // over the built-in AuthUser (gaps4 #45).
        .plugin(AuthPlugin::new().with_form_routes())
        // Sessions: session table + cookie middleware.
        .plugin(SessionsPlugin::default())
        // Admin: auto CRUD UI at /admin/ for every registered model.
        // The dashboard mounts one builtin widget from `widgets/` so a
        // fresh admin isn't empty — add your own with `.dashboard_section`.
        .plugin(
            AdminPlugin::default()
                .dashboard_section(widgets::cards::overview_section()),
        )
        // REST: JSON CRUD + filtering at /api/<table>/.
        // The Post resource has query-string filtering enabled so
        // GET /api/post/?published=true works out of the box.
        .plugin(
            RestPlugin::default()
                .resource(ResourceConfig::new("post")),
        )
        // OpenAPI: Swagger UI at /openapi/ (override with
        // `.at("/api/docs")` if you prefer a different mount).
        .plugin(OpenApiPlugin::new())
        // Static files: serves ./static at /static, which is where the compiled
        // Tailwind bundle lives. Use `{{ static('css/app.css') }}` in templates
        // rather than a hardcoded path — in production it resolves through the
        // hashed-asset manifest so you get cache-busting for free.
        //
        // The same plugin also gives you uploaded-file storage (local FS or S3)
        // when you add a FileField / ImageField: `.media("/media", "./media")`.
        .plugin(StoragePlugin::new().static_files("/static", "./static"))
        // Security (on by default): CSRF + clickjacking/HSTS hardening
        // headers across the app. `/api` is exempt so token-authenticated
        // JSON clients can POST without a browser form CSRF cookie.
        .plugin(SecurityPlugin::new().csrf_exempt(["/api"]))

        // --- Templates -------------------------------------------------------
        .templates_dir("templates")
        .not_found_template("404.html")
        .server_error_template("500.html")

        // Redirect /foo → /foo/  (append trailing slash).
        .slash_redirect(SlashRedirect::Append)

        // --- Routes ----------------------------------------------------------
        // The Routes builder records each (method, path) pair as you
        // declare it, so the dev-mode 404 panel surfaces them without
        // a parallel declaration list. Handlers live in `views/`; this
        // table is the URL conf — open `views/mod.rs` to see them all.
        // Per-route middleware (here, login_required_html on /dashboard)
        // goes through the explicit `.layered(method, path, mr)` form so
        // the layer attaches just to that handler — not all routes.
        .routes(
            Routes::new()
                // Public home page.
                .get("/", views::public::home)
                // API: list posts as JSON (no auth required — demo).
                .get("/api/posts", views::public::api_list_posts)
                // Login page. The form POSTs to /auth/login (mounted by
                // `with_form_routes()` above); on success it redirects to
                // `?next`. This is the page login_required_html sends
                // anonymous visitors to.
                .get("/login", views::public::login)
                // Dashboard: only reachable when logged in. The
                // login_required_html("/login") layer issues a 302 to
                // /login?next=/dashboard/ for anonymous visitors.
                .layered(
                    "GET",
                    "/dashboard",
                    get(views::public::dashboard).layer(login_required_html("/login")),
                ),
        )
        // Auto-migrate + seed on `serve` (gaps4 #47) so `cargo run -- serve`
        // Just Works against a fresh database, and NEVER during
        // `makemigrations` / `migrate` / any other subcommand. In Dev,
        // auto_migrate_on_serve also autodetects (the makemigrations half);
        // in Prod it only applies pending migrations. `seed::all()` is
        // idempotent — see seed/mod.rs.
        .auto_migrate_on_serve()
        .seed_on_serve(seed::all)

        // `build_deferred`, not `build`: it wires everything (pools, model
        // registry, router, system checks) but leaves each plugin's `on_ready`
        // hook unfired. Those hooks seed content and backfill rows, so they must
        // not run during `migrate` — the command whose whole job is to create the
        // tables they write to. `dispatch` fires them once it has read argv.
        .build_deferred()?;

    umbral_cli::dispatch(app).await
}}

"#
    );
    write_file(&root, "src/main.rs", &main_rs, &mut files)?;

    // ------------------------------------------------------------------ //
    // src/views/mod.rs — re-export layer (handlers return ApiError)        //
    // ------------------------------------------------------------------ //
    let views_mod_rs = r#"//! HTTP handlers, split by concern — the re-export / discoverability
//! layer. Open this file and you see the whole web surface in a few
//! lines: one submodule per resource grouping.
//!
//! Submodules:
//!   - `public` — pages anyone can hit (home, JSON listings).
//!
//! Add `pub mod account;` here when auth-gated views land (dashboard,
//! /me, staff-only pages), then re-export it below so `main.rs` keeps
//! referencing handlers as `views::public::home` without caring which
//! file owns each one. This is a recommended convention, not a rule —
//! the router reads handlers directly, so you're free to restructure.

pub mod public;

// No `internal_error` helper, on purpose.
//
// Handlers return `Result<_, umbral::web::ApiError>` and use a bare `?`. ApiError
// converts from sqlx / WriteError / TemplateError, logs the real cause server-side, and
// returns an opaque 500 — so a missing table or a SQL fragment never reaches the browser.
// The `(StatusCode, String)` + `err.to_string()` pattern does the opposite.
"#;
    write_file(&root, "src/views/mod.rs", views_mod_rs, &mut files)?;

    // ------------------------------------------------------------------ //
    // src/views/public.rs — public/unauth handlers                        //
    // ------------------------------------------------------------------ //
    let views_public_rs = r#"//! Public storefront views — anyone can hit these, no auth required.
//!
//! Every handler returns `Result<_, ApiError>` and lets `?` do the work. `ApiError`
//! converts from a database error, a `WriteError` and a template error, so there is no
//! per-handler error helper to write — and a 500 logs the real cause server-side while
//! the client gets an opaque message. Never hand `err.to_string()` to a browser: that is
//! how table names and SQL fragments end up on someone else's screen.

use umbral::prelude::*;
use umbral::templates::context;

use crate::Post;
use crate::post;

/// Home page. Counts published posts and renders home.html.
pub async fn home() -> Result<Html<String>, ApiError> {
    let post_count = Post::objects()
        .filter(post::PUBLISHED.eq(true))
        .count()
        .await?;

    let body = umbral::templates::render("home.html", &context!(post_count))?;
    Ok(Html(body))
}

/// JSON list of all posts — demonstrates the ORM QuerySet.
pub async fn api_list_posts() -> Result<Json<Vec<Post>>, ApiError> {
    let posts = Post::objects().order_by(post::ID.desc()).fetch().await?;
    Ok(Json(posts))
}

/// Login page. Renders the form in `login.html`; the form POSTs to the
/// auth plugin's `/auth/login` action. The `?next` query param (set by
/// the `login_required_html` layer when it bounced an anonymous visitor
/// here) is passed through to the template so a successful login returns
/// the user to where they were headed.
pub async fn login(umbral::web::Query(q): umbral::web::Query<LoginQuery>) -> Result<Html<String>, ApiError> {
    let next = q.next.unwrap_or_else(|| "/dashboard".to_string());
    let body = umbral::templates::render("login.html", &context!(next))?;
    Ok(Html(body))
}

/// `?next=<path>` on the login page — where to return after signing in.
#[derive(serde::Deserialize)]
pub struct LoginQuery {
    pub next: Option<String>,
}

/// Dashboard: only reachable when logged in (see the `login_required_html`
/// layer in `main.rs`). The `LoggedIn<AuthUser>` extractor supplies the
/// current user — the layer already checked the session, so this is a
/// cheap field read, not a second DB query.
pub async fn dashboard(
    user: umbral_auth::LoggedIn<umbral_auth::AuthUser>,
) -> Result<Html<String>, ApiError> {
    // Demonstrates a transaction: fetch the user's post list atomically.
    let user_id = user.id;
    let my_posts = umbral::transaction(|tx| {
        Box::pin(async move {
            Post::objects()
                .filter(post::AUTHOR.eq(user_id))
                .on_tx(tx)
                .fetch()
                .await
        })
    })
    .await?;

    let body = umbral::templates::render("dashboard.html", &context!(user, my_posts))?;
    Ok(Html(body))
}
"#;
    write_file(&root, "src/views/public.rs", views_public_rs, &mut files)?;

    // ------------------------------------------------------------------ //
    // src/seed/mod.rs — the seed orchestrator                              //
    // ------------------------------------------------------------------ //
    let seed_mod_rs = r#"//! Seed orchestrator — the re-export / dependency-order layer. One
//! file per concern keeps each step small and focused; `all()` pins
//! the order in which they run.
//!
//! Submodules:
//!   - `credentials` — first-run dev superuser so you can log in to
//!                     /admin/ without a manual `createsuperuser`.
//!
//! Add a `pub mod <concern>;` here for each new seed step, then call it
//! from `all()` in dependency order (e.g. catalog rows before the orders
//! that reference them). The order in `all()` doubles as documentation
//! of which step depends on which.

pub mod credentials;

/// Run every seed step in the right order. Each step is idempotent
/// (short-circuits on a non-empty table), so calling `all()` on a
/// partially-seeded DB tops up the missing pieces without re-inserting.
pub async fn all() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    credentials::test_credentials().await?;
    Ok(())
}
"#;
    write_file(&root, "src/seed/mod.rs", seed_mod_rs, &mut files)?;

    // ------------------------------------------------------------------ //
    // src/seed/credentials.rs — idempotent dev superuser                  //
    // ------------------------------------------------------------------ //
    let seed_credentials_rs = r#"//! First-run convenience: mints a dev superuser `admin` when no users
//! exist yet — but ONLY in the Dev environment AND only when you opt in
//! by exporting a password. There is deliberately NO hardcoded default
//! password: a bare `./app` launch against an empty production database
//! must never plant a known-credential admin account.
//!
//! To auto-seed the dev superuser:
//!
//!   UMBRAL_DEV_ADMIN_PASSWORD=your-dev-password cargo run
//!
//! Otherwise the first boot prints guidance to run
//! `cargo run -- createsuperuser` and seeds nothing. Idempotent —
//! subsequent boots find the user and stay quiet.

use umbral::Environment;
use umbral_auth::AuthUser;

/// Env var that opts a fresh install into the dev-superuser seed and
/// supplies its password. Unset => no seed (print guidance instead).
const DEV_ADMIN_PASSWORD_ENV: &str = "UMBRAL_DEV_ADMIN_PASSWORD";

pub async fn test_credentials() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    // Never mint a dev superuser outside the Dev environment — belt and
    // suspenders on top of the caller only running us on a bare launch.
    if umbral::settings::get().environment != Environment::Dev {
        return Ok(());
    }

    // Idempotent: bail out the moment any user exists.
    if AuthUser::objects().count().await? > 0 {
        return Ok(());
    }

    // Opt-in only: without an explicit password we plant nothing. This
    // is what keeps a known `admin`/`admin` account off every fresh DB.
    let password = match std::env::var(DEV_ADMIN_PASSWORD_ENV) {
        Ok(p) if !p.is_empty() => p,
        _ => {
            eprintln!();
            eprintln!("No users yet, and no dev superuser was seeded. To create one:");
            eprintln!("  • interactive:  cargo run -- createsuperuser");
            eprintln!("  • auto on boot: set {DEV_ADMIN_PASSWORD_ENV}=... and restart");
            eprintln!("                  (Dev environment only; never seeds in Prod)");
            eprintln!();
            return Ok(());
        }
    };

    umbral_auth::create_superuser("admin", "admin@example.com", &password)
        .await
        .map_err(|e| -> Box<dyn std::error::Error + Send + Sync> { Box::new(e) })?;

    eprintln!();
    eprintln!("======================================================================");
    eprintln!(" DEV SUPERUSER seeded (Dev environment, {DEV_ADMIN_PASSWORD_ENV} set)");
    eprintln!("----------------------------------------------------------------------");
    eprintln!(" Username : admin");
    eprintln!(" Password : (the value of {DEV_ADMIN_PASSWORD_ENV})");
    eprintln!(" Log in   : http://127.0.0.1:8000/admin/");
    eprintln!(" Remove or edit src/seed/credentials.rs before shipping.");
    eprintln!("======================================================================");
    eprintln!();

    Ok(())
}
"#;
    write_file(
        &root,
        "src/seed/credentials.rs",
        seed_credentials_rs,
        &mut files,
    )?;

    // ------------------------------------------------------------------ //
    // src/widgets/mod.rs — per-kind re-export layer                       //
    // ------------------------------------------------------------------ //
    let widgets_mod_rs = r#"//! Admin dashboard widgets — the re-export / discoverability layer,
//! grouped by kind so each file stays small and focused on one
//! rendering shape.
//!
//! Submodules:
//!   - `cards` — KPI tiles + dashboard sections.
//!
//! Add `pub mod charts;`, `pub mod tables;`, etc. as your dashboard
//! grows, then re-export the builders so `main.rs` calls them as
//! `widgets::cards::overview_section()` without knowing which file owns
//! each one. A recommended convention — restructure freely.

pub mod cards;
"#;
    write_file(&root, "src/widgets/mod.rs", widgets_mod_rs, &mut files)?;

    // ------------------------------------------------------------------ //
    // src/widgets/cards.rs — one builtin dashboard widget so a fresh      //
    // admin isn't empty                                                    //
    // ------------------------------------------------------------------ //
    let widgets_cards_rs = r#"//! Dashboard widget builders. This starter re-exports one framework
//! builtin so a fresh `/admin/` dashboard isn't empty; replace it with
//! your own KPI tiles as the app grows.
//!
//! A widget is a `Widget` value handed to `WidgetSection::widget(...)`.
//! Each section becomes one row of tiles on the admin dashboard. See
//! `documentation/docs/v0.0.1/admin/` and the `examples/shop/src/widgets`
//! reference for the data-closure pattern that hits the ORM.

use umbral_admin::WidgetSection;

/// One dashboard section wiring two framework builtins: a model-count
/// tile and a recent-users list. Mounted from `main.rs` via
/// `.dashboard_section(widgets::cards::overview_section())`.
pub fn overview_section() -> WidgetSection {
    WidgetSection::new("Overview")
        .subtitle("Framework-wide health + recent activity")
        .widget(umbral_admin::builtin_total_models_widget().with_span(8, 2))
        .widget(umbral_admin::builtin_recent_users_widget().with_span(4, 2))
}
"#;
    write_file(&root, "src/widgets/cards.rs", widgets_cards_rs, &mut files)?;

    // ------------------------------------------------------------------ //
    // plugins/ — empty home for local app plugins (umbral startapp)        //
    // ------------------------------------------------------------------ //
    write_file(&root, "plugins/.gitkeep", "", &mut files)?;
    let plugins_readme = "# plugins/\n\nLocal plugins go here; create one with `umbral startplugin <name>`.\nEach is its own crate (`lib.rs` + `models.rs` + `handlers.rs`) and is\nauto-wired into this project's `Cargo.toml` `[dependencies]`.\n";
    write_file(&root, "plugins/README.md", plugins_readme, &mut files)?;

    // ------------------------------------------------------------------ //
    // umbral.toml                                                           //
    // ------------------------------------------------------------------ //
    // A random dev secret, unique per scaffolded project (audit_2 macros-cli #7)
    // — shared into both umbral.toml and the working .env below so they match.
    let dev_secret = random_dev_secret_key();
    let umbral_toml = format!(
        r#"# umbral settings for {name}.
# Environment variables (UMBRAL_*) override these at runtime.
# See umbral::settings for the full schema.

database_url = "sqlite://{name}.db?mode=rwc"

# Bind address for `cargo run -- serve`.
# Override via UMBRAL_BIND_ADDR or the --addr flag.
bind_addr = "127.0.0.1:8000"

environment = "Dev"

# A random dev-only key, unique to this project. CHANGE THIS IN PRODUCTION —
# the framework errors at boot if a dev key is used with environment = "Prod".
secret_key = "{dev_secret}"
"#
    );
    write_file(&root, "umbral.toml", &umbral_toml, &mut files)?;

    // ------------------------------------------------------------------ //
    // .env  (working copy — not checked in)                               //
    // ------------------------------------------------------------------ //
    let dot_env = format!(
        r#"# Working .env for {name}. Do not commit this file.
# Generate a real secret key: openssl rand -hex 32
UMBRAL_DATABASE_URL=sqlite://{name}.db?mode=rwc
UMBRAL_BIND_ADDR=127.0.0.1:8000
UMBRAL_SECRET_KEY={dev_secret}
RUST_LOG=info,umbral=debug
"#
    );
    write_file(&root, ".env", &dot_env, &mut files)?;

    // ------------------------------------------------------------------ //
    // .env.example                                                         //
    // ------------------------------------------------------------------ //
    let env_example = r#"# Copy to `.env` and source from your shell, or use a tool like direnv.
# Settings here override the umbral.toml values at runtime.
#
# UMBRAL_SECRET_KEY=$(openssl rand -hex 32)
# UMBRAL_DATABASE_URL=sqlite://my.db?mode=rwc
# UMBRAL_BIND_ADDR=0.0.0.0:8000
# UMBRAL_ENVIRONMENT=prod
# RUST_LOG=info,umbral=debug
"#;
    write_file(&root, ".env.example", env_example, &mut files)?;

    // ------------------------------------------------------------------ //
    // .gitignore                                                           //
    // ------------------------------------------------------------------ //
    let gitignore = format!("/target\n/{name}.db*\n.env\nCargo.lock\n");
    write_file(&root, ".gitignore", &gitignore, &mut files)?;

    // ------------------------------------------------------------------ //
    // README.md                                                            //
    // ------------------------------------------------------------------ //
    let readme = format!(
        r#"# {name}

Your umbral app.

It starts with one model (`Post`), an admin, a JSON API and an OpenAPI browser, so there
is something running from the first `cargo run`. All of it is ordinary code in this
repository — rename it, gut it, replace it.

## What's in the project

| File | What it shows |
|---|---|
| `src/main.rs` | App wiring: models, plugins, routes, auto-migrate |
| `Post` model | `ForeignKey<AuthUser>`, ORM QuerySet, `#[derive(Model)]` |
| `/` route | Template rendering with context |
| `/api/posts` | JSON endpoint via the ORM |
| `/dashboard` | `login_required_html("/login")` layer, `LoggedIn<AuthUser>` extractor, transaction |
| `RestPlugin` | JSON CRUD at `/api/post/` with query-string filtering (`?published=true`) |
| `AdminPlugin` | Auto CRUD UI at `/admin/` |
| `OpenApiPlugin` | Swagger UI at `/openapi/` |
| `SecurityPlugin` | CSRF middleware + hardening headers, with `/api` exempt for token clients |

## Running

```bash
# First run — `serve` (or a bare `cargo run`, which defaults to serve)
# auto-migrates AND seeds against a fresh database before starting the
# server (auto_migrate_on_serve + seed_on_serve in main.rs). In dev it
# also autodetects model changes (the makemigrations half), so editing a
# model and re-running `serve` just works. Schema commands like `migrate`
# / `makemigrations` do NOT auto-migrate — they drive the flow themselves.
cargo run -- serve

# Separate steps (production pattern) — migrate explicitly, then serve:
cargo run -- makemigrations   # autodetect model changes into a migration file
cargo run -- migrate          # apply pending migrations
cargo run -- serve

# Create a superuser (the login page above uses these credentials):
cargo run -- createsuperuser

# Inspect the schema:
cargo run -- showmigrations

# Background tasks: run a worker alongside the server to drain the queue.
# Any #[umbral::task] handler you write is discovered automatically.
cargo run -- tasks-worker
```

## Styling

The pages use Tailwind, compiled to `static/css/app.css` and served by the
StoragePlugin at `/static`. That bundle ships **prebuilt**, so this project renders
correctly with no `npm install`.

You only need Node once you edit a template and reach for a utility class that is not
already in the bundle:

```bash
cd styles
npm install
npm run build      # or: npm run watch
```

The palette lives in `styles/input.css` as CSS variables (`--accent` is the violet).
Change them there and every page follows. There is deliberately no `cdn.tailwindcss.com`
script: it is versionless, it pulls a third party into every page load, and it is the
first thing a `default-src 'self'` Content-Security-Policy blocks.

## Where to go next

- Add a plugin: `umbral startplugin posts`
- Your first app: {docs}/getting-started/your-first-app
- Models & the ORM: {docs}/orm/models
- Migrations: {docs}/migrations/managed-migrations
- Admin: {docs}/plugins/admin
- REST: {docs}/rest/index
- Login & signup pages: {docs}/auth/login-and-signup-pages
- The Plugin trait: {docs}/plugins/the-plugin-trait
"#,
        docs = DOCS_URL,
    );
    write_file(&root, "README.md", &readme, &mut files)?;

    // ------------------------------------------------------------------ //
    // templates/ + styles/ + static/  — the design system                 //
    //                                                                      //
    // These live as real files under `crates/umbral-cli/assets/scaffold/`  //
    // rather than as string literals, so the templates can be edited (and  //
    // the Tailwind bundle actually COMPILED) like the HTML and CSS they    //
    // are. `__PROJECT__` / `__INITIAL__` / `__DOCS__` are substituted here.//
    // ------------------------------------------------------------------ //
    let initial = name
        .chars()
        .next()
        .map(|c| c.to_uppercase().to_string())
        .unwrap_or_else(|| "U".to_string());
    let fill = |tpl: &str| -> String {
        tpl.replace("__PROJECT__", name)
            .replace("__INITIAL__", &initial)
            .replace("__DOCS__", DOCS_URL)
    };

    for (path, body) in [
        (
            "templates/base.html",
            include_str!("../assets/scaffold/templates/base.html"),
        ),
        (
            "templates/home.html",
            include_str!("../assets/scaffold/templates/home.html"),
        ),
        (
            "templates/dashboard.html",
            include_str!("../assets/scaffold/templates/dashboard.html"),
        ),
        (
            "templates/login.html",
            include_str!("../assets/scaffold/templates/login.html"),
        ),
        (
            "templates/404.html",
            include_str!("../assets/scaffold/templates/404.html"),
        ),
        (
            "templates/500.html",
            include_str!("../assets/scaffold/templates/500.html"),
        ),
        (
            "styles/input.css",
            include_str!("../assets/scaffold/styles/input.css"),
        ),
        (
            "styles/tailwind.config.js",
            include_str!("../assets/scaffold/styles/tailwind.config.js"),
        ),
        (
            "styles/package.json",
            include_str!("../assets/scaffold/styles/package.json"),
        ),
        // The COMPILED bundle, shipped prebuilt. A brand-new project renders correctly
        // with no npm install — `npm run build` in styles/ is only needed once you edit
        // the templates and use a utility class that isn't already in here.
        (
            "static/css/app.css",
            include_str!("../assets/scaffold/static/css/app.css"),
        ),
    ] {
        write_file(&root, path, &fill(body), &mut files)?;
    }

    let next_steps = vec![
        format!("cd {name}"),
        "cargo run -- migrate  # apply schema migrations".to_string(),
        "cargo run -- serve    # boot the HTTP server on http://127.0.0.1:8000".to_string(),
        "cargo run -- createsuperuser  # create an admin login".to_string(),
        "umbral startplugin <name>       # add a plugin to this project".to_string(),
    ];

    Ok(ScaffoldReport {
        root,
        files,
        next_steps,
        cargo_toml_registered: None,
        // `startproject` has nothing to register itself with — it IS the project.
        registered: None,
    })
}

/// Deprecated alias for [`scaffold_plugin`]. Everything the framework
/// generates under `plugins/` is a *plugin* — there is no separate "app"
/// contract — so the old minimal `startapp` writer folds into
/// `startplugin` / [`scaffold_plugin`], leaving one generator to maintain.
/// Kept as a forwarding shim so existing API callers keep working; the CLI
/// `startapp` command forwards here and prints a deprecation note. (Not
/// `#[deprecated]` at the Rust level — that would warn on every internal
/// test call site; the user-facing deprecation lives on the CLI command.)
pub fn scaffold_app(
    name: &str,
    project_root: &Path,
    local_umbral_repo: Option<&Path>,
) -> Result<ScaffoldReport, ScaffoldError> {
    scaffold_plugin(name, project_root, local_umbral_repo)
}

/// Write a richer plugin scaffold at `<project_root>/plugins/<name>/`
/// targeted at *distributable* / reusable plugins (third-party crates
/// you'd publish or share across projects). Layout:
///
/// ```text
/// plugins/<name>/
/// ├── Cargo.toml         — deps: umbral, serde, sqlx, chrono, async-trait
/// ├── README.md          — what this plugin does, how to wire it
/// └── src/
///     ├── lib.rs         — Plugin trait impl, glues models + routes
///     ├── models.rs      — one example Model showing common field types
///     │                    (Text + max_length, Choice enum, optional DateTime)
///     └── handlers.rs    — one example axum handler using AppContext
/// ```
///
/// This is the one plugin scaffolder. `startapp` / [`scaffold_app`] are a
/// deprecated alias that forward here — everything generated under
/// `plugins/` is a plugin, so there is no separate "app" template.
pub fn scaffold_plugin(
    name: &str,
    project_root: &Path,
    local_umbral_repo: Option<&Path>,
) -> Result<ScaffoldReport, ScaffoldError> {
    // Reserved first, then the identifier rules — see `scaffold_app`.
    let normalized = name.replace('-', "_");
    if RESERVED_PLUGIN_NAMES.contains(&normalized.as_str()) {
        return Err(ScaffoldError::ReservedName(name.to_string()));
    }

    validate_name(name)?;

    let plugins_dir = project_root.join("plugins");
    let root = plugins_dir.join(name);
    if root.exists() {
        return Err(ScaffoldError::AlreadyExists(root));
    }

    fs::create_dir_all(&root)?;
    fs::create_dir_all(root.join("src"))?;

    let crate_name = rust_ident(name);
    let pascal = pascal_case_from_ident(name);
    let mut files = Vec::new();

    // Cargo.toml — pulls in the deps the example modules use. async-
    // trait is here because Plugin trait methods are sync today, but
    // the generated handlers.rs example uses an async axum extractor,
    // and most plugins grow async work quickly. Cheap to ship now,
    // saves the user a Cargo.toml edit later.
    let version = env!("CARGO_PKG_VERSION");
    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"
description = "A {crate_name} plugin for umbral."

[dependencies]
umbral = "{version}"
serde = {{ version = "1", features = ["derive"] }}
sqlx = {{ version = "0.8", default-features = false, features = ["macros", "runtime-tokio"] }}
chrono = {{ version = "0.4", features = ["serde"] }}
async-trait = "0.1"
"#
    );
    let cargo_toml = match local_umbral_repo {
        Some(repo) => localize_deps(&cargo_toml, repo),
        None => cargo_toml,
    };
    write_file(&root, "Cargo.toml", &cargo_toml, &mut files)?;

    // README.md — the user-facing tour. Mirrors the file structure so
    // a reader who clones the crate knows where to look first.
    let readme = format!(
        r#"# {name}

A {crate_name} plugin for [umbral](https://github.com/dalmasonto/umbral).

Generated by `umbral startplugin {name}`.

## What's inside

| File | Purpose |
|---|---|
| `src/lib.rs` | `{pascal}Plugin` struct + `impl Plugin` (registers models, routes, lifecycle hooks). |
| `src/models.rs` | One example model showing common field types (`#[umbral(...)]` attributes for `max_length`, `choices`, FK, defaults). |
| `src/handlers.rs` | One example axum handler showing how to read query params and return JSON. |

## Wiring it in

In your project's `Cargo.toml`:

```toml
[dependencies]
{name} = {{ path = "plugins/{name}" }}
```

In `src/main.rs`:

```rust,ignore
let app = umbral::App::builder()
    .plugin({crate_name}::{pascal}Plugin::default())
    // ... your other plugins
    .build_deferred()?;   // build_deferred + dispatch: lets `dispatch` fire

umbral_cli::dispatch(app).await   // on_ready AFTER a management command runs
```

Then:

```sh
cargo run -- makemigrations   # generates 0001_initial.json from your models
cargo run -- migrate          # applies the schema
cargo run -- serve            # boots the HTTP server
```

## Next steps

- Add your own models in `src/models.rs` (or split into a `models/` module).
- Add routes in `routes()` and handlers in `src/handlers.rs`.
- Use `on_ready(&AppContext)` for one-shot setup work (seed default rows, register signals).
- See `documentation/docs/v0.0.1/plugins/the-plugin-trait.mdx` for the full trait surface.
"#
    );
    write_file(&root, "README.md", &readme, &mut files)?;

    // src/lib.rs — Plugin impl that pulls models + routes from the
    // sibling modules. `models()` returns the registered model meta;
    // `routes()` returns the axum Router with the example handler.
    let lib_rs = format!(
        r#"//! {pascal}Plugin — a distributable umbral plugin.
//!
//! Wire this into your App in `src/main.rs`:
//!
//! ```ignore
//! .plugin({crate_name}::{pascal}Plugin::default())
//! ```
//!
//! See `README.md` for the full file tour.

pub mod handlers;
pub mod models;

use async_trait::async_trait;
use umbral::migrate::ModelMeta;
use umbral::plugin::{{AppContext, Plugin, PluginError}};
use umbral::web::{{Router, get}};

/// The plugin entry point. Register one instance per `App::builder()`.
#[derive(Debug, Default, Clone)]
pub struct {pascal}Plugin;

#[async_trait]
impl Plugin for {pascal}Plugin {{
    fn name(&self) -> &'static str {{
        "{name}"
    }}

    /// Models the framework's migration engine should track. Each
    /// returned [`ModelMeta`] becomes one row in the
    /// `umbral_migrations` tracking table once the initial migration
    /// applies.
    fn models(&self) -> Vec<ModelMeta> {{
        // One entry per model the plugin owns. `umbral::discovered_models!()`
        // finds every #[derive(Model)] in this crate automatically if you'd
        // rather not maintain the list by hand.
        vec![ModelMeta::for_::<models::{pascal}Item>()]
    }}

    /// HTTP routes contributed by this plugin. The base path is
    /// up to you — convention is `/<name>/...` for HTML and
    /// `/api/<name>/...` for JSON.
    fn routes(&self) -> Router {{
        Router::new().route("/{name}/hello", get(handlers::hello))
    }}

    /// One-shot setup after `App::build()` finishes. Use this for
    /// seeding default rows, registering signal handlers, or any
    /// work that needs the database available. Sync because the
    /// `Plugin` trait signature is sync (BUG-3 in bugs/tests/testBugs.md);
    /// reach into a runtime via `tokio::runtime::Handle::current()
    /// .block_on(...)` if you need to await something here.
    fn on_ready(&self, _ctx: &AppContext) -> Result<(), PluginError> {{
        Ok(())
    }}
}}
"#
    );
    write_file(&root, "src/lib.rs", &lib_rs, &mut files)?;

    // src/models.rs — one Model showing the field types most plugins
    // need: a Text with max_length, a Choice enum, an optional
    // DateTime. Keeps it small enough to read in one screen.
    let models_rs = format!(
        r#"//! Example model. Replace or extend with your own.
//!
//! What this demonstrates:
//! - `#[umbral(max_length = 200)]` — DDL `VARCHAR(200)` + admin form hint.
//! - `#[umbral(choices)]` on an enum — closed-set column with OpenAPI
//!   `enum` and a Postgres `CHECK (col IN (...))` constraint.
//! - `Option<DateTime<Utc>>` — nullable timestamptz column.
//! - `#[umbral(noedit)]` — read-only on admin forms; not editable via
//!   PUT/PATCH through the REST plugin.

use chrono::{{DateTime, Utc}};
use serde::{{Deserialize, Serialize}};

/// One {crate_name} item. Replace with whatever your plugin actually
/// stores.
#[derive(Debug, Clone, sqlx::FromRow, Serialize, Deserialize, umbral::orm::Model)]
pub struct {pascal}Item {{
    /// Auto-incrementing primary key.
    pub id: i64,

    /// Display title. Capped at 200 chars; admin renders a single-line
    /// input.
    #[umbral(string, max_length = 200)]
    pub title: String,

    /// Lifecycle state. `#[umbral(choices)]` maps the column 1:1 to the
    /// enum variants: the migration engine emits a CHECK constraint, the
    /// admin renders a `<select>`, and the OpenAPI schema gets an `enum`.
    #[umbral(choices)]
    pub status: {pascal}Status,

    /// When the item was last published. Read-only on edit forms.
    #[umbral(noedit)]
    pub published_at: Option<DateTime<Utc>>,
}}

/// Lifecycle state for [`{pascal}Item`]. The `Choices` derive teaches the
/// ORM the closed set; `rename_all` controls how variants serialize to the
/// stored string (`Draft` → `"draft"`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, umbral::orm::Choices)]
#[choices(rename_all = "lowercase")]
pub enum {pascal}Status {{
    Draft,
    Review,
    Published,
    Archived,
}}
"#
    );
    write_file(&root, "src/models.rs", &models_rs, &mut files)?;

    // src/handlers.rs — one axum handler returning JSON. Shows the
    // Query extractor + the framework's Json response shape.
    let handlers_rs = format!(
        r#"//! Example HTTP handlers. Replace or extend with your own.
//!
//! `GET /{name}/hello?name=world` returns `{{"greeting": "Hello, world!"}}`.

use serde::{{Deserialize, Serialize}};
use umbral::web::{{Json, Query}};

#[derive(Debug, Deserialize, Default)]
pub struct HelloParams {{
    /// Who to greet. Defaults to "{name}" when omitted.
    #[serde(default)]
    pub name: Option<String>,
}}

#[derive(Debug, Serialize)]
pub struct HelloResponse {{
    pub greeting: String,
}}

pub async fn hello(Query(params): Query<HelloParams>) -> Json<HelloResponse> {{
    let who = params.name.as_deref().unwrap_or("{name}");
    Json(HelloResponse {{
        greeting: format!("Hello, {{who}}!"),
    }})
}}
"#
    );
    write_file(&root, "src/handlers.rs", &handlers_rs, &mut files)?;

    // Auto-register the new crate as a path dep in the project's Cargo.toml.
    let project_cargo_toml = project_root.join("Cargo.toml");
    let cargo_toml_registered = if project_cargo_toml.is_file() {
        register_dep_in_cargo_toml(&project_cargo_toml, name).ok()
    } else {
        None
    };

    let next_steps = vec![
        "Wire the plugin into your App::builder chain in src/main.rs:".to_string(),
        format!("    .plugin({crate_name}::{pascal}Plugin::default())"),
        "Generate + apply the initial migration:".to_string(),
        "    cargo run -- makemigrations".to_string(),
        "    cargo run -- migrate".to_string(),
        format!("Then visit http://127.0.0.1:8000/{name}/hello?name=you"),
    ];

    Ok(ScaffoldReport {
        root,
        files,
        next_steps,
        cargo_toml_registered,
        registered: None,
    })
}

// ===================================================================== //
// startcommand (gaps3 #81)                                              //
// ===================================================================== //

/// Where a scaffolded management command lives: the project's own binary
/// (registered on the App builder via `.commands(commands::all())`) or a
/// plugin under `plugins/<name>/` (returned from its `Plugin::commands()`,
/// so it travels with the plugin).
///
/// This is `umbral::codegen::Target` — the same "root or which plugin?" every
/// generator asks, including the ones plugins ship (`umbral-rest`'s
/// `startpermission` and friends). Two enums saying the same thing is one
/// enum too many.
pub use umbral::codegen::Target as CommandTarget;

/// The marker line the scaffolder inserts new module declarations above.
const MODS_MARKER: &str =
    "// umbral:startcommand — `umbral startcommand` declares new modules above this line.";
/// The marker line the scaffolder inserts new registry entries above.
const REGISTRY_MARKER: &str =
    "// umbral:startcommand — `umbral startcommand` registers new commands above this line.";

/// List the plugins available in this project: every `plugins/<name>/`
/// directory that holds a `Cargo.toml`.
///
/// Reads the disk rather than `main.rs`, so a plugin you scaffolded but
/// haven't registered yet is still offered as a home for a command. Shared
/// with every other generator via `umbral::codegen`.
pub use umbral::codegen::discover_plugins;

/// Write a management command and register it.
///
/// Two targets, one shape. Either way the command lands in a
/// `commands/<name>.rs` next to a `commands/mod.rs` whose `all()` function
/// is the registry, and the registry is wired into the thing that owns it:
///
/// ```text
/// --in root                        --in <plugin>
/// src/                             plugins/<plugin>/src/
///   main.rs   .commands(all())       lib.rs   fn commands() -> all()
///   commands/                        commands/
///     mod.rs  pub fn all()             mod.rs  pub fn all()
///     <name>.rs                        <name>.rs
/// ```
///
/// ## Why a hand-maintained `all()` and not real auto-detection
///
/// Rust has no runtime module reflection: nothing can walk `commands/` at
/// startup and find the structs in it. The choices are a build script that
/// generates the registry, an inventory-style linker-section crate, or a
/// registry function the tool maintains. The registry function wins because
/// it stays *readable and editable by hand* — you can see every command the
/// app has in one place, reorder them, comment one out — and the scaffolder
/// keeps it up to date so the common path costs you nothing. The marker
/// comments are how it finds its insertion points; delete them and the tool
/// falls back to telling you the two lines to add.
///
/// Calling this a second time with a different name appends to the existing
/// `mod.rs` and touches neither `main.rs` nor the plugin's `lib.rs` again.
pub fn scaffold_command(
    name: &str,
    target: &CommandTarget,
    project_root: &Path,
) -> Result<ScaffoldReport, ScaffoldError> {
    // Reserved first: `migrate` and friends deserve the "that is already an
    // umbral command" message rather than a generic identifier complaint.
    if reserved_command_names().iter().any(|r| r == name) {
        return Err(ScaffoldError::ReservedCommandName(name.to_string()));
    }

    validate_name(name)?;

    let module = rust_ident(name);
    let pascal = pascal_case_from_ident(name);
    let struct_name = format!("{pascal}Command");

    // Resolve the crate the command lands in, and the file that owns its
    // registry (main.rs registers via the builder; a plugin via its
    // `Plugin::commands()` impl). `resolve_target` is shared with every other
    // generator, including the ones plugins ship.
    let resolved = umbral::codegen::resolve_target(project_root, target)?;
    let crate_root = resolved.crate_root.clone();
    let owner_file = resolved.owner_file.clone();

    let mut files = Vec::new();

    // ---------------------------------------------------------------- //
    // src/commands/<name>.rs — the command itself. `write_new_file`     //
    // refuses to overwrite, so a re-run can't eat an existing command.  //
    // ---------------------------------------------------------------- //
    umbral::codegen::write_new_file(
        &crate_root,
        &format!("src/commands/{module}.rs"),
        &render_command_file(name, &struct_name, target),
        &mut files,
    )?;

    // ---------------------------------------------------------------- //
    // src/commands/mod.rs — the registry. Created on the first command, //
    // appended to on every one after.                                   //
    // ---------------------------------------------------------------- //
    let mod_rs = crate_root.join("src/commands/mod.rs");
    let mut next_steps: Vec<String> = Vec::new();
    if mod_rs.is_file() {
        let text = fs::read_to_string(&mod_rs)?;
        match append_to_registry(&text, &module, &struct_name) {
            Some(updated) => {
                fs::write(&mod_rs, updated)?;
                files.push(PathBuf::from("src/commands/mod.rs"));
            }
            None => {
                // The markers are gone — the user restructured the file. Say so
                // and hand back the exact two lines rather than guessing where
                // they go and corrupting a file we don't understand.
                next_steps.push(
                    "src/commands/mod.rs has no `umbral:startcommand` markers — add by hand:"
                        .to_string(),
                );
                next_steps.push(format!("    pub mod {module};"));
                next_steps.push(format!(
                    "    ...and inside `all()`:  Box::new({module}::{struct_name}),"
                ));
            }
        }
    } else {
        umbral::codegen::write_new_file(
            &crate_root,
            "src/commands/mod.rs",
            &render_registry_file(&module, &struct_name, target),
            &mut files,
        )?;
    }

    // ---------------------------------------------------------------- //
    // Register the registry with its owner (once — the second command    //
    // reuses the same `all()` call).                                     //
    // ---------------------------------------------------------------- //
    let owner_text = fs::read_to_string(&owner_file)?;
    let wiring = match target {
        CommandTarget::Root => wire_registry_into_main(&owner_text),
        CommandTarget::Plugin(_) => wire_registry_into_plugin(&owner_text),
    };
    // `registered` is the truth the CLI prints. A partial edit (we added the
    // module but could not find the builder chain) counts as NOT registered:
    // the command does not run until the user pastes the remaining line.
    let registered = match wiring {
        Wiring::Updated { text, steps } => {
            fs::write(&owner_file, text)?;
            let complete = steps.is_empty();
            next_steps.extend(steps);
            complete
        }
        Wiring::AlreadyWired => true,
        Wiring::Manual(steps) => {
            next_steps.extend(steps);
            false
        }
    };

    if registered {
        next_steps.push(format!("Run it:  cargo run -- {name} --help"));
    } else {
        next_steps.push(format!(
            "Then run it:  cargo run -- {name} --help   (after the steps above — \
             it is NOT registered yet)"
        ));
    }

    Ok(ScaffoldReport {
        root: crate_root,
        files,
        next_steps,
        cargo_toml_registered: None,
        registered: Some(registered),
    })
}

/// Outcome of registering the `commands::all()` registry with the file
/// that owns it (`main.rs` for root, the plugin's `lib.rs` otherwise).
///
/// `Updated` carries leftover manual steps because the two aren't
/// exclusive: we can add the `pub mod commands;` line and still be unable
/// to touch a hand-written `fn commands()` we don't own. Discarding the
/// half that worked to keep the enum tidy would help nobody.
enum Wiring {
    /// The file was edited. `text` is the new content; `steps` is anything
    /// the edit could NOT do and the user must.
    Updated { text: String, steps: Vec<String> },
    /// Already registered — a previous `startcommand` did it. Nothing to do,
    /// which is exactly what makes the second command free.
    AlreadyWired,
    /// The file doesn't match the shape we know how to edit. Rather than
    /// guess, hand the user the lines to paste.
    Manual(Vec<String>),
}

/// Wire `mod commands;` + `.commands(commands::all())` into a project's
/// `main.rs`.
///
/// The builder call is inserted immediately before `.build()` /
/// `.build_deferred()`, which is the one anchor every umbral `main.rs` has
/// — the chain ends there by definition.
fn wire_registry_into_main(text: &str) -> Wiring {
    let already_mod = text.lines().any(|l| l.trim() == "mod commands;");
    let already_registered = text.contains(".commands(commands::all())");
    if already_mod && already_registered {
        return Wiring::AlreadyWired;
    }

    let mut out = text.to_string();
    let mut steps: Vec<String> = Vec::new();

    if !already_mod {
        // Before the first `mod x;` line, so the table of contents at the top
        // of main.rs stays alphabetical (`commands` sorts before `seed`).
        match umbral::codegen::declare_module(&out, "mod commands;") {
            Some(text) => out = text,
            None => steps.push("Add to src/main.rs:  mod commands;".to_string()),
        }
    }

    if !already_registered {
        match builder_terminal_line(&out) {
            Some(idx) => {
                let indent: String = out
                    .lines()
                    .nth(idx)
                    .map(|l| l.chars().take_while(|c| c.is_whitespace()).collect())
                    .unwrap_or_default();
                let call = format!(
                    "{indent}// Project-owned management commands (`umbral startcommand`).\n\
                     {indent}.commands(commands::all())"
                );
                out = insert_line_at_before(&out, idx, &call);
            }
            None => steps.push(
                "Add to the App::builder() chain in src/main.rs:  .commands(commands::all())"
                    .to_string(),
            ),
        }
    }

    if out == text {
        if steps.is_empty() {
            Wiring::AlreadyWired
        } else {
            Wiring::Manual(steps)
        }
    } else {
        // Whatever we DID manage to edit is written, and whatever we could not
        // is reported. The old code returned `Manual` from inside the second
        // branch and dropped `out` on the floor — so a `mod commands;` line it
        // had already inserted vanished, and the steps it printed never
        // mentioned it. The user pasted the one line they were given and got
        // `failed to resolve: use of undeclared module `commands``.
        Wiring::Updated { text: out, steps }
    }
}

/// The line index of the `.build()` / `.build_deferred()` that TERMINATES the
/// `App::builder()` chain — the only safe place to hang `.commands(...)`.
///
/// Anchoring on the first `.build()` in the file is wrong, and not
/// hypothetically: a `main.rs` that builds anything else first —
/// `reqwest::Client::builder()…​.build()?`, a `tracing` subscriber, a
/// `SqlitePoolOptions` — hands us that chain's terminal instead, and we splice
/// `.commands(commands::all())` into a type that has no such method. The user's
/// main.rs stops compiling, in a place they never touched, and the tool reports
/// success.
///
/// So: find `App::builder()` first, and take the first terminal at or after it.
/// No `App::builder()` (a project that wires the app elsewhere) → `None`, and
/// the caller prints the line to add by hand rather than guessing.
fn builder_terminal_line(text: &str) -> Option<usize> {
    let builder_at = text.lines().position(|l| l.contains("App::builder()"))?;
    text.lines()
        .enumerate()
        .skip(builder_at)
        .find(|(_, l)| {
            let t = l.trim_start();
            t.starts_with(".build_deferred()") || t.starts_with(".build()")
        })
        .map(|(idx, _)| idx)
}

/// Wire `pub mod commands;` + a `Plugin::commands()` impl into a plugin's
/// `lib.rs`.
///
/// The impl method is inserted at the top of the `impl Plugin for ...`
/// block. If the plugin already has a `fn commands`, we don't touch it —
/// a hand-written one may return more than the registry, and silently
/// rewriting someone's trait impl is exactly the kind of "helpful" edit
/// that eats work.
fn wire_registry_into_plugin(text: &str) -> Wiring {
    let already_mod = text.lines().any(|l| l.trim() == "pub mod commands;");
    let has_commands_fn = text.contains("fn commands(");
    if already_mod && has_commands_fn {
        return Wiring::AlreadyWired;
    }

    let mut out = text.to_string();
    let mut steps: Vec<String> = Vec::new();

    if !already_mod {
        match umbral::codegen::declare_module(&out, "pub mod commands;") {
            Some(text) => out = text,
            None => steps.push("Add to src/lib.rs:  pub mod commands;".to_string()),
        }
    }

    if !has_commands_fn {
        // The header must OPEN the block on this line. `impl Plugin for X` with
        // its `{` on a following line (a `where` clause, or just rustfmt on a
        // long header) would otherwise get the method spliced in *before* the
        // brace, and the plugin's lib.rs would stop parsing — a syntax error
        // inside code the user never touched, which is precisely the "generator
        // that guesses at a file it doesn't recognise" this module's docs
        // promise not to be.
        match out
            .lines()
            .position(|l| l.starts_with("impl Plugin for ") && l.trim_end().ends_with('{'))
        {
            Some(idx) => {
                let method = "\n    fn commands(&self) -> Vec<Box<dyn umbral::cli::PluginCommand>> {\n        \
                     // Every command in `src/commands/` — `umbral startcommand`\n        \
                     // appends to the registry in `commands/mod.rs`, so this line\n        \
                     // never needs to change again.\n        \
                     commands::all()\n    }";
                out = insert_line_at(&out, idx, method);
            }
            None => steps.push(
                "Add to your `impl Plugin`:  fn commands(&self) -> Vec<Box<dyn umbral::cli::PluginCommand>> { commands::all() }"
                    .to_string(),
            ),
        }
    } else {
        steps.push(
            "Your plugin already has a `fn commands()` — make sure it returns \
             `commands::all()` (or extends it) so the new command is registered."
                .to_string(),
        );
    }

    if out == text {
        // Nothing we could edit. Everything is a manual step (or, if there are
        // none, it was already wired).
        if steps.is_empty() {
            Wiring::AlreadyWired
        } else {
            Wiring::Manual(steps)
        }
    } else {
        Wiring::Updated { text: out, steps }
    }
}

/// Insert `line` immediately after line index `idx` of `text`, preserving the
/// file's line endings. Delegates to the shared primitive: the hand-rolled copy
/// emitted `\n` unconditionally, so wiring a method into a CRLF `lib.rs`
/// rewrote every line of it in the user's next diff.
fn insert_line_at(text: &str, idx: usize, line: &str) -> String {
    umbral::codegen::insert_line_after(text, idx, line)
}

/// Append a module declaration + a registry entry to an existing
/// `commands/mod.rs`, using the marker comments as insertion points.
///
/// Returns `None` when a marker is missing — the caller then reports the
/// lines to add by hand rather than guessing at a file it doesn't
/// recognise.
fn append_to_registry(text: &str, module: &str, struct_name: &str) -> Option<String> {
    // The two halves are checked INDEPENDENTLY. They can legitimately drift
    // apart — delete a command file and re-run, or hand-add the `pub mod` line —
    // and the old code took the presence of the module declaration as proof
    // that the registry entry existed too. It returned the text unchanged, so
    // `all()` never got the command, while the CLI cheerfully printed
    // "Registered". `cargo run -- <name>` then answered "unknown command" for a
    // command the tool had just claimed to wire up.
    let mod_line = format!("pub mod {module};");
    let entry = format!("Box::new({module}::{struct_name}),");

    let mut out = text.to_string();

    if !out.lines().any(|l| l.trim() == mod_line) {
        out = umbral::codegen::insert_before_marker(&out, MODS_MARKER, &mod_line)?;
    }
    if !out.lines().any(|l| l.trim() == entry) {
        out = umbral::codegen::insert_before_marker(
            &out,
            REGISTRY_MARKER,
            &format!("        {entry}"),
        )?;
    }
    Some(out)
}

/// Insert `line` immediately *before* line index `idx` of `text`, preserving
/// the file's line endings. Delegates to the shared codegen primitive so
/// `startcommand` and a plugin's generator treat a user's file identically.
fn insert_line_at_before(text: &str, idx: usize, line: &str) -> String {
    umbral::codegen::insert_line_before(text, idx, line)
}

/// The generated `commands/mod.rs` — the registry.
fn render_registry_file(module: &str, struct_name: &str, target: &CommandTarget) -> String {
    let (owner, wiring) = match target {
        CommandTarget::Root => (
            "this project",
            "`main.rs` passes `all()` to `App::builder().commands(...)`.",
        ),
        CommandTarget::Plugin(_) => (
            "this plugin",
            "`lib.rs` returns `all()` from `Plugin::commands()`.",
        ),
    };
    format!(
        r#"//! Management commands owned by {owner} — one file per command,
//! and `all()` is the registry that hands them to the framework.
//!
//! {wiring}
//!
//! Rust can't discover a module by scanning this directory at runtime, so
//! `all()` IS the auto-detection: `umbral startcommand` appends to it for
//! you (that's what the marker comments below are for). You can also edit
//! it by hand — comment a command out and it stops existing, which is
//! harder to do with a magic registry you can't see.

use umbral::cli::PluginCommand;

pub mod {module};
{MODS_MARKER}

/// Every command {owner} registers.
pub fn all() -> Vec<Box<dyn PluginCommand>> {{
    vec![
        Box::new({module}::{struct_name}),
        {REGISTRY_MARKER}
    ]
}}
"#
    )
}

/// The generated `commands/<name>.rs` — one command, showing the three arg
/// shapes clap gives you (positional, named value, flag) and how each is
/// read back out of `ArgMatches`.
fn render_command_file(name: &str, struct_name: &str, target: &CommandTarget) -> String {
    // A plugin's command reaches its own models through `crate::models`;
    // a root command reaches the project's through `crate::`.
    let orm_note = match target {
        CommandTarget::Root => "//     use crate::{Post, post};",
        CommandTarget::Plugin(_) => "//     use crate::models::{Post, post};",
    };
    format!(
        r#"//! `{name}` — a management command.
//!
//! ```bash
//! cargo run -- {name} --help                       # what it takes
//! cargo run -- {name} hello --limit 5 --dry-run    # a real run
//! umbral {name} hello --tag a --tag b              # same thing, via the umbral CLI
//! ```
//!
//! Registered through `commands::all()` in `commands/mod.rs`. It runs against
//! a fully-built app: settings loaded, pool open, every model registered — so
//! the ORM works ambiently here, with no pool to thread through.

use umbral::cli::{{CliError, PluginCommand, clap}};

/// The `{name}` command.
///
/// A unit struct is enough when the command is stateless. It doesn't have to
/// be: the trait is object-safe over `&self`, so anything the command needs
/// configured (a prefix, a client, a channel) can live on the struct and be
/// passed in at registration — which is exactly why this is a trait and not a
/// bare `fn` pointer.
pub struct {struct_name};

#[umbral::async_trait]
impl PluginCommand for {struct_name} {{
    /// Declare the command: its name, its help, and its arguments.
    ///
    /// This is plain `clap`, so everything clap can do is available here —
    /// value parsing and validation, defaults, conflicts, subcommands of your
    /// own. Note the import: `umbral::cli::clap`, the framework's own clap.
    /// Add `clap` to your Cargo.toml separately and a major-version bump on
    /// either side turns into a type mismatch a page long.
    fn command(&self) -> clap::Command {{
        clap::Command::new("{name}")
            // Shown next to the command in `umbral help`. Write it — a command
            // with no `about` lists as a dash and nobody discovers it.
            .about("TODO: one line on what {name} does")
            .long_about(
                "TODO: the longer story, shown on `{name} --help`. What it \
                 changes, whether it's safe to re-run, what it needs first.",
            )
            // POSITIONAL argument — `{name} <slug>`. Required, so clap
            // rejects the call with a usage error if it's missing and `run`
            // never sees a half-formed invocation.
            .arg(
                clap::Arg::new("slug")
                    .required(true)
                    .help("The thing to operate on"),
            )
            // NAMED argument with a value and a default — `--limit 25` / `-l 25`.
            // `value_parser` is what makes it a `u64` on the other side rather
            // than a string you'd have to parse (and mis-parse) yourself.
            .arg(
                clap::Arg::new("limit")
                    .long("limit")
                    .short('l')
                    .value_name("N")
                    .value_parser(clap::value_parser!(u64))
                    .default_value("25")
                    .help("How many rows to touch at most"),
            )
            // REPEATABLE named argument — `--tag a --tag b` collects both.
            // `ArgAction::Append` is the difference between the second `--tag`
            // overwriting the first and the two accumulating.
            .arg(
                clap::Arg::new("tag")
                    .long("tag")
                    .value_name("TAG")
                    .action(clap::ArgAction::Append)
                    .help("Filter by tag. Repeat for more than one."),
            )
            // BOOLEAN flag — `--dry-run`, no value. `SetTrue` is what makes it
            // a flag rather than an option that demands a value.
            .arg(
                clap::Arg::new("dry-run")
                    .long("dry-run")
                    .action(clap::ArgAction::SetTrue)
                    .help("Report what would change without writing anything"),
            )
    }}

    /// Run the command. `matches` is this subcommand's own `ArgMatches` —
    /// clap has already validated it against `command()` above, so every
    /// `get_one` here is reading a value that exists and typechecked.
    async fn run(&self, matches: &clap::ArgMatches) -> Result<(), CliError> {{
        let slug = matches
            .get_one::<String>("slug")
            .expect("clap enforces `required(true)`");
        let limit = *matches
            .get_one::<u64>("limit")
            .expect("clap fills in `default_value`");
        let tags: Vec<&String> = matches
            .get_many::<String>("tag")
            .map(Iterator::collect)
            .unwrap_or_default();
        let dry_run = matches.get_flag("dry-run");

        println!("{name}: slug={{slug}} limit={{limit}} tags={{tags:?}} dry_run={{dry_run}}");

        // The app is already built by the time this runs, so the ORM is live:
        //
        {orm_note}
        //
        //     let posts = Post::objects()
        //         .filter(post::PUBLISHED.eq(true))
        //         .limit(limit as i64)
        //         .fetch()
        //         .await?;
        //
        //     if dry_run {{
        //         println!("would touch {{}} post(s)", posts.len());
        //         return Ok(());
        //     }}
        //
        // `?` just works: `CliError` is a boxed error, so every umbral error
        // converts into it. Return `Err(...)` and the process exits non-zero,
        // which is what a CI step or a cron job is watching for.

        Ok(())
    }}
}}
"#
    )
}

/// Write a file under `root` at the given relative path. Records the
/// relative path in `files` for the user-facing report.
fn write_file(
    root: &Path,
    rel_path: &str,
    contents: &str,
    files: &mut Vec<PathBuf>,
) -> Result<(), ScaffoldError> {
    // `write_new_file` refuses to overwrite. The scaffolders that call this all
    // create a fresh directory first, so nothing should be in the way — and if
    // something IS, silently clobbering it is the last thing a generator should
    // do.
    umbral::codegen::write_new_file(root, rel_path, contents, files).map_err(Into::into)
}

/// Attempt to register `<name> = { path = "plugins/<name>" }` under
/// `[dependencies]` in the project's `Cargo.toml`.
///
/// Returns:
/// - `Ok(true)`  — dep was added.
/// - `Ok(false)` — dep was already present (idempotent; no duplicate written).
/// - `Err(_)`    — the file couldn't be read or written. Callers treat this
///   as a soft failure: the scaffold files are already on disk, so we warn
///   but don't roll them back.
///
/// The insertion uses minimal string surgery (find the `[dependencies]`
/// header, append one line immediately after it) so comments, ordering,
/// and formatting of existing deps are preserved. `toml_edit` is not yet
/// a dep of umbral-cli; if it's added later this function is the right
/// place to switch to it.
pub fn register_dep_in_cargo_toml(cargo_toml_path: &Path, name: &str) -> io::Result<bool> {
    // Delegates to `umbral::codegen::ensure_dependency`. The copy that used to
    // live here matched `<name> =` on ANY line, so a crate listed under
    // `[dev-dependencies]` read as already-present (and the dep was never
    // added), and it never recognised the `[dependencies.<name>]` table form
    // (so it appended a duplicate key and cargo refused the manifest). Both are
    // fixed in the shared primitive, and both were being shipped from here.
    umbral::codegen::ensure_dependency(
        cargo_toml_path,
        name,
        &format!("{{ path = \"plugins/{name}\" }}"),
    )
    .map_err(|e| match e {
        umbral::codegen::CodegenError::Io(e) => e,
        other => io::Error::new(io::ErrorKind::InvalidData, other.to_string()),
    })
}
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn validate_name_accepts_simple_identifiers() {
        assert!(validate_name("posts").is_ok());
        assert!(validate_name("blog_engine").is_ok());
        assert!(validate_name("blog-engine").is_ok());
        assert!(validate_name("api2").is_ok());
    }

    #[test]
    fn validate_name_rejects_empty() {
        assert!(validate_name("").is_err());
    }

    #[test]
    fn validate_name_rejects_leading_digit() {
        assert!(validate_name("2cool").is_err());
    }

    #[test]
    fn validate_name_rejects_special_chars() {
        assert!(validate_name("foo bar").is_err());
        assert!(validate_name("foo!bar").is_err());
        assert!(validate_name("foo/bar").is_err());
    }

    #[test]
    fn pascal_case_handles_kebab_and_snake() {
        assert_eq!(pascal_case_from_ident("posts"), "Posts");
        assert_eq!(pascal_case_from_ident("blog_engine"), "BlogEngine");
        assert_eq!(pascal_case_from_ident("blog-engine"), "BlogEngine");
        assert_eq!(pascal_case_from_ident("api2"), "Api2");
    }

    #[test]
    fn rust_ident_replaces_hyphens() {
        assert_eq!(rust_ident("blog-engine"), "blog_engine");
        assert_eq!(rust_ident("posts"), "posts");
    }

    #[test]
    fn scaffold_app_rejects_reserved_built_in_plugin_names() {
        let tmp = tempfile::tempdir().expect("tempdir");
        for name in RESERVED_PLUGIN_NAMES {
            let result = scaffold_app(name, tmp.path(), None);
            assert!(
                matches!(result, Err(ScaffoldError::ReservedName(_))),
                "expected ReservedName error for `{name}`, got: {result:?}",
            );
            assert!(
                !tmp.path().join("plugins").join(name).exists(),
                "directory must NOT be created when name is reserved: {name}",
            );
        }
    }

    #[test]
    fn scaffold_app_rejects_reserved_name_with_hyphen_variant() {
        // `static` is reserved; so is `my-static`-anything? No — only
        // exact matches. But hyphens should normalize to underscores so
        // someone typing `umbral-storage` or `umbral_storage` doesn't slip
        // through. We compare on the underscored form.
        let tmp = tempfile::tempdir().expect("tempdir");
        // Pure name check: built-in names contain no hyphens today, but
        // the normalization defends against future built-ins like
        // `slack-bot` versus `slack_bot`.
        let result = scaffold_app("auth", tmp.path(), None);
        assert!(matches!(result, Err(ScaffoldError::ReservedName(_))));
    }

    #[test]
    fn scaffold_app_message_lists_reserved_names() {
        let err = ScaffoldError::ReservedName("auth".to_string());
        let msg = format!("{err}");
        assert!(msg.contains("`auth`"), "error names the offending input");
        assert!(
            msg.contains("admin") && msg.contains("sessions") && msg.contains("permissions"),
            "error lists the reserved set so the user can pick again: {msg}",
        );
    }

    #[test]
    fn scaffold_app_already_exists_message_says_app() {
        // Gap 39: the AlreadyExists message used to say "target" which
        // didn't tell a user that there's an existing APP. The new copy
        // names the app directly.
        let err = ScaffoldError::AlreadyExists(PathBuf::from("plugins/blog"));
        let msg = format!("{err}");
        assert!(msg.contains("app already exists"), "got: {msg}");
        assert!(msg.contains("plugins/blog"), "got: {msg}");
    }

    // ----------------------------------------------------------------- //
    // scaffold_plugin (gap #63)                                         //
    // ----------------------------------------------------------------- //

    #[test]
    fn scaffold_plugin_writes_richer_layout() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let report = scaffold_plugin("widgets", tmp.path(), None).expect("scaffold ok");

        let root = tmp.path().join("plugins").join("widgets");
        assert!(root.is_dir());

        // The richer layout: README + lib + models + handlers.
        for rel in [
            "Cargo.toml",
            "README.md",
            "src/lib.rs",
            "src/models.rs",
            "src/handlers.rs",
        ] {
            assert!(
                root.join(rel).exists(),
                "missing expected file: {rel}; got {:?}",
                report.files,
            );
        }
    }

    #[test]
    fn scaffold_plugin_lib_rs_references_sibling_modules() {
        let tmp = tempfile::tempdir().expect("tempdir");
        scaffold_plugin("widgets", tmp.path(), None).expect("scaffold ok");
        let lib = fs::read_to_string(tmp.path().join("plugins/widgets/src/lib.rs")).unwrap();

        assert!(
            lib.contains("pub mod handlers;"),
            "lib.rs must publish handlers"
        );
        assert!(
            lib.contains("pub mod models;"),
            "lib.rs must publish models"
        );
        assert!(lib.contains("WidgetsPlugin"), "PascalCase plugin name");
        assert!(
            lib.contains("ModelMeta::for_::<models::WidgetsItem>()"),
            "models() should register the example model",
        );
        assert!(
            lib.contains("/widgets/hello"),
            "routes() should register the example handler",
        );
    }

    #[test]
    fn scaffold_plugin_models_rs_uses_real_umbral_attributes() {
        let tmp = tempfile::tempdir().expect("tempdir");
        scaffold_plugin("widgets", tmp.path(), None).expect("scaffold ok");
        let models = fs::read_to_string(tmp.path().join("plugins/widgets/src/models.rs")).unwrap();

        assert!(
            models.contains("umbral::orm::Model"),
            "model derive must reference the framework's Model trait",
        );
        assert!(
            models.contains("max_length = 200"),
            "example model should demonstrate max_length",
        );
        assert!(
            models.contains("WidgetsStatus"),
            "example model should declare a Choice enum",
        );
        // The choices field MUST carry `#[umbral(choices)]` and the enum
        // MUST use the `Choices` derive — a bare `sqlx::Type` enum made the
        // generated model fail to compile ("M3 doesn't support this field
        // type"). Pin both so that regression can't recur.
        assert!(
            models.contains("#[umbral(choices)]"),
            "the status field needs #[umbral(choices)] or the model won't compile",
        );
        assert!(
            models.contains("Choices"),
            "the enum needs the Choices derive, not a bare sqlx::Type",
        );
        assert!(
            models.contains("noedit"),
            "example model should show the noedit attribute",
        );
    }

    #[test]
    fn scaffold_plugin_rejects_reserved_built_in_plugin_names() {
        let tmp = tempfile::tempdir().expect("tempdir");
        for name in RESERVED_PLUGIN_NAMES {
            let result = scaffold_plugin(name, tmp.path(), None);
            assert!(
                matches!(result, Err(ScaffoldError::ReservedName(_))),
                "expected ReservedName error for `{name}`, got: {result:?}",
            );
        }
    }

    #[test]
    fn scaffold_plugin_refuses_to_overwrite_existing_directory() {
        let tmp = tempfile::tempdir().expect("tempdir");
        scaffold_plugin("widgets", tmp.path(), None).expect("first scaffold ok");
        let result = scaffold_plugin("widgets", tmp.path(), None);
        assert!(matches!(result, Err(ScaffoldError::AlreadyExists(_))));
    }

    // ----------------------------------------------------------------- //
    // scaffold_project per-concern layout (gaps2 #8) + SecurityPlugin    //
    // default (gaps2 #25)                                                //
    // ----------------------------------------------------------------- //

    #[test]
    fn scaffold_project_writes_per_concern_tree() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let report = scaffold_project("blog", tmp.path(), None).expect("scaffold ok");

        let root = tmp.path().join("blog");
        assert!(root.is_dir());

        // The per-concern tree: views/, seed/, widgets/, plugins/.
        for rel in [
            "src/main.rs",
            "src/views/mod.rs",
            "src/views/public.rs",
            "src/seed/mod.rs",
            "src/seed/credentials.rs",
            "src/widgets/mod.rs",
            "src/widgets/cards.rs",
            "plugins/.gitkeep",
            "plugins/README.md",
        ] {
            assert!(
                root.join(rel).exists(),
                "missing expected file: {rel}; got {:?}",
                report.files,
            );
        }
    }

    #[test]
    fn scaffold_project_mod_files_carry_orchestrator_markers() {
        let tmp = tempfile::tempdir().expect("tempdir");
        scaffold_project("blog", tmp.path(), None).expect("scaffold ok");
        let root = tmp.path().join("blog");

        let views_mod = fs::read_to_string(root.join("src/views/mod.rs")).unwrap();
        assert!(
            views_mod.contains("re-export"),
            "views/mod.rs should describe itself as the re-export layer",
        );
        // gaps3 #57. The scaffold used to GENERATE a `fn internal_error` helper into every
        // new app — and that helper hands `err.to_string()` to the browser, so a missing
        // table or a SQL fragment is printed to whoever asked for the page. The scaffold
        // is the first umbral code a developer ever reads; it was teaching the leak.
        //
        // This assertion is deliberately inverted from what it used to be.
        assert!(
            !views_mod.contains("fn internal_error"),
            "the scaffold must NOT generate an internal_error helper — handlers return \
             ApiError, which logs the cause and keeps it off the wire",
        );
        let views_public = fs::read_to_string(root.join("src/views/public.rs")).unwrap();
        assert!(
            views_public.contains("Result<Html<String>, ApiError>")
                && !views_public.contains("map_err(internal_error)"),
            "generated handlers must return ApiError and use a bare `?`",
        );

        let seed_mod = fs::read_to_string(root.join("src/seed/mod.rs")).unwrap();
        assert!(
            seed_mod.contains("pub async fn all()"),
            "seed/mod.rs must declare the all() orchestrator",
        );
        assert!(
            seed_mod.contains("credentials::test_credentials()"),
            "seed::all() must call the credentials step",
        );
        assert!(
            seed_mod.contains("dependency order") || seed_mod.contains("order in which"),
            "seed/mod.rs should explain it pins dependency order",
        );

        let credentials = fs::read_to_string(root.join("src/seed/credentials.rs")).unwrap();
        assert!(
            credentials.contains("fn test_credentials"),
            "credentials.rs must define the test_credentials seed",
        );
        assert!(
            credentials.contains("count().await? > 0"),
            "test_credentials must be idempotent (short-circuit on existing users)",
        );

        let widgets_mod = fs::read_to_string(root.join("src/widgets/mod.rs")).unwrap();
        assert!(
            widgets_mod.contains("pub mod cards;"),
            "widgets/mod.rs must publish the cards submodule",
        );

        let cards = fs::read_to_string(root.join("src/widgets/cards.rs")).unwrap();
        assert!(
            cards.contains("builtin_total_models_widget")
                || cards.contains("builtin_recent_users_widget"),
            "cards.rs should re-export a builtin widget so the dashboard isn't empty",
        );
    }

    #[test]
    fn scaffold_project_main_declares_modules_and_mounts_security() {
        let tmp = tempfile::tempdir().expect("tempdir");
        scaffold_project("blog", tmp.path(), None).expect("scaffold ok");
        let main = fs::read_to_string(tmp.path().join("blog/src/main.rs")).unwrap();

        // The table-of-contents module declarations.
        assert!(
            main.contains("mod views;"),
            "main.rs must declare mod views"
        );
        assert!(main.contains("mod seed;"), "main.rs must declare mod seed");
        assert!(
            main.contains("mod widgets;"),
            "main.rs must declare mod widgets",
        );

        // Routes reference the per-concern handlers.
        assert!(
            main.contains("views::public::home"),
            "route table should wire views::public::home",
        );
        // Boot seeds via the framework seam (gaps4 #47): serve-only,
        // after migrations, idempotent.
        assert!(
            main.contains(".seed_on_serve(seed::all)"),
            "boot should seed via .seed_on_serve(seed::all)",
        );

        // SecurityPlugin mounted by default (gaps2 #25).
        assert!(
            main.contains("SecurityPlugin"),
            "SecurityPlugin must be mounted by default",
        );
    }

    #[test]
    fn scaffold_project_creates_empty_plugins_dir() {
        let tmp = tempfile::tempdir().expect("tempdir");
        scaffold_project("blog", tmp.path(), None).expect("scaffold ok");
        let readme = fs::read_to_string(tmp.path().join("blog/plugins/README.md")).unwrap();
        assert!(
            readme.contains("umbral startplugin"),
            "plugins/README.md should point at the canonical `umbral startplugin`",
        );
    }

    // ----------------------------------------------------------------- //
    // scaffold_app is now a deprecated alias forwarding to scaffold_plugin //
    // ----------------------------------------------------------------- //

    #[test]
    fn scaffold_app_forwards_to_the_plugin_generator() {
        let tmp = tempfile::tempdir().expect("tempdir");
        scaffold_app("posts", tmp.path(), None).expect("scaffold ok");
        let root = tmp.path().join("plugins/posts");

        // The plugin layout (not the old plain views.rs/urls.rs one).
        for rel in [
            "Cargo.toml",
            "README.md",
            "src/lib.rs",
            "src/models.rs",
            "src/handlers.rs",
        ] {
            assert!(root.join(rel).exists(), "missing expected file: {rel}");
        }
        let lib = fs::read_to_string(root.join("src/lib.rs")).unwrap();
        assert!(lib.contains("pub mod models;"), "lib.rs publishes models");
        assert!(
            lib.contains("pub mod handlers;"),
            "lib.rs publishes handlers"
        );
        assert!(lib.contains("PostsPlugin"), "PascalCase plugin name");
    }

    #[test]
    fn scaffold_app_auto_registers_path_dep_in_project_cargo() {
        let tmp = tempfile::tempdir().expect("tempdir");
        // Fixture project Cargo.toml with a [dependencies] section.
        let project_cargo = "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\nserde = \"1\"\n";
        fs::write(tmp.path().join("Cargo.toml"), project_cargo).unwrap();

        let report = scaffold_app("posts", tmp.path(), None).expect("scaffold ok");
        assert_eq!(
            report.cargo_toml_registered,
            Some(true),
            "the path dep should have been added",
        );

        let cargo = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();
        assert!(
            cargo.contains("posts = { path = \"plugins/posts\" }"),
            "project Cargo.toml must gain the plugin path dep; got:\n{cargo}",
        );

        // Idempotent: a second run reports `false` (already present).
        // (Different name would re-add; same name short-circuits.)
        let second = register_dep_in_cargo_toml(&tmp.path().join("Cargo.toml"), "posts").unwrap();
        assert!(!second, "re-registering the same dep must be a no-op");
    }

    #[test]
    fn scaffold_app_still_rejects_reserved_names() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let result = scaffold_app("auth", tmp.path(), None);
        assert!(matches!(result, Err(ScaffoldError::ReservedName(_))));
    }

    #[test]
    fn scaffold_plugin_validates_name_like_startapp() {
        let tmp = tempfile::tempdir().expect("tempdir");
        assert!(matches!(
            scaffold_plugin("2cool", tmp.path(), None),
            Err(ScaffoldError::InvalidName(_))
        ));
        assert!(matches!(
            scaffold_plugin("foo bar", tmp.path(), None),
            Err(ScaffoldError::InvalidName(_))
        ));
    }

    // ----------------------------------------------------------------- //
    // startcommand (gaps3 #81)                                           //
    // ----------------------------------------------------------------- //

    /// A real scaffolded project to run `startcommand` against — the same
    /// `main.rs` a user gets from `umbral startproject`, so the wiring
    /// surgery is exercised against the file it actually has to edit, not a
    /// fixture written to make the test pass.
    fn project(tmp: &tempfile::TempDir) -> PathBuf {
        scaffold_project("demo", tmp.path(), None).expect("scaffold_project");
        tmp.path().join("demo")
    }

    fn read(root: &Path, rel: &str) -> String {
        fs::read_to_string(root.join(rel)).unwrap_or_else(|e| panic!("read {rel}: {e}"))
    }

    #[test]
    fn startcommand_root_writes_the_command_and_wires_main() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);

        let report =
            scaffold_command("backfill_slugs", &CommandTarget::Root, &root).expect("scaffold");
        assert!(
            report
                .files
                .contains(&PathBuf::from("src/commands/backfill_slugs.rs"))
        );
        assert!(report.files.contains(&PathBuf::from("src/commands/mod.rs")));

        // The command file: right struct, right trait, framework's clap.
        let cmd = read(&root, "src/commands/backfill_slugs.rs");
        assert!(cmd.contains("pub struct BackfillSlugsCommand;"), "{cmd}");
        assert!(
            cmd.contains("impl PluginCommand for BackfillSlugsCommand"),
            "{cmd}"
        );
        assert!(
            cmd.contains("use umbral::cli::{CliError, PluginCommand, clap};"),
            "the generated file must import the framework's clap, not its own: {cmd}"
        );
        assert!(
            cmd.contains(r#"clap::Command::new("backfill_slugs")"#),
            "{cmd}"
        );

        // The registry.
        let registry = read(&root, "src/commands/mod.rs");
        assert!(registry.contains("pub mod backfill_slugs;"), "{registry}");
        assert!(
            registry.contains("Box::new(backfill_slugs::BackfillSlugsCommand),"),
            "{registry}"
        );

        // The wiring: main.rs declares the module AND registers the registry.
        let main_rs = read(&root, "src/main.rs");
        assert!(
            main_rs.contains("mod commands;"),
            "main.rs never declared the module: {main_rs}"
        );
        assert!(
            main_rs.contains(".commands(commands::all())"),
            "main.rs never registered the command registry: {main_rs}"
        );
        // ...and it goes INSIDE the builder chain, before the terminal build.
        let reg = main_rs.find(".commands(commands::all())").unwrap();
        let build = main_rs.find(".build_deferred()").unwrap();
        assert!(
            reg < build,
            "`.commands(...)` landed after `.build_deferred()`, which doesn't compile"
        );
    }

    /// The whole reason `all()` exists: the SECOND command is free. It
    /// appends to the registry and touches `main.rs` exactly zero more
    /// times — no duplicate `mod commands;`, no second `.commands(...)`
    /// call (which wouldn't compile as a duplicate... it would silently
    /// register the same list twice).
    #[test]
    fn startcommand_second_command_appends_and_leaves_main_alone() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);

        scaffold_command("backfill_slugs", &CommandTarget::Root, &root).expect("first");
        let main_after_first = read(&root, "src/main.rs");
        scaffold_command("import-prices", &CommandTarget::Root, &root).expect("second");
        let main_after_second = read(&root, "src/main.rs");

        assert_eq!(
            main_after_first, main_after_second,
            "the second startcommand edited main.rs again"
        );

        let registry = read(&root, "src/commands/mod.rs");
        assert!(registry.contains("pub mod backfill_slugs;"), "{registry}");
        // A hyphenated command name becomes a snake_case module and a
        // PascalCase struct, while the CLI name keeps its hyphen.
        assert!(registry.contains("pub mod import_prices;"), "{registry}");
        assert!(
            registry.contains("Box::new(import_prices::ImportPricesCommand),"),
            "{registry}"
        );
        let cmd = read(&root, "src/commands/import_prices.rs");
        assert!(
            cmd.contains(r#"clap::Command::new("import-prices")"#),
            "the clap name should be what the user typed, hyphens and all: {cmd}"
        );

        assert_eq!(
            main_after_second
                .matches(".commands(commands::all())")
                .count(),
            1,
            "main.rs registered the registry twice"
        );
        assert_eq!(
            main_after_second.matches("\nmod commands;").count(),
            1,
            "main.rs declared `mod commands;` twice"
        );
    }

    #[test]
    fn startcommand_plugin_writes_the_command_and_wires_the_plugin() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        scaffold_app("blog", &root, None).expect("scaffold_app");

        scaffold_command("reindex", &CommandTarget::Plugin("blog".to_string()), &root)
            .expect("scaffold");

        let plugin_root = root.join("plugins/blog");
        let registry = read(&plugin_root, "src/commands/mod.rs");
        assert!(registry.contains("pub mod reindex;"), "{registry}");
        assert!(
            registry.contains("Box::new(reindex::ReindexCommand),"),
            "{registry}"
        );

        let lib_rs = read(&plugin_root, "src/lib.rs");
        assert!(lib_rs.contains("pub mod commands;"), "{lib_rs}");
        assert!(
            lib_rs.contains("fn commands(&self) -> Vec<Box<dyn umbral::cli::PluginCommand>>"),
            "the plugin never got a `Plugin::commands()` impl: {lib_rs}"
        );
        assert!(
            lib_rs.contains("commands::all()"),
            "the impl doesn't return the registry: {lib_rs}"
        );
        // The method has to land INSIDE the impl block, not after it.
        let impl_start = lib_rs.find("impl Plugin for BlogPlugin {").unwrap();
        let method = lib_rs.find("fn commands(&self)").unwrap();
        assert!(method > impl_start, "the method landed outside the impl");
    }

    /// `umbral startcommand move` used to sail through validation and write
    /// `pub mod move;` into the registry — a syntax error in a file the user
    /// never touched. `scaffold_command` was still calling a private copy of
    /// the name rules that predated the keyword guard, so the codegen test
    /// asserting the correct behaviour passed while the CLI shipped the wrong
    /// one. Found by the pre-0.0.10 review sweep.
    #[test]
    fn startcommand_rejects_a_rust_keyword_as_a_command_name() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        for kw in ["move", "type", "match"] {
            assert!(
                matches!(
                    scaffold_command(kw, &CommandTarget::Root, &root),
                    Err(ScaffoldError::InvalidName(_))
                ),
                "`{kw}` is a Rust keyword — `pub mod {kw};` does not parse"
            );
        }
    }

    /// A command name that's already a framework built-in would SHADOW it:
    /// dispatch tries app/plugin commands before the built-in clap parser.
    /// `migrate` would stop migrating, silently. Reject it where the fix is
    /// free.
    #[test]
    fn startcommand_rejects_a_builtin_command_name() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        for taken in ["migrate", "serve", "makemigrations", "dev"] {
            assert!(
                matches!(
                    scaffold_command(taken, &CommandTarget::Root, &root),
                    Err(ScaffoldError::ReservedCommandName(_))
                ),
                "`{taken}` is a built-in and must be rejected"
            );
        }
    }

    /// Same shadowing hazard, but for a command a built-in *plugin* ships.
    /// These can't be read off a clap parser (they only exist on a built
    /// App), so they're listed — and the list has to be honoured.
    #[test]
    fn startcommand_rejects_a_builtin_plugin_command_name() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        assert!(matches!(
            scaffold_command("createsuperuser", &CommandTarget::Root, &root),
            Err(ScaffoldError::ReservedCommandName(_))
        ));
        assert!(matches!(
            scaffold_command("tasks-worker", &CommandTarget::Root, &root),
            Err(ScaffoldError::ReservedCommandName(_))
        ));
    }

    /// The reserved set is derived from the clap parser, so a subcommand
    /// added to `Command` in lib.rs reserves its own name with no second
    /// list to remember to update.
    #[test]
    fn reserved_command_names_are_read_off_the_real_parser() {
        let names = reserved_command_names();
        for expected in ["migrate", "serve", "typegen", "squashmigrations", "help"] {
            assert!(
                names.iter().any(|n| n == expected),
                "`{expected}` missing from the reserved set: {names:?}"
            );
        }
    }

    #[test]
    fn startcommand_rejects_an_unknown_plugin_and_lists_the_real_ones() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        scaffold_app("blog", &root, None).expect("scaffold_app");

        let err = scaffold_command("reindex", &CommandTarget::Plugin("blgo".into()), &root)
            .expect_err("a typo'd plugin name must not scaffold anything");
        match err {
            ScaffoldError::NoSuchPlugin { asked, available } => {
                assert_eq!(asked, "blgo");
                assert_eq!(available, vec!["blog".to_string()]);
            }
            other => panic!("expected NoSuchPlugin, got {other:?}"),
        }
    }

    #[test]
    fn startcommand_refuses_to_overwrite_an_existing_command() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        scaffold_command("reindex", &CommandTarget::Root, &root).expect("first");
        assert!(matches!(
            scaffold_command("reindex", &CommandTarget::Root, &root),
            Err(ScaffoldError::AlreadyExists(_))
        ));
    }

    #[test]
    fn startcommand_outside_a_project_says_so() {
        let tmp = tempfile::tempdir().expect("tempdir");
        assert!(matches!(
            scaffold_command("reindex", &CommandTarget::Root, tmp.path()),
            Err(ScaffoldError::NotAProject(_))
        ));
    }

    #[test]
    fn discover_plugins_lists_plugin_crates_only() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        // A fresh project has an empty `plugins/` (a .gitkeep + README, no crates).
        assert!(discover_plugins(&root).is_empty());

        scaffold_app("blog", &root, None).expect("scaffold_app");
        scaffold_app("shop", &root, None).expect("scaffold_app");
        // A stray directory with no Cargo.toml isn't a plugin and must not be
        // offered as a home for a command.
        fs::create_dir_all(root.join("plugins/notacrate")).unwrap();

        assert_eq!(
            discover_plugins(&root),
            vec!["blog".to_string(), "shop".to_string()]
        );
    }

    // ----------------------------------------------------------------- //
    // Regressions found by the pre-0.0.10 review sweep                    //
    // ----------------------------------------------------------------- //

    /// The `.build()` anchor must belong to the **App** chain. A main.rs that
    /// builds anything else first (an HTTP client, a subscriber, a pool) used
    /// to capture the insertion: `.commands(commands::all())` was spliced into
    /// `reqwest::Client::builder()`, which has no such method. The user's
    /// main.rs stopped compiling — in code they never wrote — and the tool
    /// printed "Registered".
    #[test]
    fn startcommand_does_not_splice_into_someone_elses_builder_chain() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);

        let main_rs = root.join("src/main.rs");
        let original = read(&root, "src/main.rs");
        // A second builder chain, ABOVE the App's, whose terminal `.build()?`
        // is the first one in the file.
        let with_client = original.replace(
            "    let settings = Settings::from_env()?;",
            "    let client = reqwest::Client::builder()\n\
             \x20       .timeout(Duration::from_secs(5))\n\
             \x20       .build()?;\n\n\
             \x20   let settings = Settings::from_env()?;",
        );
        assert_ne!(with_client, original, "fixture did not apply");
        fs::write(&main_rs, &with_client).unwrap();

        scaffold_command("import_prices", &CommandTarget::Root, &root).expect("scaffold");

        let after = read(&root, "src/main.rs");
        let commands_at = after.find(".commands(commands::all())").expect("wired");
        let client_build_at = after.find(".build()?;").expect("client chain still there");
        let app_builder_at = after.find("App::builder()").expect("app chain still there");

        assert!(
            commands_at > client_build_at,
            "`.commands(...)` was spliced into the reqwest chain:\n{after}"
        );
        assert!(
            commands_at > app_builder_at,
            "`.commands(...)` landed outside the App::builder() chain:\n{after}"
        );
    }

    /// No `App::builder()` to anchor on → decline, and say so. The command file
    /// is still written; the user is told the two lines to add.
    #[test]
    fn startcommand_declines_when_there_is_no_app_builder_chain() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        fs::write(
            root.join("src/main.rs"),
            "mod seed;\n\nfn main() {\n    println!(\"no app here\");\n}\n",
        )
        .unwrap();

        let report = scaffold_command("backfill", &CommandTarget::Root, &root).expect("scaffold");

        assert_eq!(
            report.registered,
            Some(false),
            "the tool must not claim a registration it could not perform"
        );
        let steps = report.next_steps.join("\n");
        assert!(steps.contains(".commands(commands::all())"), "{steps}");
        assert!(root.join("src/commands/backfill.rs").is_file());
    }

    /// A partially-wired file must keep the edit it DID make, and the steps must
    /// name what it could not. The old code inserted `mod commands;` into a
    /// local copy, then returned `Manual` and threw the copy away — while
    /// printing only the `.commands(...)` line. The user pasted it and got
    /// `failed to resolve: use of undeclared module `commands``.
    #[test]
    fn startcommand_keeps_the_module_declaration_it_managed_to_add() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        // Has a `mod x;` line (so the module CAN be declared) but no App chain
        // (so the builder call cannot be inserted).
        fs::write(
            root.join("src/main.rs"),
            "mod seed;\n\nfn main() {\n    println!(\"no app\");\n}\n",
        )
        .unwrap();

        let report = scaffold_command("backfill", &CommandTarget::Root, &root).expect("scaffold");

        let after = read(&root, "src/main.rs");
        assert!(
            after.contains("mod commands;"),
            "the module declaration the tool made was thrown away: {after}"
        );
        assert_eq!(report.registered, Some(false));
        assert!(
            report
                .next_steps
                .join("\n")
                .contains(".commands(commands::all())"),
            "the user was not told the one step that remained"
        );
    }

    /// A multi-line `impl Plugin for X` header (a `where` clause, or rustfmt
    /// wrapping a long one) must not get the method spliced in before its `{`.
    #[test]
    fn startcommand_declines_a_plugin_impl_whose_brace_is_on_the_next_line() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        scaffold_app("blog", &root, None).expect("scaffold_app");

        let lib_rs = root.join("plugins/blog/src/lib.rs");
        fs::write(
            &lib_rs,
            "pub mod models;\n\npub struct BlogPlugin;\n\n\
             impl Plugin for BlogPlugin\nwhere\n    Self: Send,\n{\n    \
             fn name(&self) -> &'static str {\n        \"blog\"\n    }\n}\n",
        )
        .unwrap();

        let report = scaffold_command("reindex", &CommandTarget::Plugin("blog".to_string()), &root)
            .expect("scaffold");

        let after = read(&root, "plugins/blog/src/lib.rs");
        // The impl header is untouched: no method between it and its `where`.
        assert!(
            after.contains("impl Plugin for BlogPlugin\nwhere\n    Self: Send,\n{"),
            "the generator spliced a method into a multi-line impl header:\n{after}"
        );
        assert_eq!(report.registered, Some(false));
        assert!(
            report.next_steps.join("\n").contains("fn commands"),
            "the user was not told to add the method by hand"
        );
    }

    /// The module declaration and the `all()` entry are checked INDEPENDENTLY.
    /// The old early-return took "`pub mod x;` is present" as proof the registry
    /// entry was too, skipped it, and still reported success — so `all()` never
    /// returned the command and `cargo run -- x` said "unknown command".
    #[test]
    fn startcommand_repairs_a_registry_missing_only_its_entry() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        scaffold_command("backfill", &CommandTarget::Root, &root).expect("first");

        // Simulate the drift: the module is declared, the entry is gone.
        let mod_rs = root.join("src/commands/mod.rs");
        let text = read(&root, "src/commands/mod.rs")
            .lines()
            .filter(|l| !l.contains("Box::new(backfill::BackfillCommand)"))
            .collect::<Vec<_>>()
            .join("\n");
        fs::write(&mod_rs, format!("{text}\n")).unwrap();
        fs::remove_file(root.join("src/commands/backfill.rs")).unwrap();

        let report = scaffold_command("backfill", &CommandTarget::Root, &root).expect("re-run");

        let registry = read(&root, "src/commands/mod.rs");
        assert_eq!(
            registry.matches("pub mod backfill;").count(),
            1,
            "duplicate module declaration:\n{registry}"
        );
        assert!(
            registry.contains("Box::new(backfill::BackfillCommand),"),
            "the registry entry was never restored, but the command reports as \
             registered:\n{registry}"
        );
        assert_eq!(report.registered, Some(true));
    }

    /// When a user has restructured `commands/mod.rs` past recognition, the
    /// tool must not "helpfully" rewrite a file it doesn't understand. It
    /// writes the command and hands back the two lines to add.
    #[test]
    fn startcommand_reports_manual_steps_when_the_registry_markers_are_gone() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = project(&tmp);
        scaffold_command("first", &CommandTarget::Root, &root).expect("first");

        let mod_rs = root.join("src/commands/mod.rs");
        let mangled = read(&root, "src/commands/mod.rs")
            .lines()
            .filter(|l| !l.trim().starts_with("// umbral:startcommand"))
            .collect::<Vec<_>>()
            .join("\n");
        fs::write(&mod_rs, &mangled).unwrap();

        let report = scaffold_command("second", &CommandTarget::Root, &root).expect("second");

        // The registry was NOT touched...
        assert_eq!(read(&root, "src/commands/mod.rs"), mangled);
        // ...and the user was told exactly what to add.
        let steps = report.next_steps.join("\n");
        assert!(steps.contains("pub mod second;"), "{steps}");
        assert!(steps.contains("Box::new(second::SecondCommand)"), "{steps}");
    }
}