rustlavel-cli 0.8.2

The rustlavel command-line tool: new, serve, make:*
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
//! `rustlavel new <app>` — scaffold an application.
//!
//! Deliberately slim, following Laravel 11+: routes, one controller, config,
//! public, tests. Everything else arrives when a package is added.

use crate::auth_kit;
use crate::naming;
use crate::stubs::{self, render};
use crate::console;
use crate::ask;
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// The packages `--with` can turn on, and what each one needs on disk.
const PACKAGES: &[(&str, &[&str])] = &[
    ("ai", &[]),
    // Not a crate of its own: `auth-kit` writes a working sign-in, roles and
    // an administration area into the project, and turns on the packages that
    // code needs.
    ("audit", &["database/migrations"]),
    ("auth", &["storage/sessions"]),
    ("auth-kit", &["storage/sessions", "resources/views", "public/css", "public/js"]),
    ("billing", &["database/migrations"]),
    ("cache", &["storage/cache"]),
    ("chart", &[]),
    ("client", &[]),
    ("db", &["database/migrations", "database/seeders"]),
    ("debugbar", &[]),
    ("discovery", &[]),
    // Not a crate of its own: three files added to the auth kit, plus the two
    // packages they import. See `auth_kit::DISCOVERY_FILES`.
    ("discovery-ui", &[]),
    ("flags", &[]),
    ("gateway", &[]),
    ("i18n", &["lang"]),
    ("ldap", &[]),
    ("ledger", &["database/migrations"]),
    ("mail", &["resources/views"]),
    ("mcp", &[]),
    ("metrics", &[]),
    // Not a crate of its own: a workspace of three services, expanded into the
    // packages their code imports. See `microservices_kit`.
    ("microservices-kit", &[]),
    ("model-cache", &[]),
    ("oauth", &["storage/sessions"]),
    ("oauth-provider", &["storage/sessions"]),
    ("openapi", &[]),
    ("otel", &[]),
    ("payment", &["database/migrations"]),
    ("queue", &["database/migrations"]),
    ("rbac", &["database/migrations"]),
    // Not a crate of its own: it turns on `rustlavel-auth`'s Redis session
    // store and the cache package the client lives in. Wiring it is a line in
    // `main.rs`, which is why it is in `NEEDS_WIRING` too.
    ("redis-sessions", &[]),
    ("search", &[]),
    ("sqlite", &["database/migrations"]),
    ("storage", &["storage/app"]),
    ("telescope", &[]),
    ("validation", &[]),
    // The same driver as `cache`, under the name of the server you are actually
    // running. Turns on the cache package and writes a configuration that
    // points at Valkey rather than at the memory driver.
    ("valkey", &["storage/cache"]),
    ("vault", &[]),
    ("view", &["resources/views"]),
    ("webauthn", &["storage/sessions"]),
    ("ws", &[]),
];

pub fn run(args: &[String]) -> Result<(), String> {
    let mut name = None;
    let mut local_framework: Option<String> = None;
    let mut packages: Vec<String> = Vec::new();
    let mut chose_packages = false;
    let mut ask_nothing = false;

    let mut iter = args.iter();
    while let Some(arg) = iter.next() {
        match arg.as_str() {
            // Point the new app at a framework checkout instead of crates.io,
            // which is what the framework's own smoke tests need.
            "--local" => {
                local_framework =
                    Some(iter.next().ok_or("--local needs a path to the framework workspace")?.clone())
            }
            // `rustlavel new blog --with db,view` is the scaffold-time form of
            // `cargo add`: the same opt-in, chosen up front.
            "--with" => {
                let list = iter.next().ok_or("--with needs a comma-separated list of packages")?;
                for requested in list.split(',').map(str::trim).filter(|p| !p.is_empty()) {
                    if !PACKAGES.iter().any(|(known, _)| *known == requested) {
                        return Err(format!(
                            "`{requested}` is not a package. Available: {}",
                            PACKAGES.iter().map(|(name, _)| *name).collect::<Vec<_>>().join(", ")
                        ));
                    }
                    packages.push(requested.to_string());
                }
                chose_packages = true;
            }
            "--all" => {
                packages = PACKAGES.iter().map(|(name, _)| (*name).to_string()).collect();
                chose_packages = true;
            }
            // For a script, and for anybody who would rather not be asked.
            "--yes" | "-y" | "--no-input" => ask_nothing = true,
            other if other.starts_with('-') => return Err(format!("unknown option `{other}`")),
            other => name = Some(other.to_string()),
        }
    }

    // Asked for rather than refused, when there is somebody to ask. A person
    // who typed `rustlavel new` and meant it should not have to read a usage
    // line to find out the command wanted one more word.
    let name = match name {
        Some(given) => given,
        None if ask::interactive() && !ask_nothing => {
            let given = ask::text("What is the project called?", "app");
            if given.trim().is_empty() {
                return Err("a project needs a name.".into());
            }
            given.trim().to_string()
        }
        None => {
            return Err(
                "usage: rustlavel new <name> [--with db,view] [--all] [--yes] [--local <path>]"
                    .into(),
            );
        }
    };

    // Nothing was asked for, and there is somebody there to ask. Everything
    // below this point is the same whether the answers came from the flags or
    // from the questions.
    if !chose_packages && !ask_nothing {
        packages = interview();
    }
    // Kept before `auth-kit` is expanded into the nine packages it implies, so
    // the summary shows what somebody chose rather than what that turned into.
    let chosen = packages.clone();

    // `auth-kit` is scaffolding rather than a feature flag, so it is expanded
    // into the packages its generated code actually imports and then dropped
    // from the list passed to Cargo.
    let auth_kit = packages.iter().any(|p| p == "auth-kit");
    if auth_kit {
        for required in auth_kit::REQUIRED_PACKAGES {
            packages.push((*required).to_string());
        }
        packages.retain(|p| p != "auth-kit");
    }

    // The discovery dashboard: three files and two packages, and only for a
    // kit — on its own it would be a page in an application with no layout to
    // put it in.
    let discovery_ui = packages.iter().any(|p| p == "discovery-ui");
    if discovery_ui {
        for required in auth_kit::DISCOVERY_PACKAGES {
            packages.push((*required).to_string());
        }
        packages.retain(|p| p != "discovery-ui");
    }

    // The same treatment for the microservices kit: scaffolding, not a flag.
    let microservices = packages.iter().any(|p| p == "microservices-kit");
    if microservices {
        for required in crate::microservices_kit::REQUIRED_PACKAGES {
            packages.push((*required).to_string());
        }
        packages.retain(|p| p != "microservices-kit");
    }

    packages.sort();
    packages.dedup();

    let crate_name = naming::snake(&name);
    let root = PathBuf::from(&name);

    if root.exists() {
        return Err(format!("`{name}` already exists"));
    }

    let source = match &local_framework {
        Some(path) => {
            let absolute = std::fs::canonicalize(path)
                .map_err(|e| format!("cannot resolve --local path `{path}`: {e}"))?;
            format!("path = \"{}/crates/rustlavel\"", absolute.display())
        }
        None => format!("version = \"{}\"", env!("CARGO_PKG_VERSION")),
    };

    let dependency = if packages.is_empty() {
        source
    } else {
        let list = packages.iter().map(|p| format!("\"{p}\"")).collect::<Vec<_>>().join(", ");
        format!("{source}, features = [{list}]")
    };

    let mut values = BTreeMap::new();
    // `auth-kit` writes its own `main.rs`, and that file already registers two
    // of these — naming them again as owed would tell somebody to add a line
    // that is four lines above.
    let already: &[&str] = if auth_kit { &["rbac", "audit", "i18n"] } else { &[] };
    values.insert("plugins", plugin_lines(&packages, already));
    // A `DATABASE_URL` for the engine that was chosen, so somebody who said
    // "MySQL" is not handed a PostgreSQL line to correct. Blank when nothing
    // in this project uses a database, rather than a commented-out URL that
    // looks like a setting somebody turned off.
    values.insert(
        "database",
        match packages.iter().any(|p| p == "db") {
            true => format!("\n{}\n", database_url_line()),
            false => String::new(),
        },
    );
    // The module slots in the kit. Empty unless the dashboard was asked for —
    // and empty is the whole of what "not asked for" means: no file, no
    // dependency, no permission check per page.
    let wired = discovery_ui && auth_kit;
    if discovery_ui && !auth_kit {
        // Said out loud rather than written anyway. The dashboard is three
        // files that extend the kit's layout and use its permissions; dropping
        // them into a project with neither would not compile. Doing nothing
        // quietly is the shape this scaffold keeps having to remove.
        console::info(
            "`discovery-ui` needs `auth-kit` — it is a page in the kit's admin area. \
             The discovery package is enabled; the page was not written.",
        );
    }
    // The four module slots, from the one place that defines them.
    for (slot, value) in auth_kit::module_slots(wired) {
        values.insert(slot, value);
    }
    values.insert("name", crate_name.clone());
    values.insert("crate_name", crate_name.clone());
    values.insert("app_name", naming::pascal(&name));
    values.insert("dependency", dependency);

    // The last chance to say no, and it only appears when the answers came
    // from questions: somebody who typed `--with db,view` has already said
    // what they want and does not need to say it twice.
    if !chose_packages && !ask_nothing && ask::interactive() {
        let summary = match chosen.is_empty() {
            true => "no packages".to_string(),
            false => chosen.join(", "),
        };
        println!();
        console::info(&format!("{} with {summary}", console::bold(&name)));
        if !ask::confirm("Create it?", true) {
            console::info("Nothing was written.");
            return Ok(());
        }
    }

    console::heading(&format!("Creating {}", console::accent(&name)));

    let files: &[(&str, &str)] = &[
        ("Cargo.toml", stubs::CARGO_TOML),
        (".gitignore", stubs::GITIGNORE),
        (".env", stubs::ENV),
        (".env.example", stubs::ENV),
        ("README.md", stubs::README),
        ("CLAUDE.md", stubs::AGENT_NOTES),
        ("config/app.json", stubs::CONFIG_APP),
        ("public/README.md", stubs::PUBLIC_KEEP),
        (
            "src/main.rs",
            // With the database package, main.rs also registers the generated
            // migration and seeder lists.
            if packages.iter().any(|p| p == "db") { stubs::MAIN_RS_DB } else { stubs::MAIN_RS },
        ),
        ("src/routes/mod.rs", stubs::ROUTES_MOD),
        ("src/routes/web.rs", stubs::ROUTES_WEB),
        ("src/controllers/mod.rs", stubs::CONTROLLERS_MOD),
        ("src/controllers/welcome_controller.rs", stubs::WELCOME_CONTROLLER),
        ("tests/web.rs", stubs::TEST_STUB),
    ];

    // The microservices kit is a workspace, not an application: it has no
    // `src/` of its own, and the ordinary scaffold's `Cargo.toml` is the wrong
    // shape for a workspace root. It replaces this rather than layering on it,
    // which is the difference between it and `auth-kit` — that one augments an
    // application, this one *is* the project.
    if !microservices {
        for (path, template) in files {
            write(&root.join(path), &render(template, &values))?;
            console::created(path);
        }
    }

    // Everything from here to the packages loop belongs to an *application*:
    // one crate, with a library beside its binary and one set of database
    // registries. The microservices kit's root is a workspace, where a `src/`
    // belongs to no member and a `database/` to no service — each has its own.
    // A `src/lib.rs` at a workspace root is not merely untidy: it is a crate
    // nothing declares, which is exactly the sort of thing somebody later
    // spends an afternoon on.
    //
    // `tests/web.rs` reaches into the app's modules, which requires a library
    // target beside the binary.
    let lib = if packages.iter().any(|p| p == "db") {
        format!("{LIB_RS}pub mod database;\n")
    } else {
        LIB_RS.to_string()
    };
    if !microservices {
        write(&root.join("src/lib.rs"), &lib)?;
        console::created("src/lib.rs");
    }

    // The database package needs its generated registries to exist before the
    // first build, since main.rs names them.
    if packages.iter().any(|p| p == "db") && !microservices {
        let empty: BTreeMap<&str, String> =
            [("modules", String::new()), ("entries", String::new())].into_iter().collect();

        write(
            &root.join("database/migrations/mod.rs"),
            &render(stubs::MIGRATIONS_REGISTRY, &empty),
        )?;
        write(&root.join("database/seeders/mod.rs"), &render(stubs::SEEDERS_REGISTRY, &empty))?;
        write(&root.join("src/database.rs"), DATABASE_BRIDGE)?;
        console::created("database/migrations/mod.rs");
        console::created("database/seeders/mod.rs");
        console::created("src/database.rs");
    }

    // A package that needs a directory gets one now, so the first run does not
    // fail on a path that was only ever going to be created by hand.
    //
    // Not for the microservices kit: those directories belong to an
    // application, and the kit's root is a workspace. `storage/sessions` at the
    // root of a workspace belongs to no service and would be written to by
    // none of them.
    for (package, directories) in PACKAGES.iter().filter(|_| !microservices) {
        if !packages.iter().any(|enabled| enabled == package) {
            continue;
        }
        for directory in *directories {
            std::fs::create_dir_all(root.join(directory))
                .map_err(|e| format!("cannot create {directory}: {e}"))?;
            write(&root.join(directory).join(".gitkeep"), "")?;
            console::created(directory);
        }
    }

    // The cache package reads `cache.*` from configuration, and configuration
    // only knows what a file under `config/` declares. Without this file
    // `CACHE_DRIVER=redis` in `.env` reaches nothing and the application runs on
    // the memory driver — silently, because the memory driver works.
    if packages.iter().any(|p| p == "cache" || p == "valkey") && !microservices {
        write(&root.join("config/cache.json"), &render(stubs::CONFIG_CACHE, &values))?;
        console::created("config/cache.json");

        for file in [".env", ".env.example"] {
            let path = root.join(file);
            let mut contents = std::fs::read_to_string(&path).unwrap_or_default();
            contents.push_str(&render(stubs::ENV_CACHE, &values));
            write(&path, &contents)?;
        }
    }

    // The mail package reads `mail.*` from configuration, and configuration
    // only knows what a file under `config/` declares. Without this the whole
    // `MAIL_*` block in `.env` is inert: the mailer uses its defaults while the
    // settings screen, which reads the environment directly, reports that the
    // environment is in charge.
    if packages.iter().any(|p| p == "mail") {
        write(&root.join("config/mail.json"), stubs::CONFIG_MAIL)?;
        console::created("config/mail.json");

        for file in [".env", ".env.example"] {
            let path = root.join(file);
            let mut contents = std::fs::read_to_string(&path).unwrap_or_default();
            contents.push_str(&render(stubs::ENV_MAIL, &values));
            write(&path, &contents)?;
        }
    }

    if microservices {
        // A workspace of three services and one shared crate. Every file goes
        // through `render`, like the auth kit's — nothing is written from a
        // constant, because that split is what let 0.7.0 ship a placeholder.
        for (path, contents) in crate::microservices_kit::FILES {
            write(&root.join(path), &render(contents, &values))?;
        }
        console::created("services/gateway, services/auth, services/api");
        console::created("shared/ — what crosses between them, and nothing else");

        for file in [".env", ".env.example"] {
            let path = root.join(file);
            let mut contents = std::fs::read_to_string(&path).unwrap_or_default();
            contents.push_str(&render(crate::microservices_kit::ENV_ADDITIONS, &values));
            write(&path, &contents)?;
        }
        crate::upgrade::write_manifest(&root, "microservices-kit", env!("CARGO_PKG_VERSION"))?;
    }

    if auth_kit {
        for (path, contents) in auth_kit::FILES {
            // Rendered rather than copied: `tests/web.rs` names the crate, and
            // the crate is only known here. Nothing else in the kit holds a
            // `{{placeholder}}` — the views use `{{ spaced }}` for their own
            // variables, which this does not touch.
            write(&root.join(path), &render(contents, &values))?;
        }
        if wired {
            for (path, contents) in auth_kit::DISCOVERY_FILES {
                write(&root.join(path), &render(contents, &values))?;
            }
            console::created("src/modules/discovery/ (the service registry dashboard)");
        }

        // The font, byte for byte: not through `render`, which would rewrite
        // whatever inside a woff2 happened to look like a placeholder.
        for (path, bytes) in auth_kit::BINARY_FILES {
            write_bytes(&root.join(path), bytes)?;
        }
        console::created("src/controllers/auth/ (sign in, register, reset, two-factor)");
        console::created("src/controllers/admin/ (users, roles, permissions)");
        console::created("resources/views/ (every page, Tailwind)");
        console::created("public/css/app.css, public/js/app.js");
        console::created("public/fonts/ (Inter, self-hosted, OFL)");
        console::created("database/migrations/ (users, tokens, sign-in log, factors)");

        // The kit's own main.rs, lib.rs, registries, seeder and config are in
        // `FILES` with everything else, so the loop above has already written
        // them over the plain ones the scaffold produced. They are named here
        // only because they are worth seeing go by.
        console::created("src/main.rs, database/seeders/auth_kit_seeder.rs");
        console::created("config/auth.json, config/rbac.json, config/webauthn.json");

        for file in [".env", ".env.example"] {
            let path = root.join(file);
            let mut contents = std::fs::read_to_string(&path).unwrap_or_default();
            contents.push_str(auth_kit::ENV_ADDITIONS);
            write(&path, &contents)?;
        }

        // Which version wrote these files. `rustlavel upgrade` reads it to
        // know which published kit to reconcile against, and without it there
        // is no base and so no merge — which is why it is written here rather
        // than left for somebody to remember later.
        crate::upgrade::write_manifest(&root, "auth-kit", env!("CARGO_PKG_VERSION"))?;
        console::created(".rustlavel/manifest.json");
    }

    let enabled = if packages.is_empty() {
        String::new()
    } else {
        format!("\n  Packages: {}", packages.join(", "))
    };

    console::success(&format!(
        "Created {name}.{enabled}\n\n  cd {name}\n  rustlavel serve"
    ));
    Ok(())
}

/// The application's own crate root, so tests and the binary share modules.
const LIB_RS: &str = r#"pub mod controllers;
pub mod routes;
"#;

/// `database/` sits outside `src/`, so a module points at it.
const DATABASE_BRIDGE: &str = r#"//! Generated by the rustlavel CLI: bridges `database/` into the crate.

#[path = "../database/migrations/mod.rs"]
pub mod migrations;

#[path = "../database/seeders/mod.rs"]
pub mod seeders;
"#;

/// The same, for a file that is not text.
fn write_bytes(path: &Path, bytes: &[u8]) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
    }
    std::fs::write(path, bytes).map_err(|e| format!("cannot write {}: {e}", path.display()))
}

fn write(path: &Path, contents: &str) -> Result<(), String> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
    }
    std::fs::write(path, contents).map_err(|e| format!("cannot write {}: {e}", path.display()))
}

const REGISTERABLE: &[(&str, &str)] = &[
    ("telescope", "Telescope::new()"),
    ("debugbar", "DebugBar::new()"),
    ("metrics", "Metrics::new()"),
    ("otel", "OpenTelemetry::new()"),
];
/// Needs something `main.rs` does not have yet, so it gets a comment.
const NEEDS_WIRING: &[(&str, &str)] = &[
    ("rbac", "Rbac::from_config(db.clone(), app.config())?"),
    ("audit", "rustlavel::audit::Audit::new(db.clone())"),
    ("flags", "FeatureFlags::new(flags)"),
    ("vault", "Vault::from_config(app.config())?"),
    // A bare `Gateway::new()` routes nothing, so inserting one would register a
    // plugin that does nothing — the shape this project keeps having to remove.
    // The note says what to write instead.
    (
        "gateway",
        "Gateway::new().route(\"/api/*\", Upstream::at(&env_or(\"API_URL\", \"http://127.0.0.1:9002\")))",
    ),
    // Not a plugin but application state, so the note names the `.state`
    // line rather than a `.plugin(...)` one. Without it `--with cache` compiled
    // the crate, wrote its configuration, and left `main.rs` silent about how
    // any of it is reached — a package switched on and used by nothing.
    ("cache", "app.state(CacheStore::from_config(app.config())?) — then `req.state::<CacheStore>()` in a handler"),
    ("valkey", "app.state(CacheStore::from_config(app.config())?) — reads CACHE_URL, which points at Valkey"),
    // Two things in one package, and the common one is not the registry. Most
    // projects asking for discovery want to *join* one — so the note shows the
    // registrar. `RegistryServer::new()` is the other line, and a project that
    // wants it is a project whose whole job is being the registry.
    (
        "discovery",
        "Registrar::new(vec![env_or(\"DISCOVERY_URL\", \"http://127.0.0.1:8761\")], Instance::new(\"my-service\", \"127.0.0.1\", 9000)) — then `Arc::new(it).start()`, or `RegistryServer::new()` to *be* the registry",
    ),
    // Not a plugin but a session store, so the note names the store rather
    // than a `.plugin(...)` line. Without it, `--with redis-sessions` would
    // compile the store in and leave the application on the file store — a
    // feature that looks enabled and does nothing.
    (
        "redis-sessions",
        "SessionManager::from_config(app.config(), RedisSessions::connect(&env_or(\"REDIS_URL\", \"redis://127.0.0.1:6379\"))?)?",
    ),
    // `QueueDashboard::new` takes an `Arc<dyn Queue>`, not a database —
    // the comment used to say otherwise, and anybody pasting it got a
    // type error.
    ("queue", "QueueDashboard::new(Arc::new(DatabaseQueue::new(db.clone())) as Arc<dyn Queue>)"),
    // These three take something only the application can build: a set of
    // tools, a configured provider, an authorization server. A bare
    // `Socialite::new()` would mount two routes that answer "unknown
    // provider" to everything, which is a line that looks registered and
    // is not.
    ("i18n", "Translator::new() — load_dir(\"lang\"), then .state(it) and .views(engine.with_translator(...))"),
    ("mcp", "Mcp::new(server)"),
    ("chart", "Charts::default() — then add the two <script> tags the plugin serves to your layout"),
    // A receiver needs the gateway the application chose and the handler
    // that credits the customer — neither of which a scaffold can invent.
    ("ledger", "Ledger::new(db.clone(), \"credits\") — then .state(it); register CreateLedgerTables in the migrations"),
    ("billing", "Billing::new(db.clone(), ledger.clone(), gateway, plans) — then .state(it); register CreateBillingTables; schedule billing.tick() and send what it returns"),
    ("payment", "Receiver::new(Arc::new(FakeGateway::new(secret)), Arc::new(DatabaseWebhookLog::new(db.clone(), \"fake\")), |event| Box::pin(async move { … }))"),
    ("oauth", "Socialite::new().provider(client)"),
    ("oauth-provider", "OAuthProvider::new(server)"),
];

/// The `.plugin(...)` lines for the packages that were asked for.
///
/// **A package that is switched on and never registered is a package that does
/// nothing**, and the generated `main.rs` used to say nothing about it: asking
/// for `--with telescope` compiled the dependency in, `/telescope` answered
/// 404, and the file gave no hint that a line was missing. The scaffold knows
/// exactly what was requested, so it writes the line.
///
/// Only the plugins that can be built from nothing are here. `Rbac` and
/// `Audit` need a database handle and `FeatureFlags` needs a store, so a line
/// for those would not compile — the auth-kit's own `main.rs` registers them,
/// because it is the one that creates the handle. A comment names them instead.
fn plugin_lines(packages: &[String], already: &[&str]) -> String {

    let mut lines = String::new();
    for (package, expression) in REGISTERABLE {
        if already.contains(package) {
            continue;
        }
        if packages.iter().any(|p| p == package) {
            lines.push_str(&format!("        .plugin({expression})\n"));
        }
    }

    let owed: Vec<&str> = NEEDS_WIRING
        .iter()
        .filter(|(package, _)| !already.contains(package))
        .filter(|(package, _)| packages.iter().any(|p| p == package))
        .map(|(_, expression)| *expression)
        .collect();
    if !owed.is_empty() {
        lines.push_str(&format!(
            "        // Also asked for, and each needing something only this\n\
             \x20       // application can build — a database handle, a store, a\n\
             \x20       // configured client. Add them here:\n\
             \x20       // {}\n",
            owed.join("\n        // ")
        ));
    }

    lines
}

/// The questions `rustlavel new` asks when nothing was asked for on the
/// command line.
///
/// **It answers itself when nobody is there.** Every prompt falls back to its
/// default if stdin is not a terminal, so a scaffold in CI produces the same
/// project it always did rather than hanging on a question. `--with`, `--all`
/// and `--yes` all skip this entirely.
///
/// Three questions, in the order somebody actually decides them: what kind of
/// application, which database, and what else to put in. Asking about
/// packages one at a time — twenty-seven yes/no questions — would be worse
/// than the flag it replaces.
fn interview() -> Vec<String> {
    if !ask::interactive() {
        return Vec::new();
    }

    let shape = ask::choose(
        "What kind of application is this?",
        &[
            (
                "A full application, with the auth starter kit",
                "Sign-in, passkeys, roles and permissions, an admin area, settings, an audit trail",
            ),
            ("An API", "Routing, JSON resources, validation and a database — no views"),
            ("A web application", "Routes, views and a database, with sign-in left to you"),
            ("Nothing but the skeleton", "One route and one controller; add packages later"),
        ],
        0,
    );

    let mut packages: Vec<String> = match shape {
        0 => vec!["auth-kit".to_string()],
        1 => ["db", "validation", "openapi"].iter().map(|p| p.to_string()).collect(),
        2 => ["db", "view", "validation"].iter().map(|p| p.to_string()).collect(),
        _ => Vec::new(),
    };

    // The database question is only worth asking when something will use one.
    // The kit needs one to boot at all, so "none" is not offered there.
    if packages.iter().any(|p| p == "db" || p == "auth-kit") {
        let needs_one = shape == 0;
        let mut engines: Vec<(&str, &str)> = vec![
            ("PostgreSQL", "The reference driver — everything is tested here first"),
            ("MySQL or MariaDB", ""),
            ("SQL Server", ""),
        ];
        if !needs_one {
            engines.push(("Decide later", "The database package is added; DATABASE_URL is left blank"));
        }

        let engine = ask::choose("Which database?", &engines, 0);
        chosen_database(engine);
    }

    // Only for the kit: on its own the dashboard would be a page with no
    // layout to render it in, and asking everybody about a registry most
    // projects do not run is a question that teaches people to skim.
    if shape == 0
        && ask::confirm(
            "Add a dashboard for a service registry? (an admin page listing services and their instances)",
            false,
        )
    {
        packages.push("discovery-ui".to_string());
    }

    let extras = ask::choose_many(
        "Anything else? (each one is a package, and what you leave out is never compiled)",
        EXTRAS,
        &[],
    );
    for index in extras {
        packages.push(EXTRAS[index].0.split_whitespace().next().unwrap_or_default().to_string());
    }

    packages.sort();
    packages.dedup();

    if packages.is_empty() {
        console::info("No packages. `rustlavel new <name> --with <package>` adds one later.");
    }
    packages
}

/// The optional packages worth offering, in the order somebody reaches for
/// them. Not every package: `auth`, `db` and the rest that a shape above
/// already implies are not choices at this point, and offering all
/// twenty-seven would make the list unreadable.
///
/// The first word of each label is the package name, which is what
/// [`interview`] reads back — so the label cannot be reworded freely, and the
/// test below checks that every one of them is still a real package.
const EXTRAS: &[(&str, &str)] = &[
    ("queue — background jobs", "Workers, scheduling, retries and a dead-letter store"),
    ("storage — files", "Local disk and S3-compatible object stores"),
    ("mail — email", "SMTP written here, with a log driver for development"),
    ("cache — caching", "Memory, file, or Redis, chosen in .env"),
    ("model-cache — a second-level cache", "Entities and query results, invalidated per table"),
    ("i18n — translations", ""),
    ("ws — WebSockets", "RFC 6455, plus channel broadcasting"),
    ("telescope — a debugging dashboard", "Requests, queries and logs, in process"),
    ("debugbar — a development overlay", "This request's queries, cache and timing, on the page"),
    ("metrics — Prometheus metrics", ""),
    ("otel — OpenTelemetry", "Traces and metrics over OTLP"),
    ("openapi — an OpenAPI document", "Generated from the router"),
    ("client — an outbound HTTP client", "TLS from rustls, with a circuit breaker"),
    ("ai — Anthropic, OpenAI and Ollama", "One API, with streaming, tools and a fake provider"),
    ("mcp — Model Context Protocol", ""),
    ("search — Elasticsearch", ""),
    ("ldap — a directory", "Bind, search, and authenticating against it"),
    ("oauth — social login", "The client half: sign in with Google, GitHub and the rest"),
    ("oauth-provider — be a provider", "Authorization code with PKCE, refresh rotation, revocation"),
    ("vault — secrets", "OpenBao or HashiCorp Vault, with dynamic database credentials"),
    ("flags — feature flags", "Runtime switches, per user or per tenant"),
];

/// Remember the engine somebody picked, so `.env` can be written with a URL
/// they can actually fill in rather than a PostgreSQL one they have to correct.
fn chosen_database(index: usize) {
    DATABASE.with(|cell| cell.set(index));
}

thread_local! {
    static DATABASE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// The `DATABASE_URL` line for the engine that was chosen.
fn database_url_line() -> &'static str {
    match DATABASE.with(std::cell::Cell::get) {
        1 => "DATABASE_URL=mysql://root:secret@127.0.0.1:3306/app",
        2 => "DATABASE_URL=sqlserver://sa:secret@127.0.0.1:1433/app",
        3 => "DATABASE_URL=",
        _ => "DATABASE_URL=postgres://postgres:secret@127.0.0.1:5432/app",
    }
}

#[cfg(test)]
mod tests {

    /// The first `{{placeholder}}` left in rendered text, if any.
    ///
    /// A brace pair followed by a letter is a scaffold placeholder nobody filled
    /// in. `{{ spaced }}` belongs to the view engine and `{{` before a newline is
    /// a `format!` escape, so neither counts.
    fn unrendered_placeholder(text: &str) -> Option<String> {
    let bytes = text.as_bytes();
    let mut i = 0;
    while let Some(at) = text[i..].find("{{") {
        let start = i + at;
        let next = bytes.get(start + 2).copied().unwrap_or(b' ');
        if (next.is_ascii_alphabetic() || next == b'_')
            && let Some(end) = text[start..].find("}}")
        {
            return Some(text[start..start + end + 2].to_string());
        }
        i = start + 2;
    }
    None
    }

    /// **Every package that ships a plugin has to be accounted for — in the
    /// file that is actually written.**
    ///
    /// The first version of this test called `plugin_lines` and passed while
    /// the feature was broken for every `auth-kit` project: `auth-kit` writes
    /// its own `main.rs`, that template had no `{{plugins}}` in it, and it is
    /// written second so it wins. The helper was right and the artifact was
    /// wrong, which is the only kind of bug a test on the helper cannot see.
    ///
    /// So this renders both templates and reads the output.
    #[test]
    fn every_package_that_ships_a_plugin_is_named_in_the_main_rs_that_gets_written() {
        let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .expect("crates/ is the parent of this crate");

        for (package, _) in PACKAGES {
            if *package == "auth-kit" {
                continue;
            }
            if !ships_a_plugin(&crates.join(format!("rustlavel-{package}")).join("src")) {
                continue;
            }

            // Both shapes: the plain scaffold, and the starter kit — which
            // already registers `rbac` and `audit` in its own template.
            for (template, already) in [
                (stubs::MAIN_RS, &[] as &[&str]),
                (stubs::MAIN_RS_DB, &[]),
                (crate::auth_kit::file("src/main.rs"), &["rbac", "audit", "i18n"][..]),
            ] {
                let mut values = BTreeMap::new();
                values.insert("plugins", plugin_lines(&[(*package).to_string()], already));
                values.insert("crate_name", "app".to_string());
                let rendered = stubs::render(template, &values);

                let mentioned = rendered.contains(package)
                    || REGISTERABLE
                        .iter()
                        .chain(NEEDS_WIRING)
                        .find(|(name, _)| name == package)
                        .is_some_and(|(_, expression)| {
                            rendered.contains(expression.split("::").next().unwrap_or(expression))
                        });

                assert!(
                    mentioned || already.contains(package),
                    "`--with {package}` produces a main.rs that says nothing about it:\n{rendered}"
                );
            }
        }
    }

    /// **Every table the kit's migrations create has to be in the backup.**
    ///
    /// Three were added in one afternoon and none of them reached
    /// `OWN_TABLES`, so the Backup screen produced a file that silently
    /// omitted the navigation menus, the whole audit trail and the password
    /// history — and said nothing, because a hand-kept list cannot know what
    /// it is missing. This reads the migrations instead.
    #[test]
    fn the_backup_covers_every_table_the_kit_creates() {
        let migrations = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("templates/auth-kit/database/migrations");
        let backup = include_str!("../templates/auth-kit/src/modules/backup/archive.rs");

        let mut missing = Vec::new();
        for entry in std::fs::read_dir(&migrations).expect("the migrations directory") {
            let path = entry.expect("a readable entry").path();
            if path.extension().is_none_or(|e| e != "rs") {
                continue;
            }
            let source = std::fs::read_to_string(&path).expect("a readable migration");

            // `schema.create("name", …)` — the tables this file makes.
            for (at, _) in source.match_indices(".create(\"") {
                let rest = &source[at + ".create(\"".len()..];
                let Some(end) = rest.find('"') else { continue };
                let table = &rest[..end];

                // `backups` is deliberately absent — a dump that recorded the
                // row describing itself would restore a catalogue of files
                // that are no longer on disk.
                if table == "backups" {
                    continue;
                }
                if !backup.contains(&format!("\"{table}\"")) {
                    missing.push(format!("{table} (from {})", path.file_name().unwrap().to_string_lossy()));
                }
            }
        }

        // The kit's registry also extends with another crate's migrations, and
        // `audit_logs` came from there — which is exactly why the first
        // version of this test passed while that table was missing. A check
        // that reads one directory is the same hand-kept list in a different
        // shape.
        //
        // Only crates whose table names are *fixed* are checked here.
        // `rustlavel-rbac` lets an application rename its five, so `tables()`
        // asks the store for them at runtime rather than hard-coding them, and
        // a static check would be looking for the wrong names.
        let registry = include_str!("auth_kit.rs");
        for package in ["audit"] {
            if !registry.contains(&format!("rustlavel::{package}::migrations()")) {
                continue;
            }
            let source = std::fs::read_to_string(
                std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                    .parent()
                    .expect("crates/")
                    .join(format!("rustlavel-{package}/src/tables.rs")),
            )
            .unwrap_or_default();

            let marker = "pub const TABLE: &str = \"";
            for (at, _) in source.match_indices(marker) {
                let rest = &source[at + marker.len()..];
                let Some(end) = rest.find('"') else { continue };
                let table = &rest[..end];

                // Either form counts. Naming the crate's own constant is the
                // better one — a rename there cannot then drop the table out
                // of every backup — so a check that insisted on the literal
                // would be pushing towards the worse spelling.
                let by_literal = backup.contains(&format!("\"{table}\""));
                let by_constant = backup.contains(&format!("{package}::TABLE"));
                if !by_literal && !by_constant {
                    missing.push(format!("{table} (from rustlavel-{package})"));
                }
            }
        }

        assert!(
            missing.is_empty(),
            "these tables are created by the kit and would not be in a backup: {missing:#?}"
        );
    }

    /// **Every `MAIL_*` variable has to reach the mailer, not just the page.**
    ///
    /// `Config` knows only what a file under `config/` declares — there is no
    /// automatic `MAIL_HOST` to `mail.host` mapping — while the starter kit's
    /// settings screen reads the environment directly. So a variable with a
    /// line in `.env` and no path in `config/mail.json` produces a screen that
    /// says the environment is in charge of a value the mailer never sees.
    /// That was true of five of them.
    #[test]
    fn every_mail_variable_in_the_env_is_wired_through_config() {
        let catalogue = include_str!("../templates/auth-kit/src/support/settings.rs");
        let declared: Vec<&str> = catalogue
            .match_indices("MAIL_")
            .map(|(at, _)| {
                let rest = &catalogue[at..];
                let end = rest
                    .find(|c: char| !c.is_ascii_uppercase() && c != '_')
                    .unwrap_or(rest.len());
                &rest[..end]
            })
            .filter(|name| *name != "MAIL_DRIVERS")
            .collect();

        assert!(declared.len() >= 5, "the catalogue no longer names any: {declared:?}");

        for variable in declared {
            assert!(
                stubs::ENV_MAIL.contains(&format!("{variable}=")),
                "the settings screen reads {variable} and `.env` has no line for it"
            );
            assert!(
                stubs::CONFIG_MAIL.contains(&format!("${{{variable}")),
                "{variable} is in `.env` but config/mail.json does not read it, so it reaches \
                 the settings screen and never the mailer"
            );
        }
    }

    /// Every file under `directory` whose name ends in one of `suffixes`.
    fn gather(directory: &std::path::Path, suffixes: &[&str], into: &mut Vec<(String, String)>) {
        let Ok(entries) = std::fs::read_dir(directory) else { return };
        for entry in entries.filter_map(Result::ok) {
            let path = entry.path();
            if path.is_dir() {
                gather(&path, suffixes, into);
            } else if suffixes.iter().any(|s| path.to_string_lossy().ends_with(s))
                && let Ok(text) = std::fs::read_to_string(&path)
            {
                into.push((path.to_string_lossy().into_owned(), text));
            }
        }
    }

    /// A setting nobody reads is a switch that does nothing.
    ///
    /// This is the bug that keeps coming back, and it never shows up in a
    /// review: the catalogue declares the key, the tab renders a control for
    /// it, saving writes a row — and no code anywhere asks what the row says.
    /// Six mail settings, a timezone, a date format, a backup destination and
    /// a first-day-of-week all shipped that way. So enumerate the catalogue
    /// rather than trust it, and require a reader outside the settings screen
    /// itself for every key in it.
    #[test]
    fn every_setting_in_the_catalogue_is_read_by_something() {
        let kit = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("templates/auth-kit");
        let catalogue = std::fs::read_to_string(kit.join("src/support/settings.rs")).unwrap();
        // The built-in list, plus whatever each module declares beside the
        // code that reads it. The catalogue is the two joined, so a guard that
        // reads only one of them reports a module's settings as undeclared.
        let mut body = catalogue
            .split_once("const BUILT_IN")
            .and_then(|(_, rest)| rest.split_once("\n];"))
            .expect("the built-in settings are no longer a `const BUILT_IN` ending in `];`")
            .0
            .to_string();

        let mut module_files = Vec::new();
        gather(&kit.join("src/modules"), &["mod.rs"], &mut module_files);
        for (_, text) in &module_files {
            if let Some((_, rest)) = text.split_once("static SETTINGS")
                && let Some((declared, _)) = rest.split_once("\n];")
            {
                body.push_str(declared);
            }
        }
        let body = body.as_str();

        let mut keys: Vec<&str> = Vec::new();
        for piece in body.split('"').skip(1).step_by(2) {
            let looks_like_a_key = piece.contains('.')
                && !piece.is_empty()
                && piece
                    .chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.' || c == '_')
                // Every segment starts with a letter, which is what keeps a
                // default like `127.0.0.1` from reading as a key.
                && piece.split('.').all(|part| part.starts_with(|c: char| c.is_ascii_lowercase()));
            if looks_like_a_key && !keys.contains(&piece) {
                keys.push(piece);
            }
        }
        assert!(keys.len() > 40, "only {} keys parsed out of the catalogue", keys.len());

        // Everything except the settings screen, which renders a control for a
        // key whether or not anything honours it — the very thing being tested.
        let mut files = Vec::new();
        gather(&kit.join("src"), &[".rs"], &mut files);
        gather(&kit.join("resources"), &[".html"], &mut files);
        files.retain(|(path, _)| {
            !path.ends_with("support/settings.rs")
                && !path.contains("settings_controller")
                && !path.contains("views/settings")
        });
        for entry in &mut files {
            entry.1 = without_declarations(&entry.1);
        }

        let dead: Vec<&str> = keys
            .iter()
            .copied()
            .filter(|key| {
                let quoted = format!("\"{key}\"");
                !files.iter().any(|(_, text)| text.contains(&quoted))
            })
            .collect();

        assert!(
            dead.is_empty(),
            "these settings are declared, rendered on a tab and saved to the database, and \
             nothing outside the settings screen ever reads them — wire each one up or take \
             it off the tab: {dead:?}"
        );
    }

    /// A permission the seeder creates and nothing checks, or the other way
    /// round, is the same bug as a setting nobody reads.
    ///
    /// One half locks a page nobody can ever reach — the guard names a
    /// permission that is in no role, so every request is refused. The other
    /// half is a row in the permissions table that grants nothing, which an
    /// administrator will tick and then wonder about.
    #[test]
    fn every_permission_is_both_seeded_and_checked() {
        let kit = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("templates/auth-kit");
        // The list lives in the seeder the CLI writes, which is a string
        // here and Rust only once a project exists — so read it out of the
        // string rather than referring to a constant that is not ours.
        let seeder = crate::auth_kit::file("database/seeders/auth_kit_seeder.rs");
        let table = seeder
            .split_once("const PERMISSIONS: &[(&str, &str)] = &[")
            .and_then(|(_, rest)| rest.split_once("\n];"))
            .expect("the seeder no longer declares PERMISSIONS as a table")
            .0;
        let mut seeded: Vec<String> = table
            .split("(\"")
            .skip(1)
            .filter_map(|piece| piece.split_once('"').map(|(name, _)| name.to_string()))
            .collect();

        // A module declares its own beside the code that checks them, and the
        // seeder reads both lists. So must this.
        let mut module_files = Vec::new();
        gather(&kit.join("src/modules"), &["mod.rs"], &mut module_files);
        for (_, text) in &module_files {
            if let Some((_, rest)) = text.split_once("static PERMISSIONS")
                && let Some((declared, _)) = rest.split_once("\n];")
            {
                seeded.extend(
                    declared
                        .split("(\"")
                        .skip(1)
                        .filter_map(|piece| piece.split_once('"').map(|(n, _)| n.to_string())),
                );
            }
        }
        let seeded: Vec<&str> = seeded.iter().map(String::as_str).collect();
        assert!(seeded.len() > 15, "only {} permissions parsed: {seeded:?}", seeded.len());

        let mut files = Vec::new();
        gather(&kit.join("src"), &[".rs"], &mut files);
        gather(&kit.join("resources"), &[".html"], &mut files);
        for entry in &mut files {
            entry.1 = without_declarations(&entry.1);
        }

        for name in &seeded {
            let quoted = format!("\"{name}\"");
            assert!(
                files.iter().any(|(_, text)| text.contains(&quoted)),
                "the seeder creates `{name}` and nothing in the generated application asks for \
                 it, so granting it does nothing"
            );
        }

        // And the other direction: anything a guard or a `can` names has to be
        // a permission the seeder actually creates.
        for (path, text) in &files {
            for prefix in ["guard(\"", "can(\"", "@can(\""] {
                let mut rest = text.as_str();
                while let Some(at) = rest.find(prefix) {
                    rest = &rest[at + prefix.len()..];
                    let Some(end) = rest.find('"') else { break };
                    let name = &rest[..end];
                    // Only the `noun.verb` shape is a permission; `can("...")`
                    // also appears in prose and in other kinds of argument.
                    if name.split('.').count() == 2
                        && name.chars().all(|c| c.is_ascii_lowercase() || c == '.' || c == '_')
                    {
                        assert!(
                            seeded.contains(&name),
                            "{path} checks for `{name}`, which the seeder never creates — the \
                             page it guards can never be opened by anybody"
                        );
                    }
                }
            }
        }
    }

    /// The stylesheet the kit ships has to cover the markup the kit ships.
    ///
    /// `public/css/app.css` is a Tailwind build committed so a project needs no
    /// Node toolchain, and that is the trap: adding a class to a template is
    /// free, and the stylesheet only learns about it when somebody remembers to
    /// rebuild. It went stale exactly that way — a release added a search box,
    /// a notification list, toasts, pagination and tab pills, and shipped all
    /// of them with 58 of their classes undefined, so the markup was there and
    /// the styling simply was not.
    ///
    /// Rebuild with:
    ///
    /// ```text
    /// npx @tailwindcss/cli -i resources/css/app.css -o public/css/app.css --minify
    /// ```
    #[test]
    fn the_committed_stylesheet_covers_the_classes_the_templates_use() {
        let kit = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("templates/auth-kit");
        let css = std::fs::read_to_string(kit.join("public/css/app.css")).unwrap();

        // The named component classes: every `@utility` in the source has to
        // have survived into the build, and those are the ones a template
        // spells out by name rather than composing from utilities.
        let source = std::fs::read_to_string(kit.join("resources/css/app.css")).unwrap();
        let named: Vec<&str> = source
            .match_indices("@utility ")
            .map(|(at, _)| {
                let rest = &source[at + "@utility ".len()..];
                let end = rest
                    .find(|c: char| !c.is_ascii_alphanumeric() && c != '-')
                    .unwrap_or(rest.len());
                &rest[..end]
            })
            .collect();
        assert!(named.len() > 20, "only {} utilities parsed: {named:?}", named.len());

        let mut used = Vec::new();
        gather(&kit.join("resources/views"), &[".html"], &mut used);
        gather(&kit.join("src"), &[".rs"], &mut used);
        gather(&kit.join("public/js"), &[".js"], &mut used);

        let mut undefined: Vec<String> = Vec::new();
        for name in named {
            // Only complain about a class something actually writes: a utility
            // defined and never used is dead weight, not a broken page, and
            // Tailwind sweeps it out of the build on purpose.
            let quoted = [format!("\"{name}"), format!(" {name} "), format!(" {name}\"")];
            let is_used = used
                .iter()
                .any(|(_, text)| quoted.iter().any(|form| text.contains(form.as_str())));
            if is_used && !css.contains(&format!(".{name}")) {
                undefined.push(name.to_string());
            }
        }

        assert!(
            undefined.is_empty(),
            "these classes are written into the generated markup and are not in the stylesheet \
             that ships beside it, so the elements wearing them render unstyled — rebuild \
             `public/css/app.css` from `resources/css/app.css`: {undefined:?}"
        );
    }

    /// A button labelled "(Default)" has to restore the default.
    ///
    /// Settings → Appearance offers quick presets, one of them named for the
    /// value the catalogue declares. Change that value and the button keeps
    /// handing back the old one — a control that silently disagrees with the
    /// thing it names, which is how three of them ended up restoring the
    /// colours of a design two versions old.
    #[test]
    fn the_default_appearance_presets_are_the_declared_defaults() {
        let kit = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("templates/auth-kit");
        let catalogue = std::fs::read_to_string(kit.join("src/support/settings.rs")).unwrap();
        let tab = std::fs::read_to_string(
            kit.join("resources/views/settings/tabs/appearance.rl.html"),
        )
        .unwrap();

        // The declared default for one `s("key", Kind::Colour, "#value")`.
        let declared = |key: &str| -> String {
            let at = catalogue
                .find(&format!("s(\"{key}\", Kind::Colour, \""))
                .unwrap_or_else(|| panic!("`{key}` is no longer a colour in the catalogue"));
            let rest = &catalogue[at..];
            let start = rest.rfind('"').map(|_| rest.find(", \"").unwrap() + 3).unwrap();
            let end = rest[start..].find('"').unwrap() + start;
            rest[start..end].to_string()
        };

        // Each preset in the order the controller writes its keys.
        for keys in [
            vec!["theme.brand"],
            vec![
                "theme.login.light.from",
                "theme.login.light.to",
                "theme.login.dark.from",
                "theme.login.dark.to",
            ],
            vec![
                "theme.sidebar.light.bg",
                "theme.sidebar.light.text",
                "theme.sidebar.light.active_bg",
                "theme.sidebar.light.active_text",
                "theme.sidebar.dark.bg",
                "theme.sidebar.dark.text",
                "theme.sidebar.dark.active_bg",
                "theme.sidebar.dark.active_text",
            ],
        ] {
            let wanted: Vec<String> = keys.iter().map(|k| declared(k)).collect();
            let preset = format!("data-preset=\"{}\"", wanted.join(","));
            assert!(
                tab.contains(&preset),
                "the Appearance tab has no preset restoring the declared defaults for {keys:?}. \
                 Its \"(Default)\" button hands back something else, so pressing it moves the \
                 application away from the state it names. Expected {preset}"
            );
        }
    }

    /// The font has to arrive as a font.
    ///
    /// Everything in `FILES` goes through the placeholder renderer on the way
    /// out, which is right for a template and fatal for a woff2: any two
    /// braces that happened to line up inside the compressed stream would be
    /// rewritten, and the file would arrive the right size and unreadable.
    /// `BINARY_FILES` exists to keep them apart, and this is what keeps a font
    /// from being added to the wrong list.
    #[test]
    fn the_binary_files_are_carried_byte_for_byte() {
        let kit = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("templates/auth-kit");

        for (path, bytes) in crate::auth_kit::BINARY_FILES {
            let on_disk = std::fs::read(kit.join(path))
                .unwrap_or_else(|e| panic!("{path} is in BINARY_FILES and not on disk: {e}"));
            assert_eq!(
                *bytes, &on_disk[..],
                "{path} does not match the file it is embedded from"
            );
        }

        // A woff2 begins `wOF2`. If one ever ends up in `FILES` instead, the
        // renderer will have had a chance at it.
        for (path, contents) in crate::auth_kit::FILES {
            assert!(
                !path.ends_with(".woff2") && !path.ends_with(".woff") && !path.ends_with(".png"),
                "{path} is binary and is in FILES, where every entry is run through the \
                 placeholder renderer — move it to BINARY_FILES"
            );
            let _ = contents;
        }

        let fonts: Vec<&str> = crate::auth_kit::BINARY_FILES
            .iter()
            .map(|(path, _)| *path)
            .filter(|path| path.ends_with(".woff2"))
            .collect();
        assert!(!fonts.is_empty(), "the kit no longer ships a font of its own");

        // Self-hosted means the stylesheet asks this application for it.
        let css = std::fs::read_to_string(kit.join("resources/css/app.css")).unwrap();
        for path in fonts {
            let url = path.trim_start_matches("public");
            assert!(
                css.contains(&format!("url(\"{url}\")")),
                "{path} ships with the kit and no @font-face asks for it"
            );
        }
        // The comments in that file name the CDNs they explain avoiding, so
        // ask the CSS rather than the prose around it.
        let mut rules = String::new();
        let mut rest = css.as_str();
        while let Some(at) = rest.find("/*") {
            rules.push_str(&rest[..at]);
            rest = match rest[at..].find("*/") {
                Some(end) => &rest[at + end + 2..],
                None => "",
            };
        }
        rules.push_str(rest);
        assert!(
            !rules.contains("fonts.googleapis.com") && !rules.contains("fonts.gstatic.com"),
            "the stylesheet reaches out to a font CDN, which is what self-hosting was for"
        );
    }

    /// A template file that is not in a manifest never reaches a project.
    ///
    /// The kit's files live on disk so they can be read and edited, and reach
    /// an application only through `FILES` or `BINARY_FILES`. Adding one and
    /// forgetting the manifest produces a scaffold that is missing it — with
    /// no error, because nothing looked for it. Listing a file that has since
    /// been deleted fails the build instead, which is the harmless direction.
    #[test]
    fn every_template_file_is_in_a_manifest() {
        let kit = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("templates/auth-kit");
        let listed: Vec<&str> = crate::auth_kit::FILES
            .iter()
            .map(|(path, _)| *path)
            .chain(crate::auth_kit::BINARY_FILES.iter().map(|(path, _)| *path))
            .chain(crate::auth_kit::DISCOVERY_FILES.iter().map(|(path, _)| *path))
            .collect();

        let mut on_disk = Vec::new();
        for directory in ["src", "resources", "public", "config", "database", "tests", "lang"] {
            let mut found = Vec::new();
            gather(&kit.join(directory), &[""], &mut found);
            for (path, _) in found {
                let relative = path
                    .strip_prefix(&format!("{}/", kit.display()))
                    .unwrap_or(&path)
                    .to_string();
                on_disk.push(relative);
            }
        }
        assert!(on_disk.len() > 80, "only {} template files found", on_disk.len());

        let missing: Vec<&String> = on_disk
            .iter()
            .filter(|path| !listed.contains(&path.as_str()))
            .collect();
        assert!(
            missing.is_empty(),
            "these files are in `templates/auth-kit/` and in neither manifest, so `rustlavel \
             new` writes a project without them: {missing:?}"
        );
    }

    /// The scripts' CSRF token cannot depend on a form having rendered.
    ///
    /// `app.js` posts on its own for passkeys, and it needs a token. It used to
    /// read the hidden `_token` field, which exists only inside a form — and on
    /// the two-factor page that form is behind `@if(has_totp)`. Somebody with a
    /// passkey and no authenticator app got a page with no token anywhere,
    /// so "Use a passkey" sent an empty one and the server answered 419. The
    /// token belongs in the layout, where every page gets one.
    #[test]
    fn every_layout_carries_the_csrf_token_for_the_scripts() {
        let kit = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("templates/auth-kit");

        let mut layouts = Vec::new();
        gather(&kit.join("resources/views/layouts"), &[".html"], &mut layouts);
        assert!(layouts.len() >= 2, "expected an app and a guest layout, found {}", layouts.len());

        for (path, text) in &layouts {
            assert!(
                text.contains(r#"<meta name="csrf-token""#),
                "{path} renders pages whose scripts post, and carries no CSRF token of its own"
            );
        }

        // And the script has to prefer it, or the meta tag is decoration.
        let js = std::fs::read_to_string(kit.join("public/js/app.js")).unwrap();
        let reads_meta = js.find(r#"meta[name="csrf-token"]"#);
        let reads_field = js.find("input[name=_token]");
        assert!(reads_meta.is_some(), "app.js never looks at the meta tag");
        assert!(
            reads_meta < reads_field || reads_field.is_none(),
            "app.js reads the form field before the meta tag, so a page with no form still \
             sends an empty token"
        );
    }

    /// Every flat key in a language file, so two files can be compared.
    fn phrase_keys(value: &rustlavel_core::Json, prefix: &str, into: &mut Vec<String>) {
        if let Some(fields) = value.as_object() {
            for (name, child) in fields {
                let key =
                    if prefix.is_empty() { name.clone() } else { format!("{prefix}.{name}") };
                match child.as_object().is_some() {
                    true => phrase_keys(child, &key, into),
                    false => into.push(key),
                }
            }
        }
    }

    /// A `@lang` key with no phrase behind it renders as itself on the page.
    ///
    /// The translator does that deliberately — a visible `auth.sign_in` is
    /// something somebody fixes, where a blank button is not. But it should be
    /// caught here rather than by a reader, and only enumerating the templates
    /// can catch it: the key is a string in markup and the phrase is a string
    /// in JSON, and nothing makes them agree.
    #[test]
    fn every_lang_key_a_template_writes_has_an_english_phrase() {
        let kit = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("templates/auth-kit");
        let english = std::fs::read_to_string(kit.join("lang/en.json")).unwrap();
        let english = rustlavel_core::Json::parse(&english).expect("lang/en.json is not JSON");

        let mut known = Vec::new();
        phrase_keys(&english, "", &mut known);
        assert!(known.len() > 10, "only {} phrases in lang/en.json", known.len());

        let mut views = Vec::new();
        gather(&kit.join("resources/views"), &[".html"], &mut views);

        let mut missing: Vec<String> = Vec::new();
        for (path, text) in &views {
            let mut rest = text.as_str();
            while let Some(at) = rest.find("@lang(\"") {
                rest = &rest[at + "@lang(\"".len()..];
                let Some(end) = rest.find('"') else { break };
                let key = &rest[..end];
                if !known.iter().any(|had| had == key) {
                    missing.push(format!("{key} (in {path})"));
                }
            }
        }

        assert!(
            missing.is_empty(),
            "these keys are written into a template and have no phrase in lang/en.json, so the \
             page shows the key itself: {missing:?}"
        );
    }

    /// A language file that has drifted from the source leaves half a page in
    /// the wrong language, which is worse than a page in one wrong language.
    #[test]
    fn every_language_file_carries_the_same_keys() {
        let kit = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("templates/auth-kit");
        let read = |name: &str| {
            let source = std::fs::read_to_string(kit.join(format!("lang/{name}.json")))
                .unwrap_or_else(|e| panic!("lang/{name}.json: {e}"));
            let value = rustlavel_core::Json::parse(&source)
                .unwrap_or_else(|e| panic!("lang/{name}.json is not JSON: {e}"));
            let mut keys = Vec::new();
            phrase_keys(&value, "", &mut keys);
            keys.sort();
            keys
        };

        let english = read("en");

        // Every file beside `en.json`, rather than a list here that would have
        // to be remembered: adding `ms.json` should put it under this guard
        // without anybody editing the guard.
        let mut others: Vec<String> = std::fs::read_dir(kit.join("lang"))
            .expect("lang/")
            .filter_map(Result::ok)
            .filter_map(|entry| {
                let path = entry.path();
                let stem = path.file_stem()?.to_str()?.to_string();
                (path.extension()? == "json" && stem != "en").then_some(stem)
            })
            .collect();
        others.sort();
        assert!(!others.is_empty(), "no language beside English to check against");

        for other in others {
            let other = other.as_str();
            let theirs = read(other);
            let untranslated: Vec<&String> =
                english.iter().filter(|key| !theirs.contains(key)).collect();
            let stale: Vec<&String> =
                theirs.iter().filter(|key| !english.contains(key)).collect();

            assert!(untranslated.is_empty(), "lang/{other}.json is missing: {untranslated:?}");
            assert!(stale.is_empty(), "lang/{other}.json has keys English does not: {stale:?}");
        }
    }

    /// A module file with its own declaration blocks cut out.
    ///
    /// A module declares its settings and permissions in `mod.rs`, beside the
    /// code that uses them — which is the point of a module and a problem for
    /// a guard that asks "does anything use this": the declaration is itself a
    /// mention, so every key would look used. These blocks come out before the
    /// search, and the rest of the file stays in, because a module's routes
    /// and guards live there too.
    fn without_declarations(text: &str) -> String {
        let mut out = text.to_string();
        for block in ["static SETTINGS", "static PERMISSIONS"] {
            while let Some(at) = out.find(block) {
                let end = match out[at..].find("\n];") {
                    Some(offset) => at + offset + "\n];".len(),
                    None => out.len(),
                };
                out.replace_range(at..end, "");
            }
        }
        out
    }


    /// A group that authenticates but does not check the session epoch is a way
    /// back in for a session a password reset was meant to end.
    ///
    /// This has gone wrong twice already in a different form — routes moved
    /// into a module lost their group's `Authenticate` and permission guards —
    /// so the rule is checked rather than remembered.
    #[test]
    fn every_authenticated_group_also_checks_the_session_epoch() {
        for (path, source) in crate::auth_kit::FILES {
            let mut missing = Vec::new();
            let lines: Vec<&str> = source.lines().collect();
            for (at, line) in lines.iter().enumerate() {
                if !line.contains("middleware(Authenticate::default()") {
                    continue;
                }
                // The epoch check goes next to it, so a short window is enough
                // and a group that puts it three lines down still passes.
                let window = lines[at..(at + 4).min(lines.len())].join("\n");
                if !window.contains("SessionEpoch") {
                    missing.push(format!("{path}:{}", at + 1));
                }
            }
            assert!(
                missing.is_empty(),
                "these groups authenticate but never check `users.session_epoch`, so a password \
                 reset would not end the other sessions it promises to end: {missing:?}"
            );
        }
    }


    /// Every form that checks a secret must be throttled.
    ///
    /// The password form was; the second-factor and recovery forms were not,
    /// which left somebody who already held a password an unlimited-rate
    /// oracle against six digits — three of which are accepted at any moment,
    /// because of the step window either side. A second factor guessed in
    /// minutes is not a second factor.
    ///
    /// Checked rather than remembered, because the throttle is three lines in
    /// a file nobody opens once it works.
    #[test]
    fn every_form_that_checks_a_secret_is_throttled() {
        for path in [
            "src/controllers/auth/login_controller.rs",
            "src/controllers/auth/mfa_controller.rs",
        ] {
            let source = crate::auth_kit::file(path);
            assert!(
                source.contains("address_is_blocked"),
                "{path} checks a secret and never asks whether this address has been guessing"
            );
            assert!(
                source.contains("record_address_failure"),
                "{path} refuses a wrong secret without counting it, so the check above it reads \
                 a counter nothing increments"
            );
        }
    }


    /// The same three rules the auth kit is held to, for the second kit.
    ///
    /// A kit is a hundred-odd lines the CLI never compiles — they are
    /// `include_str!` strings — so nothing but these guards and a real scaffold
    /// sees them at all.
    /// **No template may be named `Cargo.toml`.**
    ///
    /// Cargo treats any directory holding a `Cargo.toml` as a nested package
    /// and leaves it out of the parent's `.crate` file entirely. The
    /// microservices kit had six, so all twenty of its files were dropped from
    /// the published crate and `include_str!` failed to build it — caught by
    /// `cargo publish`'s verification step, on the last crate of a release, and
    /// invisible to every test and to `cargo install --path`, which reads the
    /// working tree rather than the tarball.
    ///
    /// The auth kit never tripped it only because none of its 121 files is a
    /// manifest. Templates are therefore stored as `Cargo.toml.template` and
    /// written out under their real name.
    #[test]
    fn no_template_is_named_cargo_toml_because_cargo_would_drop_its_whole_directory() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("templates");

        let mut offenders = Vec::new();
        fn walk(dir: &std::path::Path, root: &std::path::Path, offenders: &mut Vec<String>) {
            let Ok(entries) = std::fs::read_dir(dir) else { return };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    walk(&path, root, offenders);
                } else if path.file_name().is_some_and(|name| name == "Cargo.toml")
                    && let Ok(relative) = path.strip_prefix(root)
                {
                    offenders.push(relative.to_string_lossy().replace('\\', "/"));
                }
            }
        }
        walk(&root, &root, &mut offenders);
        offenders.sort();

        assert!(
            offenders.is_empty(),
            "these templates are named `Cargo.toml`, so cargo will treat each one's directory as \
             a nested package and drop it from the published crate — rename them to \
             `Cargo.toml.template` and keep the real name in the file manifest: {offenders:?}"
        );
    }

    #[test]
    fn the_microservices_kit_is_whole() {
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("templates")
            .join("microservices-kit");

        // 1. Every file on disk is in the manifest, or `new` does not write it.
        let mut on_disk = Vec::new();
        fn walk(dir: &std::path::Path, root: &std::path::Path, found: &mut Vec<String>) {
            let Ok(entries) = std::fs::read_dir(dir) else { return };
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    walk(&path, root, found);
                } else if let Ok(relative) = path.strip_prefix(root) {
                    found.push(relative.to_string_lossy().replace('\\', "/"));
                }
            }
        }
        walk(&root, &root, &mut on_disk);
        on_disk.sort();

        // A template manifest is stored as `Cargo.toml.template` and written
        // out as `Cargo.toml`; see the guard below for why.
        let on_disk: Vec<String> = on_disk
            .iter()
            .map(|path| path.trim_end_matches(".template").to_string())
            .collect();

        let manifested: Vec<&str> =
            crate::microservices_kit::FILES.iter().map(|(path, _)| *path).collect();
        let missing: Vec<&String> =
            on_disk.iter().filter(|path| !manifested.contains(&path.as_str())).collect();
        assert!(
            missing.is_empty(),
            "these files are in templates/microservices-kit/ and in no manifest, so a scaffold \
             would not receive them: {missing:?}"
        );

        // 2. Nothing still holds a placeholder once rendered.
        //
        // Exactly the values `new` passes — no more. This guard once carried an
        // invented one, so it rendered cleanly here and left `{{...}}` in a real
        // scaffold: a test agreeing with a fiction it wrote itself.
        let values = BTreeMap::from([
            ("crate_name", "demo".to_string()),
            ("name", "demo".to_string()),
            ("dependency", "version = \"0.0.0\"".to_string()),
        ]);
        for (path, template) in crate::microservices_kit::FILES {
            if let Some(found) = unrendered_placeholder(&render(template, &values)) {
                panic!("the kit writes `{path}` still holding `{found}`");
            }
        }

        // 3. Every package the generated code imports is one `--with` accepts.
        for package in crate::microservices_kit::REQUIRED_PACKAGES {
            assert!(
                PACKAGES.iter().any(|(known, _)| known == package),
                "the microservices kit needs `{package}`, which `--with` does not offer"
            );
        }
    }

    /// Every key the microservices kit's `.env` defines is read by its code,
    /// and every key its code reads is in that `.env`.
    ///
    /// **Both directions, because the kit shipped broken in both.** `.env`
    /// defined `AUTH_DATABASE_URL` and `API_DATABASE_URL` while both services
    /// read `DATABASE_URL`, so neither could start — and setting the one key
    /// they did read would have put two services in one database, which is the
    /// coupling the kit exists to avoid. `GATEWAY_PORT` was read by nothing at
    /// all. Neither was visible from a test, because a `.env` is data and the
    /// code that ignores it compiles perfectly.
    #[test]
    fn every_env_key_the_microservices_kit_defines_is_read_by_its_code() {
        let code: String = crate::microservices_kit::FILES
            .iter()
            .filter(|(path, _)| path.ends_with(".rs"))
            .map(|(_, contents)| *contents)
            .collect::<Vec<_>>()
            .join("\n");

        let declared: Vec<&str> = crate::microservices_kit::ENV_ADDITIONS
            .lines()
            .map(str::trim)
            .filter(|line| !line.starts_with('#') && line.contains('='))
            .filter_map(|line| line.split('=').next())
            .filter(|key| !key.is_empty())
            .collect();
        assert!(declared.len() > 8, "the .env block was not parsed: {declared:?}");

        let unread: Vec<&&str> =
            declared.iter().filter(|key| !code.contains(&format!("\"{key}\""))).collect();
        assert!(
            unread.is_empty(),
            "these keys are in the kit's .env and no generated file reads them, so setting \
             one does nothing: {unread:?}"
        );

        // And the other way: a key the code reads and the .env never mentions
        // is a setting nobody knows exists.
        let mut read: Vec<&str> = Vec::new();
        for (index, _) in code.match_indices("env_or(\"") {
            let rest = &code[index + "env_or(\"".len()..];
            if let Some(end) = rest.find('"') {
                read.push(&rest[..end]);
            }
        }
        read.sort_unstable();
        read.dedup();

        let undeclared: Vec<&&str> = read
            .iter()
            // `SERVER_PORT` is the framework's, and the four services take it
            // from their own environment rather than from the shared file.
            .filter(|key| **key != "SERVER_PORT")
            .filter(|key| !declared.contains(key))
            .collect();
        assert!(
            undeclared.is_empty(),
            "the kit's code reads these and its .env never mentions them: {undeclared:?}"
        );
    }

    /// Every service in the microservices kit answers `/health`.
    ///
    /// The authorization server did not, so the gateway's aggregate check
    /// probed it, got a 404, and reported the whole system `degraded` with a
    /// 503 — on a deployment where nothing was wrong. A load balancer reading
    /// that takes the gateway out of rotation, and the one endpoint that could
    /// have explained it is the one that said so.
    #[test]
    fn every_service_in_the_microservices_kit_answers_a_health_check() {
        let mains: Vec<(&str, &str)> = crate::microservices_kit::FILES
            .iter()
            .filter(|(path, _)| path.ends_with("/src/main.rs"))
            .map(|(path, contents)| (*path, *contents))
            .collect();
        assert!(mains.len() >= 4, "only {} services found", mains.len());

        for (path, contents) in mains {
            assert!(
                // The gateway mounts its own through the plugin; the rest
                // declare a route.
                contents.contains(r#"get("/health""#) || contents.contains(r#".health("/health""#),
                "{path} serves no /health, so the gateway will report the whole system degraded"
            );
        }
    }

    /// Every view the kit writes must parse with the engine that will render it.
    ///
    /// A mismatched `@if`, a directive that does not exist, an `@endforeach`
    /// closing an `@if` — none of these are visible until somebody opens the
    /// page, and the page they open is usually the one nobody has opened yet.
    /// The parser is cheap and it is right here.
    #[test]
    fn every_kit_view_parses() {
        let views = crate::auth_kit::FILES
            .iter()
            .chain(crate::auth_kit::DISCOVERY_FILES)
            .filter(|(path, _)| path.ends_with(".rl.html"));

        let mut checked: Vec<&str> = Vec::new();
        for (path, source) in views {
            // The scaffold placeholders come out first, exactly as `new` does
            // it — the engine has never seen them and should not have to.
            let rendered = render(
                source,
                &BTreeMap::from([
                    ("crate_name", "demo".to_string()),
                    ("name", "demo".to_string()),
                    ("modules_nav", crate::auth_kit::DISCOVERY_NAV.to_string()),
                ]),
            );

            if let Err(error) = rustlavel_view::parser::parse(path, &rendered) {
                panic!("{path} does not parse: {error}");
            }
            checked.push(path);
        }

        // Two floors, because a filter that matches nothing passes every check
        // above it. The count catches a filter that broke wholesale; the named
        // view catches the narrower case of the optional manifest dropping out
        // of the chain, which no count would notice.
        assert!(checked.len() > 30, "only {} views were checked", checked.len());
        assert!(
            checked.contains(&"resources/views/admin/discovery/index.rl.html"),
            "the optional manifest is not being checked"
        );
    }

    /// A generated file must not still hold a `{{placeholder}}`.
    ///
    /// 0.7.0 shipped a seeder containing the literal text `{{crate_name}}`,
    /// because it was written straight from the constant while every other
    /// file went through `render`. A fresh `rustlavel new --with auth-kit`
    /// did not compile, and nothing here noticed: the templates are tested,
    /// the writing of them was not.
    #[test]
    fn no_generated_file_still_carries_a_placeholder() {
        let base = BTreeMap::from([
            ("crate_name", "demo".to_string()),
            ("name", "demo".to_string()),
            ("dependency", "version = \"0.0.0\"".to_string()),
            ("plugins", String::new()),
            ("database", String::new()),
        ]);

        // The module slots, in both of the states `new` can leave them: empty
        // when the discovery dashboard was not asked for, filled when it was.
        // Checking only one of them would let the other ship a project holding
        // a literal `{{module_list}}`.
        let mut values = base.clone();
        for slot in ["module_declarations", "module_list", "module_nav_flags", "modules_nav"] {
            values.insert(slot, String::new());
        }

        let mut wired = base.clone();
        wired.insert("module_declarations", "pub mod discovery;\n".to_string());
        wired.insert("module_list", ", Box::new(discovery::Discovery)".to_string());
        wired.insert(
            "module_nav_flags",
            "        (\"can_view_discovery\", \"discovery.view\"),\n".to_string(),
        );
        wired.insert("modules_nav", crate::auth_kit::DISCOVERY_NAV.to_string());

        // Every file the kit writes, rendered the way `new` renders it. This
        // reads the manifests rather than a list kept by hand, so a template
        // added tomorrow is covered the day it is added.
        //
        // `{{ spaced }}` is the *view* engine's syntax and is left alone on
        // purpose; only `{{unspaced}}` is a scaffold placeholder, which is why
        // the check looks at the character after the braces.
        for (path, template) in crate::auth_kit::FILES {
            for filled in [&values, &wired] {
                let rendered = render(template, filled);
                if let Some(found) = unrendered_placeholder(&rendered) {
                    panic!(
                        "the kit writes `{path}` into a project still holding `{found}` — \
                         either the value it wants is not among the ones `new` passes, or the \
                         placeholder should not be there"
                    );
                }
            }
        }

        // The dashboard's own files are only ever written in the wired state.
        for (path, template) in crate::auth_kit::DISCOVERY_FILES {
            let rendered = render(template, &wired);
            if let Some(found) = unrendered_placeholder(&rendered) {
                panic!("the discovery dashboard writes `{path}` still holding `{found}`");
            }
        }

        for (name, source) in [
            ("stubs::MAIN_RS", stubs::MAIN_RS),
            ("stubs::MAIN_RS_DB", stubs::MAIN_RS_DB),
        ] {
            let rendered = render(source, &values);
            assert!(
                unrendered_placeholder(&rendered).is_none(),
                "{name} still holds a placeholder after rendering: the value it wants is not \
                 among the ones `new` passes"
            );
        }
    }

    /// Whether any file under this directory implements `Plugin`.
    fn ships_a_plugin(directory: &std::path::Path) -> bool {
        let Ok(entries) = std::fs::read_dir(directory) else { return false };
        entries.filter_map(Result::ok).any(|entry| {
            let path = entry.path();
            if path.is_dir() {
                return ships_a_plugin(&path);
            }
            path.extension().is_some_and(|e| e == "rs")
                && std::fs::read_to_string(&path)
                    .is_ok_and(|text| text.contains("impl Plugin for"))
        })
    }

    /// A package that is switched on and never registered does nothing, and
    /// the generated file used to say nothing about it.
    #[test]
    fn the_scaffold_registers_the_plugins_it_was_asked_for() {
        let asked = ["telescope", "debugbar", "metrics"].map(str::to_string);
        let lines = plugin_lines(&asked, &[]);

        assert!(lines.contains(".plugin(Telescope::new())"), "{lines}");
        assert!(lines.contains(".plugin(DebugBar::new())"), "{lines}");
        assert!(lines.contains(".plugin(Metrics::new())"), "{lines}");

        // Nothing asked for, nothing written — a bare `main.rs` stays bare.
        assert_eq!(plugin_lines(&[], &[]), "");
    }

    /// The ones that need a database handle cannot be registered from a file
    /// that has none, so they are named in a comment rather than emitted as a
    /// line that would not compile.
    #[test]
    fn a_plugin_that_needs_wiring_is_named_rather_than_guessed_at() {
        let lines = plugin_lines(&["rbac".to_string(), "audit".to_string()], &[]);

        assert!(!lines.contains(".plugin(Rbac"), "an uncompilable line was written: {lines}");
        assert!(lines.contains("// Rbac::from_config"), "{lines}");
        assert!(lines.contains("// rustlavel::audit::Audit::new"), "{lines}");
    }

    /// Every expression the generator can write has to name a type the prelude
    /// exports, because the generated `main.rs` imports the prelude and
    /// nothing else. `Metrics` was not in it, and the line did not compile.
    #[test]
    fn every_registered_plugin_is_reachable_from_the_prelude() {
        let prelude = include_str!("../../rustlavel/src/lib.rs");
        let preludes_at = prelude.find("pub mod prelude").expect("the prelude moved");
        let exports = &prelude[preludes_at..];

        for kind in ["Telescope", "DebugBar", "Metrics"] {
            assert!(
                exports.contains(&format!("pub use crate::{kind};")),
                "{kind} is written into main.rs but the prelude does not export it"
            );
        }
    }

    use super::*;

    /// The list `--with` accepts has to be the list the meta-crate offers.
    ///
    /// These two drifted once already: `rbac` and `flags` were features of
    /// `rustlavel` for a release each before `rustlavel new --with rbac` would
    /// take them, which is a confusing way to find out a package exists. The
    /// manifest is the source of truth, so this reads it rather than repeating
    /// the list a third time.
    #[test]
    fn every_feature_on_the_meta_crate_is_a_package_the_scaffold_accepts() {
        let manifest = include_str!("../../rustlavel/Cargo.toml");

        let features: Vec<&str> = manifest
            .lines()
            .skip_while(|line| line.trim() != "[features]")
            .skip(1)
            .take_while(|line| !line.trim_start().starts_with('['))
            // Comments are not features. Without this a comment that happens
            // to contain `=` — `CACHE_DRIVER=valkey`, say — is read as one,
            // and the guard fails on prose.
            .filter(|line| !line.trim_start().starts_with('#'))
            .filter_map(|line| line.split_once('=').map(|(name, _)| name.trim()))
            // `default` and `full` are not packages, they are collections of
            // them; every other key is a package the scaffold should know.
            .filter(|name| !name.is_empty() && *name != "default" && *name != "full")
            .collect();

        assert!(features.len() > 20, "the feature list was not found: {features:?}");

        let known: Vec<&str> = PACKAGES.iter().map(|(name, _)| *name).collect();
        let missing: Vec<&&str> = features.iter().filter(|f| !known.contains(f)).collect();
        assert!(
            missing.is_empty(),
            "these are features of the rustlavel crate but `--with` refuses them: {missing:?}"
        );
    }

    /// `full` must mean every package, or it means whatever somebody
    /// remembered.
    ///
    /// `gateway` was missing from it for a release, so `features = ["full"]`
    /// quietly left out a crate — the kind of gap nobody finds by reading,
    /// because the list is long and sorted and looks complete.
    #[test]
    fn the_full_feature_contains_every_package() {
        let manifest = include_str!("../../rustlavel/Cargo.toml");

        let full: Vec<&str> = manifest
            .lines()
            .skip_while(|line| !line.trim_start().starts_with("full = ["))
            .skip(1)
            .take_while(|line| !line.trim().starts_with(']'))
            .map(|line| line.trim().trim_matches(|c| c == '"' || c == ','))
            .filter(|name| !name.is_empty())
            .collect();
        assert!(full.len() > 20, "the `full` list was not found: {full:?}");

        let packages: Vec<&str> = manifest
            .lines()
            .skip_while(|line| line.trim() != "[features]")
            .skip(1)
            .take_while(|line| !line.trim_start().starts_with('['))
            // Comments are not features. Without this a comment that happens
            // to contain `=` — `CACHE_DRIVER=valkey`, say — is read as one,
            // and the guard fails on prose.
            .filter(|line| !line.trim_start().starts_with('#'))
            .filter_map(|line| line.split_once('=').map(|(name, _)| name.trim()))
            .filter(|name| !name.is_empty() && *name != "default" && *name != "full")
            .collect();

        // `full` means "everything, for trying it out", and it has exactly one
        // deliberate hole. `sqlite` compiles a C library, so putting it in
        // `full` would make `cargo build --features full` fail on a machine
        // with no C compiler — for somebody whose only intent was to look at
        // the framework. Listed here rather than skipped silently, so adding a
        // second exception is a decision somebody has to write down.
        const NOT_IN_FULL: [&str; 1] = ["sqlite"];

        let missing: Vec<&&str> = packages
            .iter()
            .filter(|p| !full.contains(p) && !NOT_IN_FULL.contains(p))
            .collect();
        assert!(
            missing.is_empty(),
            "these packages exist but `full` does not turn them on: {missing:?}"
        );

        // And the hole stays a hole: if `sqlite` is ever added to `full`, this
        // fails and sends the reader to the comment above.
        let wrongly_included: Vec<&&str> =
            NOT_IN_FULL.iter().filter(|p| full.contains(p)).collect();
        assert!(
            wrongly_included.is_empty(),
            "`full` now turns on {wrongly_included:?}, which makes it need a C compiler"
        );
    }

    /// And the other direction, except for the one that is not a feature.
    #[test]
    fn the_scaffold_offers_nothing_the_meta_crate_cannot_turn_on() {
        let manifest = include_str!("../../rustlavel/Cargo.toml");
        for (package, _) in PACKAGES {
            // The kits are scaffolding rather than feature flags: each writes
            // files and expands into the packages that code imports.
            // Listed by name rather than matched by suffix, so adding one is
            // a decision somebody makes here rather than a naming accident.
            if package.ends_with("-kit") || *package == "discovery-ui" {
                continue;
            }
            assert!(
                manifest.contains(&format!("\n{package} = [")),
                "`--with {package}` is offered, but `rustlavel` has no such feature"
            );
        }
    }

    #[test]
    fn the_package_list_is_sorted_so_the_error_message_reads_in_order() {
        let names: Vec<&str> = PACKAGES.iter().map(|(name, _)| *name).collect();
        let mut sorted = names.clone();
        sorted.sort_unstable();
        assert_eq!(names, sorted, "keep PACKAGES alphabetical");
    }
}