ridl-core 0.6.0

The RIDL family compiler core: the incremental database, diagnostics, and the package and workspace model.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
//! Filesystem discovery: from an entry path to a loaded [`Workspace`]
//! (ADR-0002 §1, §4–5).
//!
//! This is the only module in the crate that touches the filesystem, and it
//! sits behind the default-on `fs` feature (ADR-0007 decision 5) so the crate
//! still builds for `wasm32-unknown-unknown` with `--no-default-features`.
//!
//! [`load_workspace`] walks from an entry path — a source file, a package
//! directory, or a workspace root — reads the `ridl.toml` manifests, loads
//! every source file (`.typl` and `.ridl` alike — a package may mix both)
//! into [`InputFile`] inputs, and enforces the package↔directory law (typl
//! reference §3.1): every file in a package directory must declare that
//! directory's package name (TYPL-002), and more than one `package`
//! declaration in a file is TYPL-001. A bare `.typl` or `.ridl` file with no
//! manifest anywhere up the tree loads in **single-file mode**: one synthetic
//! package named from the file's declared package, exempt from TYPL-002 (the
//! task 20 CLI contract). Every package directory — the bare file's directory
//! included — is also read for an `interfaces.lock`, which rides on the
//! [`Package`] as its [`PackageLock`]; a malformed one is RIDL-410 on the
//! file's own line (lock design §2, §8).
//!
//! Problems in loaded content — manifest diagnostics, the law violations, a
//! nested workspace (MANI-004), a broken member (MANI-008), a file that is
//! not valid UTF-8 — are accumulated [`Diagnostic`]s, never an error return
//! (ADR-0004 §5). `std::io::Error` is reserved for real filesystem failures.

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

use ridl_ir::codegen::{header_control_character, normalise_header};
use ridl_syntax::ast::{AstNode as _, SourceFile};
use rowan::{TextRange, TextSize};

use crate::db::{InputFile, RidlDatabase, parse_file};
use crate::diag::{DiagCode, Diagnostic, FileId, Severity, SourceMap, Span};
use crate::interface_lock;
use crate::lint::{LintLevels, LintScopes};
use crate::manifest::{Manifest, ManifestKind, TimingDefaults, parse_manifest};
use crate::package::{Package, PackageLock, PackageOrigin, Workspace, package_declarations};

/// The result of [`load_workspace`]: the salsa [`Workspace`] input, the
/// diagnostics the load accumulated, the interned path+text table the
/// diagnostics' [`Span`]s point into (what the caller hands to
/// [`render`](crate::diag::render())), and the effective lint levels by
/// directory (ADR-0024 decision 10): one scope for the workspace root,
/// one per member, one for a standalone package, none in single-file mode.
/// The scope keys are the directories in the same path form as the file
/// paths in `sources`, so [`LintScopes::for_path`] resolves a recorded path.
pub struct LoadedWorkspace {
    pub workspace: Workspace,
    pub diagnostics: Vec<Diagnostic>,
    pub sources: SourceMap,
    pub lints: LintScopes,
    /// The text of the file named by the root manifest's `[codegen]
    /// header-file`, normalised by [`ridl_ir::codegen::normalise_header`];
    /// `None` when no file is named, when the file holds no text, and in
    /// single-file mode.
    pub codegen_header: Option<String>,
    /// The member directory the entry lies in, when the entry is inside a
    /// member of the loaded workspace ([`find_root`] walked from the member to
    /// its workspace, or the entry named a path below a member); `None` for
    /// an entry at the workspace root, a standalone package, or single-file
    /// mode. The whole workspace is loaded and checked either way; a command
    /// that reports diagnostics reports only those under this directory
    /// (ADR-0024 decision 9). The path is in the same form as the file paths
    /// in `sources`.
    pub report_scope: Option<PathBuf>,
}

/// Unsaved source text for a file in a loaded package directory.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Overlay {
    pub path: PathBuf,
    pub text: String,
}

/// A filesystem failure or an overlay that cannot belong to the workspace.
#[derive(Debug)]
pub enum LoadError {
    Io(io::Error),
    OverlayNotSource(PathBuf),
    OverlayOutsideWorkspace {
        path: PathBuf,
        missing_directory: bool,
    },
}

impl std::fmt::Display for LoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io(e) => write!(f, "{e}"),
            Self::OverlayNotSource(p) => write!(
                f,
                "overlay `{}` is not a `.typl`, `.ridl` or `.rsdl` file",
                p.display()
            ),
            Self::OverlayOutsideWorkspace {
                path,
                missing_directory: true,
            } => write!(
                f,
                "overlay `{}` is in a directory that does not exist; create the directory first",
                path.display()
            ),
            Self::OverlayOutsideWorkspace {
                path,
                missing_directory: false,
            } => write!(
                f,
                "overlay `{}` is not in a package directory of the workspace loaded from this path",
                path.display()
            ),
        }
    }
}

impl std::error::Error for LoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            _ => None,
        }
    }
}

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

/// The comparison key for a path: its parent directory canonicalised, joined
/// with its file name. `None` when the parent directory does not exist.
fn overlay_key(path: &Path) -> Option<PathBuf> {
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir().ok()?.join(path)
    };
    Some(
        absolute
            .parent()?
            .canonicalize()
            .ok()?
            .join(absolute.file_name()?),
    )
}

/// Loads the workspace reachable from `entry` into `db`.
///
/// `entry` may be:
///
/// - a `.typl` or `.ridl` file — [`find_root`] from the file's directory is
///   the root; with no manifest anywhere up the tree the file loads in
///   single-file mode;
/// - a package directory or workspace root — [`find_root`] from the
///   directory is the root; a `[package]` manifest loads that package's
///   directory tree, a `[workspace]` manifest loads every member.
///
/// An entry inside a workspace member loads the whole workspace, so the
/// root's `[lints]`, `[defaults]` and `[imports]` apply to the member
/// and its imports of sibling members resolve;
/// [`LoadedWorkspace::report_scope`] records the member.
///
/// `[imports]` maps stay scoped per ADR-0002 §5: each [`Package`] carries the
/// `[imports]` of the manifest governing its directory tree (step 2), and
/// [`Workspace::imports`] holds only the workspace root's `[imports]` (step
/// 3, the shared default). Nothing is merged — a member's pin never leaks to
/// a sibling member; the task 9 resolver walks the order itself. In a
/// standalone package load the manifest's `[imports]` ride on its packages
/// and [`Workspace::imports`] is empty.
pub fn load_workspace(db: &mut RidlDatabase, entry: &Path) -> io::Result<LoadedWorkspace> {
    load_workspace_with(db, entry, &[]).map_err(|error| match error {
        LoadError::Io(e) => e,
        _ => unreachable!("no overlay error is possible without overlays"),
    })
}

/// Loads a workspace with unsaved source text substituted before parsing.
pub fn load_workspace_with(
    db: &mut RidlDatabase,
    entry: &Path,
    overlays: &[Overlay],
) -> Result<LoadedWorkspace, LoadError> {
    let mut loader = Loader::default();
    for overlay in overlays {
        if !overlay
            .path
            .extension()
            .is_some_and(|ext| ext == "typl" || ext == "ridl" || ext == "rsdl")
        {
            return Err(LoadError::OverlayNotSource(overlay.path.clone()));
        }
        let key = overlay_key(&overlay.path).ok_or_else(|| LoadError::OverlayOutsideWorkspace {
            path: overlay.path.clone(),
            missing_directory: true,
        })?;
        loader.overlays.push((key, overlay.clone(), false));
    }

    if entry.is_file() {
        match entry.parent().and_then(find_root) {
            Some(root) => loader.load_root(db, &root)?,
            None => loader.load_single_file(db, entry)?,
        }
    } else if entry.is_dir() {
        match find_root(entry) {
            Some(root) => loader.load_root(db, &root)?,
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::NotFound,
                    format!("no `ridl.toml` found at or above `{}`", entry.display()),
                )
                .into());
            }
        }
    } else {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            format!("`{}` does not exist", entry.display()),
        )
        .into());
    }

    if let Some((_, overlay, _)) = loader.overlays.iter().find(|(_, _, consumed)| !consumed) {
        return Err(LoadError::OverlayOutsideWorkspace {
            path: overlay.path.clone(),
            missing_directory: false,
        });
    }
    let report_scope = absolute(entry).and_then(|entry| {
        loader
            .member_dirs
            .iter()
            .find(|member| absolute(member).is_some_and(|member| entry.starts_with(member)))
            .cloned()
    });
    let workspace = Workspace::new(&*db, loader.packages, loader.workspace_imports);
    Ok(LoadedWorkspace {
        workspace,
        diagnostics: loader.diagnostics,
        sources: loader.sources,
        lints: loader.lints,
        codegen_header: loader.codegen_header,
        report_scope,
    })
}

/// The directory [`load_workspace`] loads from for an entry at or below
/// `dir` (ADR-0002 §4). It starts at the nearest directory at or above `dir`
/// that contains a `ridl.toml`. When that manifest is a `[package]`, the walk
/// continues upward:
///
/// - at the first `[workspace]` manifest it stops; that workspace is the root
///   when its `members` names the package directory, and the package is the
///   root otherwise;
/// - a `[package]` manifest above does not stop the walk;
/// - a manifest that cannot be read or parsed stops the walk and is the root,
///   so the loader reports why it failed;
/// - a directory that holds `.git` stops the walk after its own `ridl.toml`
///   is checked, and so does the filesystem root; the package is then the
///   root.
///
/// A relative `dir` gives a root in the same relative form, built with `..`
/// when the root is above the current directory. `None` means there is no
/// `ridl.toml` at or above `dir`. The command line, the language server and
/// the MCP server all call this, so every entry point loads the same root.
pub fn find_root(dir: &Path) -> Option<PathBuf> {
    let package = dir
        .ancestors()
        .find(|candidate| candidate.join("ridl.toml").is_file())?
        .to_path_buf();
    if !matches!(
        read_manifest_kind(&package),
        Some(ManifestKind::Package { .. })
    ) {
        return Some(package);
    }
    let Some(absolute_package) = absolute(&package) else {
        return Some(package);
    };
    for (levels, parent) in absolute_package.ancestors().skip(1).enumerate() {
        if parent.join("ridl.toml").is_file() {
            match read_manifest_kind(parent) {
                None => return Some(up(&package, levels + 1)),
                Some(ManifestKind::Workspace { members }) => {
                    let listed = members
                        .iter()
                        .any(|member| normalize(&parent.join(member)) == absolute_package);
                    return Some(if listed {
                        up(&package, levels + 1)
                    } else {
                        package
                    });
                }
                Some(ManifestKind::Package { .. }) => {}
            }
        }
        if parent.join(".git").exists() {
            break;
        }
    }
    Some(package)
}

/// The manifest kind of `dir/ridl.toml`, or `None` when the file cannot be
/// read as UTF-8 or does not parse as a manifest.
fn read_manifest_kind(dir: &Path) -> Option<ManifestKind> {
    let text = fs::read_to_string(dir.join("ridl.toml")).ok()?;
    parse_manifest(FileId::DETACHED, &text)
        .0
        .map(|manifest| manifest.kind)
}

/// `path` made absolute against the current directory and normalised
/// lexically; `None` when the current directory cannot be read.
fn absolute(path: &Path) -> Option<PathBuf> {
    if path.is_absolute() {
        Some(normalize(path))
    } else {
        Some(normalize(&std::env::current_dir().ok()?.join(path)))
    }
}

/// `path` with every `.` removed and every `..` applied to the component
/// before it, without reading the filesystem. A trailing `/` is dropped.
fn normalize(path: &Path) -> PathBuf {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if matches!(
                    normalized.components().next_back(),
                    Some(Component::Normal(_))
                ) {
                    normalized.pop();
                } else if !normalized.has_root() {
                    normalized.push("..");
                }
            }
            other => normalized.push(other),
        }
    }
    normalized
}

/// The directory `levels` levels above `path`, in the path form of `path`:
/// a trailing name is removed, and `..` is added once no name is left to
/// remove. Removing the last name of a relative path yields `.`, not the
/// empty path [`Path::ancestors`] yields: the empty path joins like the
/// current directory, but `read_dir`, `is_dir` and `exists` fail on it, so
/// a caller that walks the root's files would read nothing.
fn up(path: &Path, levels: usize) -> PathBuf {
    let mut result = path.to_path_buf();
    for _ in 0..levels {
        match result.components().next_back() {
            Some(Component::Normal(_)) => {
                result.pop();
                if result.as_os_str().is_empty() {
                    result = PathBuf::from(".");
                }
            }
            Some(Component::RootDir | Component::Prefix(_)) => {}
            Some(Component::CurDir) | None => result = PathBuf::from(".."),
            Some(Component::ParentDir) => result.push(".."),
        }
    }
    result
}

/// One loaded file plus its `package` declarations (dotted name, source
/// range), as [`Loader::load_file`] returns them.
type LoadedFile = (InputFile, Vec<(String, TextRange)>);

/// The accumulating state of one [`load_workspace`] run.
#[derive(Default)]
struct Loader {
    overlays: Vec<(PathBuf, Overlay, bool)>,
    sources: SourceMap,
    diagnostics: Vec<Diagnostic>,
    packages: Vec<Package>,
    /// The workspace root's own `[imports]` (ADR-0002 §5 step 3). Stays empty
    /// in a standalone package load and in single-file mode.
    workspace_imports: BTreeMap<String, String>,
    /// The workspace root's `[defaults]` (ridl §9.1). A member's own
    /// `[defaults]` shadows it per key; a key the member leaves unset rides on
    /// the member's packages. Stays empty in a standalone package load and in
    /// single-file mode.
    workspace_defaults: TimingDefaults,
    /// The workspace root's effective lint levels: the registry defaults
    /// overlaid with the root `[lints]` (ADR-0002 §4).
    /// Each member's own table is overlaid on a clone. Stays at the defaults
    /// in a standalone package load and in single-file mode.
    workspace_lints: LintLevels,
    /// The effective lint levels by directory: one scope for the root, one per
    /// member directory, one for a standalone package, none in single-file mode
    /// (ADR-0024 decision 10). Each key is the directory in the path form the
    /// loader records for the files under it.
    lints: LintScopes,
    /// The workspace root's (or standalone package's) normalised header text.
    codegen_header: Option<String>,
    /// Every member directory of a loaded workspace, in the path form of the
    /// files recorded under it. Empty outside workspace mode.
    member_dirs: Vec<PathBuf>,
}

impl Loader {
    /// Loads from a directory known to contain a `ridl.toml`, in whichever
    /// mode its manifest declares.
    fn load_root(&mut self, db: &mut RidlDatabase, root: &Path) -> io::Result<()> {
        let manifest_path = root.join("ridl.toml");
        // The error names the manifest: the root may be a workspace above the
        // entry (`find_root`), so the reader cannot assume which file failed.
        let text = fs::read_to_string(&manifest_path).map_err(|e| {
            io::Error::new(
                e.kind(),
                format!("cannot read `{}`: {e}", manifest_path.display()),
            )
        })?;
        let file_id = self.sources.file_id(&path_string(&manifest_path), &text);
        let (manifest, diags) = parse_manifest(file_id, &text);
        self.diagnostics.extend(diags);
        let Some(Manifest {
            kind,
            imports,
            defaults,
            lints,
            codegen_header_file,
        }) = manifest
        else {
            return Ok(());
        };
        if let Some((relative, range)) = codegen_header_file {
            let path = root.join(&relative);
            match fs::read_to_string(&path) {
                Ok(header) => match header_control_character(&header) {
                    None => self.codegen_header = normalise_header(&header),
                    Some(c) => self.diagnostics.push(error(
                        DiagCode::MANI_011,
                        file_id,
                        byte_range(range.start, range.end),
                        format!(
                            "`[codegen] header-file` contains a control character \
                             (U+{:04X}): `{}`",
                            u32::from(c),
                            path.display()
                        ),
                    )),
                },
                Err(e) => self.diagnostics.push(error(
                    DiagCode::MANI_011,
                    file_id,
                    byte_range(range.start, range.end),
                    format!(
                        "`[codegen] header-file` cannot be read: `{}`: {e}",
                        path.display()
                    ),
                )),
            }
        }
        // The root directory's scope: the registry defaults overlaid with the
        // root `[lints]`. In workspace mode it is also the base every member
        // overlays its own table on (ADR-0002 §4).
        let mut root_lints = LintLevels::default();
        root_lints.overlay(&lints);
        self.lints.insert(root.to_path_buf(), root_lints.clone());
        match kind {
            ManifestKind::Package { name, .. } => {
                // A standalone package: the manifest's `[imports]` and
                // `[defaults]` ride on its packages; the workspace maps
                // stay empty.
                self.load_package_tree(db, root, &name, &imports, &defaults)?;
            }
            ManifestKind::Workspace { members } => {
                // ADR-0002 §5 step 3: the workspace root's `[imports]` and
                // `[defaults]` are the shared defaults. Member maps are
                // never merged into them.
                self.workspace_imports = imports;
                self.workspace_defaults = defaults;
                self.workspace_lints = root_lints;
                for member in &members {
                    self.member_dirs.push(root.join(member));
                    self.load_member(db, root, member, file_id, &text)?;
                }
            }
        }
        Ok(())
    }

    /// Loads one workspace member directory: its manifest, then its package
    /// tree. A member manifest that declares `[workspace]` is a nested
    /// workspace — MANI-004 — and loads nothing.
    fn load_member(
        &mut self,
        db: &mut RidlDatabase,
        workspace_root: &Path,
        member: &str,
        workspace_file: FileId,
        workspace_text: &str,
    ) -> io::Result<()> {
        let manifest_path = workspace_root.join(member).join("ridl.toml");
        if !manifest_path.is_file() {
            // T7 records member paths unvalidated; the loader validates them
            // against the filesystem (MANI-008).
            self.diagnostics.push(error(
                DiagCode::MANI_008,
                workspace_file,
                member_entry_range(workspace_text, member),
                format!("workspace member `{member}` has no `ridl.toml`"),
            ));
            return Ok(());
        }
        let text = fs::read_to_string(&manifest_path)?;
        let file_id = self.sources.file_id(&path_string(&manifest_path), &text);
        let (manifest, diags) = parse_manifest(file_id, &text);
        self.diagnostics.extend(diags);
        let Some(Manifest {
            kind,
            imports,
            defaults,
            lints,
            codegen_header_file,
        }) = manifest
        else {
            return Ok(());
        };
        if let Some((_, range)) = codegen_header_file {
            self.diagnostics.push(error(
                DiagCode::MANI_012,
                file_id,
                byte_range(range.start, range.end),
                format!(
                    "`[codegen] header-file` is set in workspace member `{member}`; set it in the workspace root's `ridl.toml`"
                ),
            ));
        }
        // The member directory's scope: the root levels overlaid with the
        // member's own `[lints]` (ADR-0002 §4). The key
        // is the member directory in the same path form as the file paths
        // recorded under it, so `for_path` finds them by prefix.
        let mut member_lints = self.workspace_lints.clone();
        member_lints.overlay(&lints);
        self.lints.insert(workspace_root.join(member), member_lints);
        match kind {
            ManifestKind::Workspace { .. } => {
                self.diagnostics.push(error(
                    DiagCode::MANI_004,
                    file_id,
                    workspace_section_range(&text),
                    format!(
                        "workspace member `{member}` declares `[workspace]`; nested workspaces are forbidden"
                    ),
                ));
            }
            ManifestKind::Package { name, .. } => {
                // ADR-0002 §5 step 2: the member's `[imports]` ride on the
                // member's packages only — never merged into the workspace
                // map, never visible to a sibling member. Its
                // `[defaults]` shadow the workspace defaults per key (ridl §9.1);
                // a key the member leaves unset takes the workspace value.
                let member_defaults = defaults.or(&self.workspace_defaults);
                self.load_package_tree(
                    db,
                    &workspace_root.join(member),
                    &name,
                    &imports,
                    &member_defaults,
                )?;
            }
        }
        Ok(())
    }

    /// Loads the package rooted at `dir` under the package name `name`, then
    /// every subdirectory as its own package named by its path — the
    /// package↔directory law's "the name mirrors the directory path relative
    /// to the manifest root" (ADR-0002 §1). Every package in the tree carries
    /// `imports`, the governing manifest's `[imports]`. Directories are
    /// visited in name order; hidden directories, symlinked directories
    /// (following them could revisit the tree in a cycle), and directories
    /// with their own `ridl.toml` (separate package roots) are skipped.
    fn load_package_tree(
        &mut self,
        db: &mut RidlDatabase,
        dir: &Path,
        name: &str,
        imports: &BTreeMap<String, String>,
        defaults: &TimingDefaults,
    ) -> io::Result<()> {
        let mut source_files = Vec::new();
        let mut subdirs = Vec::new();
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            let is_symlink = entry.file_type()?.is_symlink();
            if path.is_dir() {
                if !is_symlink {
                    subdirs.push(path);
                }
            } else if path
                .extension()
                .is_some_and(|ext| ext == "typl" || ext == "ridl" || ext == "rsdl")
            {
                source_files.push(path);
            }
        }
        if !self.overlays.is_empty() {
            let directory_key = dir.canonicalize()?;
            for (key, _, _) in &self.overlays {
                if key.parent() == Some(directory_key.as_path())
                    && !source_files
                        .iter()
                        .any(|p| overlay_key(p).as_ref() == Some(key))
                {
                    let added = dir.join(key.file_name().expect("overlay keys have a file name"));
                    if !source_files.contains(&added) {
                        source_files.push(added);
                    }
                }
            }
        }
        source_files.sort();
        subdirs.sort();

        if !source_files.is_empty() {
            let mut files = Vec::new();
            for path in &source_files {
                if let Some((input, _)) = self.load_file(db, path, Some(name))? {
                    files.push(input);
                }
            }
            let lock = self.read_lock(dir)?;
            self.packages.push(Package::new(
                &*db,
                name.to_string(),
                files,
                PackageOrigin::WorkspaceMember,
                imports.clone(),
                defaults.clone(),
                lock,
            ));
        }

        for subdir in subdirs {
            let Some(dir_name) = subdir.file_name().map(|n| n.to_string_lossy().into_owned())
            else {
                continue;
            };
            if dir_name.starts_with('.') || subdir.join("ridl.toml").is_file() {
                continue;
            }
            self.load_package_tree(
                db,
                &subdir,
                &format!("{name}.{dir_name}"),
                imports,
                defaults,
            )?;
        }
        Ok(())
    }

    /// Loads one bare source file as a synthetic package named from its
    /// declared package — single-file mode, exempt from TYPL-002 (TYPL-001
    /// still applies). With no usable declaration the file stem names the
    /// package; the parser's FORM-104 for the missing declaration lives on
    /// `parse_file(..).errors()`, like every parse error — loader diagnostics
    /// carry only the manifest and law findings.
    fn load_single_file(&mut self, db: &mut RidlDatabase, path: &Path) -> io::Result<()> {
        let Some((input, decls)) = self.load_file(db, path, None)? else {
            // A non-UTF8 file: the diagnostic is recorded, nothing loads.
            return Ok(());
        };
        let name = decls
            .first()
            .map(|(name, _)| name.clone())
            .filter(|name| !name.is_empty())
            .unwrap_or_else(|| {
                path.file_stem()
                    .map(|stem| stem.to_string_lossy().into_owned())
                    .unwrap_or_else(|| "package".to_string())
            });
        // The file's directory is the package directory, so the lock is read
        // there too (plan decision PD-8).
        let lock = match path.parent() {
            Some(dir) => self.read_lock(dir)?,
            None => None,
        };
        self.packages.push(Package::new(
            &*db,
            name,
            vec![input],
            PackageOrigin::WorkspaceMember,
            BTreeMap::new(),
            TimingDefaults::default(),
            lock,
        ));
        Ok(())
    }

    /// Reads `dir/interfaces.lock` for the package rooted at `dir` (lock
    /// design §2). An absent file is `None`. A malformed file — one that is
    /// not valid UTF-8 included — is RIDL-410 on the offending line of the
    /// lock file itself, through this loader's source map, at the empty range
    /// 0..0 when there is no line to point at (plan decision PD-3); the
    /// package then carries no lock. Any other I/O failure is the error.
    fn read_lock(&mut self, dir: &Path) -> io::Result<Option<PackageLock>> {
        let path = path_string(&dir.join(interface_lock::FILE_NAME));
        let text = match interface_lock::read(dir) {
            Ok(Some(text)) => text,
            Ok(None) => return Ok(None),
            Err(err) if err.kind() == io::ErrorKind::InvalidData => {
                let file_id = self.sources.file_id(&path, "");
                self.diagnostics.push(error(
                    DiagCode::RIDL_410,
                    file_id,
                    byte_range(0, 0),
                    malformed_lock_message("the file is not valid UTF-8"),
                ));
                return Ok(None);
            }
            Err(err) => return Err(err),
        };
        match interface_lock::parse(&text) {
            Ok(lock) => Ok(Some(PackageLock { path, text, lock })),
            Err(malformed) => {
                let file_id = self.sources.file_id(&path, &text);
                self.diagnostics.push(error(
                    DiagCode::RIDL_410,
                    file_id,
                    malformed.range,
                    malformed_lock_message(&malformed.message),
                ));
                Ok(None)
            }
        }
    }

    /// Reads one source file into an [`InputFile`], parses it through the
    /// salsa query, and enforces the package↔directory law: every `package`
    /// declaration after the first is TYPL-001; when `expected` is given and
    /// the first declared name differs, TYPL-002 with the declaration line as
    /// the primary span. Returns the input plus the file's declarations, or
    /// `None` for a file that is not valid UTF-8 — recorded as a diagnostic
    /// and skipped, never an abort of the whole load (ADR-0004 §5).
    fn load_file(
        &mut self,
        db: &mut RidlDatabase,
        path: &Path,
        expected: Option<&str>,
    ) -> io::Result<Option<LoadedFile>> {
        let path_str = path_string(path);
        let replacement = self
            .overlays
            .iter_mut()
            .filter(|(key, _, _)| overlay_key(path).as_ref() == Some(key))
            .map(|(_, overlay, consumed)| {
                *consumed = true;
                overlay.text.clone()
            })
            .last();
        let text = match replacement
            .map(Ok)
            .unwrap_or_else(|| fs::read_to_string(path))
        {
            Ok(text) => text,
            Err(err) if err.kind() == io::ErrorKind::InvalidData => {
                // No text means no spans; the diagnostic points at the start
                // of the interned (empty) file. No code is cataloged for a
                // broken source encoding, so it carries the `NONE` sentinel.
                let file_id = self.sources.file_id(&path_str, "");
                self.diagnostics.push(error(
                    DiagCode::NONE,
                    file_id,
                    byte_range(0, 0),
                    format!("`{path_str}` is not valid UTF-8; the file is skipped"),
                ));
                return Ok(None);
            }
            Err(err) => return Err(err),
        };
        let file_id = self.sources.file_id(&path_str, &text);
        let input = InputFile::new(&*db, path_str, text);

        let parse = parse_file(&*db, input);
        let source =
            SourceFile::cast(parse.syntax()).expect("parser roots every tree in a SourceFile");
        let decls = package_declarations(&source);

        for (_, range) in decls.iter().skip(1) {
            self.diagnostics.push(error(
                DiagCode::TYPL_001,
                file_id,
                *range,
                "more than one `package` declaration in this file".to_string(),
            ));
        }
        if let Some((declared, range)) = decls.first()
            && crate::std_lib::is_reserved_package_name(declared)
        {
            // Reported on the declaration rather than on the manifest or the
            // directory, because that is the one place both paths meet: a
            // workspace member and single-file mode both arrive here, and the
            // issue this closes (driftsys/ridl#203) names both.
            //
            // The message states only the unreachability, which always holds.
            // The artifact overwrite that issue reports is a consequence in
            // package and workspace mode, where the output base is the package
            // name; in single-file mode the base is the file stem, so it
            // collides only when that stem is itself `ridl.std`, whatever the
            // extension. That distinction belongs in the catalogue entry, not
            // in a message that would then be false for some of the inputs it
            // greets.
            self.diagnostics.push(error(
                DiagCode::TYPL_010,
                file_id,
                *range,
                format!(
                    "`{declared}` is provided by the compiler, so a package cannot declare it; every package already imports all of `{declared}` implicitly (typl §3.2), which leaves these declarations unreachable under their own name. Rename the package"
                ),
            ));
        }
        if let (Some(expected), Some((declared, range))) = (expected, decls.first())
            && !declared.is_empty()
            && declared != expected
        {
            self.diagnostics.push(error(
                DiagCode::TYPL_002,
                file_id,
                *range,
                format!(
                    "package name `{declared}` does not mirror the directory path; every file in this directory must declare `package {expected}`"
                ),
            ));
        }
        Ok(Some((input, decls)))
    }
}

/// The interned string form of a filesystem path.
fn path_string(path: &Path) -> String {
    path.to_string_lossy().into_owned()
}

/// The RIDL-410 message: what is wrong with the lock file, then the fix the
/// lock design §8 names.
fn malformed_lock_message(reason: &str) -> String {
    format!(
        "`{}` is malformed: {reason} — resolve the conflict or restore the file from version \
         control, then run `ridl lock`",
        interface_lock::FILE_NAME
    )
}

/// The byte range of the quoted `member` entry inside a workspace manifest's
/// text, or the whole file when it cannot be found (T7 does not retain member
/// spans).
fn member_entry_range(text: &str, member: &str) -> TextRange {
    let quoted = format!("\"{member}\"");
    match text.find(&quoted) {
        Some(start) => byte_range(start, start + quoted.len()),
        None => byte_range(0, text.len()),
    }
}

/// The byte range of the `[workspace]` section header inside a manifest's
/// text, or the whole file as a fallback.
fn workspace_section_range(text: &str) -> TextRange {
    const HEADER: &str = "[workspace]";
    match text.find(HEADER) {
        Some(start) => byte_range(start, start + HEADER.len()),
        None => byte_range(0, text.len()),
    }
}

/// A `rowan::TextRange` over byte offsets.
fn byte_range(start: usize, end: usize) -> TextRange {
    TextRange::new(TextSize::from(start as u32), TextSize::from(end as u32))
}

/// Builds an error [`Diagnostic`]; loader diagnostics carry no secondary
/// labels or fix-its.
fn error(code: DiagCode, file: FileId, range: TextRange, message: String) -> Diagnostic {
    Diagnostic {
        code,
        severity: Severity::Error,
        message,
        primary: Span { file, range },
        labels: Vec::new(),
        fixits: Vec::new(),
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use salsa::Setter;
    use salsa::plumbing::AsId;

    use super::*;
    use crate::lint::{LintLevel, apply_lint_levels, lint_by_name};

    /// A unique directory under the system temp dir, removed on drop.
    struct TempDir(PathBuf);

    impl TempDir {
        fn new(label: &str) -> Self {
            static COUNTER: AtomicUsize = AtomicUsize::new(0);
            let mut path = std::env::temp_dir();
            path.push(format!(
                "ridl-core-workspace-{label}-{}-{}",
                std::process::id(),
                COUNTER.fetch_add(1, Ordering::SeqCst),
            ));
            fs::create_dir_all(&path).expect("create the temp dir");
            Self(path)
        }

        fn path(&self) -> &Path {
            &self.0
        }

        /// Writes `text` at `relative`, creating parent directories.
        fn write(&self, relative: &str, text: &str) -> PathBuf {
            let path = self.0.join(relative);
            fs::create_dir_all(path.parent().expect("relative paths have a parent"))
                .expect("create parent directories");
            fs::write(&path, text).expect("write the fixture file");
            path
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    fn codes(diags: &[Diagnostic]) -> Vec<&str> {
        diags.iter().map(|d| d.code.as_str()).collect()
    }

    fn overlay_fixture() -> (TempDir, PathBuf) {
        let dir = TempDir::new("overlay");
        dir.write(
            "p/ridl.toml",
            "[package]\nname = \"p\"\nversion = \"1.0.0\"\n",
        );
        let path = dir.write("p/a.typl", "package p\ntype A: integer [0..1]\n");
        (dir, path)
    }

    fn overlay(path: PathBuf, text: &str) -> Overlay {
        Overlay {
            path,
            text: text.to_string(),
        }
    }

    #[test]
    fn overlay_replaces_the_text_of_a_file_on_disk() {
        let (dir, path) = overlay_fixture();
        let text = "package p\n\ntype Other: integer [0..1]\n";
        let mut db = RidlDatabase::default();
        let loaded = load_workspace_with(
            &mut db,
            &dir.path().join("p"),
            &[overlay(path.clone(), text)],
        )
        .unwrap();
        let files = loaded.workspace.packages(&db)[0].files(&db);
        assert_eq!(files.len(), 1);
        let file = files[0];
        assert_eq!(file.text(&db), text);
        let entries: Vec<_> = loaded.sources.iter_files().collect();
        assert!(entries.contains(&(path_string(&path).as_str(), text)));
    }

    #[test]
    fn an_added_file_sorts_with_the_disk_files() {
        let (dir, _) = overlay_fixture();
        let mut db = RidlDatabase::default();
        let loaded = load_workspace_with(
            &mut db,
            &dir.path().join("p"),
            &[overlay(dir.path().join("p/0.typl"), "package p\n")],
        )
        .unwrap();
        let files = loaded.workspace.packages(&db)[0].files(&db);
        assert_eq!(files.len(), 2);
        assert!(files[0].path(&db).ends_with("0.typl"));
        assert!(files[1].path(&db).ends_with("a.typl"));
    }
    #[test]
    fn an_overlay_replaces_rather_than_adds() {
        let (dir, path) = overlay_fixture();
        let mut db = RidlDatabase::default();
        let loaded = load_workspace_with(
            &mut db,
            &dir.path().join("p"),
            &[overlay(
                path,
                "package p\ntype Replacement: integer [0..1]\n",
            )],
        )
        .unwrap();
        assert_eq!(loaded.workspace.packages(&db)[0].files(&db).len(), 1);
    }

    #[test]
    fn overlay_adds_a_file_to_the_package_of_its_directory() {
        let (dir, _) = overlay_fixture();
        let mut db = RidlDatabase::default();
        let loaded = load_workspace_with(
            &mut db,
            &dir.path().join("p"),
            &[overlay(dir.path().join("p/b.typl"), "package p\n")],
        )
        .unwrap();
        let files = loaded.workspace.packages(&db)[0].files(&db);
        assert_eq!(files.len(), 2);
        assert!(files[0].path(&db).ends_with("a.typl"));
        assert!(files[1].path(&db).ends_with("b.typl"));
    }

    #[test]
    fn overlay_in_an_existing_subdirectory_joins_its_package() {
        let (dir, _) = overlay_fixture();
        dir.write("p/sub/c.typl", "package p.sub\n");
        let mut db = RidlDatabase::default();
        let loaded = load_workspace_with(
            &mut db,
            &dir.path().join("p"),
            &[overlay(dir.path().join("p/sub/d.typl"), "package p.sub\n")],
        )
        .unwrap();
        let package = loaded
            .workspace
            .packages(&db)
            .iter()
            .find(|p| p.name(&db) == "p.sub")
            .unwrap();
        let files = package.files(&db);
        assert_eq!(files.len(), 2);
        assert!(files[0].path(&db).ends_with("c.typl"));
        assert!(files[1].path(&db).ends_with("d.typl"));
    }

    #[test]
    fn an_added_file_with_the_wrong_package_name_draws_typl_002() {
        let (dir, _) = overlay_fixture();
        let mut db = RidlDatabase::default();
        let loaded = load_workspace_with(
            &mut db,
            &dir.path().join("p"),
            &[overlay(dir.path().join("p/b.typl"), "package q\n")],
        )
        .unwrap();
        let diag = loaded
            .diagnostics
            .iter()
            .find(|d| d.code == DiagCode::TYPL_002)
            .unwrap();
        assert!(
            loaded
                .sources
                .path(diag.primary.file)
                .unwrap()
                .ends_with("b.typl")
        );
    }

    #[test]
    fn an_overlay_in_a_missing_directory_is_refused() {
        let (dir, _) = overlay_fixture();
        let result = load_workspace_with(
            &mut RidlDatabase::default(),
            &dir.path().join("p"),
            &[overlay(
                dir.path().join("p/nope/e.typl"),
                "package p.nope\n",
            )],
        );
        assert!(matches!(
            result,
            Err(LoadError::OverlayOutsideWorkspace {
                missing_directory: true,
                ..
            })
        ));
    }

    #[test]
    fn an_overlay_outside_the_workspace_is_refused() {
        let (dir, _) = overlay_fixture();
        let path = dir.write("sibling/a.typl", "package sibling\n");
        let result = load_workspace_with(
            &mut RidlDatabase::default(),
            &dir.path().join("p"),
            &[overlay(path, "package sibling\n")],
        );
        assert!(matches!(
            result,
            Err(LoadError::OverlayOutsideWorkspace {
                missing_directory: false,
                ..
            })
        ));
    }

    #[test]
    fn an_overlay_under_a_hidden_directory_is_refused() {
        let (dir, _) = overlay_fixture();
        fs::create_dir(dir.path().join("p/.hidden")).unwrap();
        let result = load_workspace_with(
            &mut RidlDatabase::default(),
            &dir.path().join("p"),
            &[overlay(
                dir.path().join("p/.hidden/f.typl"),
                "package p.hidden\n",
            )],
        );
        assert!(matches!(
            result,
            Err(LoadError::OverlayOutsideWorkspace {
                missing_directory: false,
                ..
            })
        ));
    }

    #[test]
    fn a_non_source_overlay_is_refused() {
        let (dir, _) = overlay_fixture();
        let result = load_workspace_with(
            &mut RidlDatabase::default(),
            &dir.path().join("p"),
            &[overlay(dir.path().join("p/ridl.toml"), "")],
        );
        assert!(matches!(result, Err(LoadError::OverlayNotSource(_))));
    }

    #[test]
    fn single_file_mode_takes_an_overlay_for_the_entry() {
        let dir = TempDir::new("overlay-single");
        let path = dir.write("x.typl", "package x\n");
        let text = "package x\ntype Other: integer [0..1]\n";
        let mut db = RidlDatabase::default();
        let loaded = load_workspace_with(&mut db, &path, &[overlay(path.clone(), text)]).unwrap();
        assert_eq!(
            loaded.workspace.packages(&db)[0].files(&db)[0].text(&db),
            text
        );
        let result = load_workspace_with(
            &mut db,
            &path,
            &[overlay(dir.path().join("y.typl"), "package y\n")],
        );
        assert!(matches!(
            result,
            Err(LoadError::OverlayOutsideWorkspace {
                missing_directory: false,
                ..
            })
        ));
    }

    #[cfg(unix)]
    #[test]
    fn overlay_matches_a_file_named_by_a_relative_entry() {
        let (dir, path) = overlay_fixture();
        let cwd = std::env::current_dir().unwrap();
        let mut relative = PathBuf::new();
        for part in cwd.components() {
            if matches!(part, std::path::Component::Normal(_)) {
                relative.push("..");
            }
        }
        relative.push(path.strip_prefix("/").unwrap());
        for (entry, overlay_path) in [(&relative, &path), (&path, &relative)] {
            let mut db = RidlDatabase::default();
            let text = "package p\ntype Other: integer [0..1]\n";
            let loaded =
                load_workspace_with(&mut db, entry, &[overlay(overlay_path.clone(), text)])
                    .unwrap();
            assert_eq!(
                loaded.workspace.packages(&db)[0].files(&db)[0].text(&db),
                text
            );
        }
        drop(dir);
    }

    #[test]
    fn load_workspace_without_overlays_is_unchanged() {
        let (dir, _) = overlay_fixture();
        let mut db = RidlDatabase::default();
        let first = load_workspace_with(&mut db, &dir.path().join("p"), &[]).unwrap();
        let describe = |db: &RidlDatabase, loaded: &LoadedWorkspace| {
            loaded
                .workspace
                .packages(db)
                .iter()
                .map(|p| {
                    (
                        p.name(db).clone(),
                        p.files(db)
                            .iter()
                            .map(|f| f.path(db).clone())
                            .collect::<Vec<_>>(),
                    )
                })
                .collect::<Vec<_>>()
        };
        let expected = describe(&db, &first);
        let mut other = RidlDatabase::default();
        let second = load_workspace(&mut other, &dir.path().join("p")).unwrap();
        assert_eq!(expected, describe(&other, &second));
    }

    const PACKAGE_MANIFEST: &str = "[package]\nname = \"veh.common\"\nversion = \"1.0.0\"\n";

    /// TYPL-010: a workspace member cannot declare a name the compiler
    /// provides (driftsys/ridl#203). Before this check the member compiled
    /// clean, its declarations were unreachable because every package already
    /// imports all of `ridl.std` implicitly, and its generated artifact was
    /// overwritten by the standard package's own.
    #[test]
    fn a_package_declaring_a_reserved_name_is_refused() {
        const SOURCE: &str = "package ridl.std\ntype MyOwnType: m\n";
        let dir = TempDir::new("reserved-name");
        dir.write(
            "ridl.toml",
            "[package]\nname = \"ridl.std\"\nversion = \"1.0.0\"\n",
        );
        dir.write("own.typl", SOURCE);

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(
            codes(&loaded.diagnostics),
            vec!["TYPL-010"],
            "got: {:?}",
            loaded.diagnostics
        );
        let diagnostic = &loaded.diagnostics[0];
        assert!(
            diagnostic.message.contains("ridl.std"),
            "the message names the package: {}",
            diagnostic.message
        );
        // The message states only what holds for every input that draws it.
        // The artifact collision does not: in single-file mode the output base
        // is the file stem. Asserting the absence keeps that clause from
        // returning to the message without the test noticing.
        assert!(
            diagnostic.message.contains("unreachable"),
            "the message states the consequence that always holds: {}",
            diagnostic.message
        );
        for conditional in ["artifact", "overwrit"] {
            assert!(
                !diagnostic.message.contains(conditional),
                "`{conditional}` is true only where the output base is the package name, \
                 so it belongs in the catalogue entry, not the message: {}",
                diagnostic.message
            );
        }
        // The declaration is what is pointed at, not the manifest or the
        // directory: it is the one place a workspace member and single-file
        // mode both pass through. Both ends are asserted, against the source
        // itself, so an over-wide span covering the whole file cannot pass.
        let declaration = SOURCE
            .lines()
            .next()
            .expect("the declaration is the first line");
        assert_eq!(
            (
                usize::from(diagnostic.primary.range.start()),
                usize::from(diagnostic.primary.range.end()),
            ),
            (0, declaration.len()),
            "reported on `{declaration}` exactly"
        );
    }

    /// The same refusal in single-file mode — `ridlc build ridl_std.typl`,
    /// the second form driftsys/ridl#203 names. Single-file mode is exempt
    /// from TYPL-002, so nothing else would have caught it.
    #[test]
    fn a_single_file_declaring_a_reserved_name_is_refused() {
        let dir = TempDir::new("reserved-name-single");
        let file = dir.write("ridl_std.typl", "package ridl.std\ntype MyOwnType: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, &file).expect("single-file mode loads");
        assert_eq!(
            codes(&loaded.diagnostics),
            vec!["TYPL-010"],
            "got: {:?}",
            loaded.diagnostics
        );
    }

    /// A name that merely starts with `ridl.` is not reserved: the reservation
    /// is the set of packages the compiler provides, not a namespace policy.
    #[test]
    fn only_a_compiler_provided_name_is_reserved() {
        let dir = TempDir::new("near-reserved");
        dir.write(
            "ridl.toml",
            "[package]\nname = \"ridl.stdlib\"\nversion = \"1.0.0\"\n",
        );
        dir.write("own.typl", "package ridl.stdlib\ntype MyOwnType: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(
            loaded.diagnostics,
            Vec::new(),
            "`ridl.stdlib` is not a package the compiler provides"
        );
    }

    /// (a) A two-file package loads, both files parse, and editing one
    /// re-parses only it — asserted by the re-executed query's `database_key`
    /// (issue #102).
    #[test]
    fn two_file_package_loads_and_edit_reparses_only_the_edited_file() {
        let dir = TempDir::new("two-file");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("b.typl", "package veh.common\ntype B: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(
            loaded.diagnostics,
            Vec::new(),
            "a clean package, no diagnostics"
        );

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "one package directory, one package");
        assert_eq!(packages[0].name(&db).as_str(), "veh.common");
        assert_eq!(*packages[0].origin(&db), PackageOrigin::WorkspaceMember);
        assert_eq!(
            packages[0].imports(&db),
            &BTreeMap::new(),
            "a manifest without `[imports]` yields an empty package map",
        );
        assert_eq!(
            loaded.workspace.imports(&db),
            &BTreeMap::new(),
            "a standalone load leaves the workspace map empty",
        );

        let files = packages[0].files(&db).clone();
        assert_eq!(files.len(), 2, "both .typl files load");
        for file in &files {
            assert_eq!(
                parse_file(&db, *file).errors(),
                &[],
                "both files parse clean"
            );
        }
        let a = files
            .iter()
            .copied()
            .find(|f| f.path(&db).ends_with("a.typl"))
            .expect("a.typl is loaded");
        let b = files
            .iter()
            .copied()
            .find(|f| f.path(&db).ends_with("b.typl"))
            .expect("b.typl is loaded");

        // Drain the executions the load itself ran; unchanged inputs are then
        // pure memo hits.
        db.take_executed_queries();
        let _ = parse_file(&db, a);
        let _ = parse_file(&db, b);
        assert_eq!(
            db.take_executed_queries(),
            Vec::new(),
            "re-querying unchanged inputs must run no executions",
        );

        // Edit A's text only: exactly one re-execution, and it is A's parse.
        a.set_text(&mut db)
            .to("package veh.common\ntype A: kg\n".to_string());
        let _ = parse_file(&db, a);
        let _ = parse_file(&db, b);
        let executed = db.take_executed_queries();
        assert_eq!(
            executed.len(),
            1,
            "editing one file re-parses exactly one file"
        );
        assert_eq!(
            salsa::attach(&db, || format!("{:?}", executed[0])),
            format!("parse_file({:?})", a.as_id()),
            "the re-executed query is the parse of the edited file",
        );
    }

    /// (b) A file that declares a different package than its directory
    /// requires is TYPL-002, primary span on the `package` line.
    #[test]
    fn typl_002_on_a_mismatching_file() {
        let dir = TempDir::new("mismatch");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        let bad_text = "package veh.wrong\ntype B: s\n";
        let bad_path = dir.write("bad.typl", bad_text);

        let mut db = RidlDatabase::default();
        let mut loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["TYPL-002"]);

        let diag = &loaded.diagnostics[0];
        assert_eq!(diag.severity, Severity::Error);
        assert_eq!(
            diag.primary.range,
            byte_range(0, "package veh.wrong".len()),
            "the primary span is the mismatching `package` line",
        );
        assert_eq!(
            diag.primary.file,
            loaded.sources.file_id(&path_string(&bad_path), bad_text),
            "the span points into the mismatching file",
        );

        // The law is a diagnostic, not an exclusion: the file stays loaded.
        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1);
        assert_eq!(packages[0].files(&db).len(), 1);
    }

    /// (c) More than one `package` declaration in a file is TYPL-001 on each
    /// declaration after the first.
    #[test]
    fn typl_001_on_a_double_package_declaration() {
        let dir = TempDir::new("double-decl");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write(
            "dup.typl",
            "package veh.common\npackage veh.extra\ntype A: m\n",
        );

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["TYPL-001"]);
        assert_eq!(
            loaded.diagnostics[0].primary.range,
            byte_range(19, 36),
            "the primary span is the second `package` declaration",
        );
    }

    /// (d) Workspace mode loads every member and keeps `[imports]` scoped per
    /// ADR-0002 §5: each member package carries only its own manifest's map
    /// (step 2 — a member's pin never leaks to a sibling), and the workspace
    /// map holds only the root's `[imports]` (step 3), never a merge.
    #[test]
    fn workspace_mode_scopes_imports_per_package() {
        let dir = TempDir::new("workspace");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"m-one\", \"m-two\"]\n\n[imports]\n\"third.dep\" = \"https://registry.example.com/third/dep@v1.0.0\"\n\"shared.util\" = \"https://registry.example.com/shared/util@v1.0.0\"\n",
        );
        dir.write(
            "m-one/ridl.toml",
            "[package]\nname = \"veh.one\"\nversion = \"1.0.0\"\n\n[imports]\n\"third.dep\" = \"https://mirror.example.com/third/dep@v2.0.0\"\n\"member.only\" = \"https://registry.example.com/member/only@v1.0.0\"\n",
        );
        dir.write("m-one/one.typl", "package veh.one\ntype A: m\n");
        dir.write(
            "m-two/ridl.toml",
            "[package]\nname = \"veh.two\"\nversion = \"1.0.0\"\n\n[imports]\n\"two.only\" = \"https://registry.example.com/two/only@v1.0.0\"\n",
        );
        dir.write("m-two/two.typl", "package veh.two\ntype B: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean workspace");

        let packages = loaded.workspace.packages(&db).clone();
        let names: Vec<String> = packages.iter().map(|p| p.name(&db).clone()).collect();
        assert_eq!(
            names,
            vec!["veh.one", "veh.two"],
            "both members load, in member order"
        );

        // Step 3: the workspace map is the root's `[imports]`, un-merged —
        // the member pin for `third.dep` must NOT overwrite the root's.
        let workspace_imports = loaded.workspace.imports(&db).clone();
        assert_eq!(
            workspace_imports.get("third.dep").map(String::as_str),
            Some("https://registry.example.com/third/dep@v1.0.0"),
            "the workspace map keeps the root pin, not the member pin",
        );
        assert_eq!(
            workspace_imports.get("shared.util").map(String::as_str),
            Some("https://registry.example.com/shared/util@v1.0.0"),
        );
        assert_eq!(workspace_imports.len(), 2, "no member entry leaks upward");

        // Step 2: each member package carries its own manifest's map only.
        let one_imports = packages[0].imports(&db).clone();
        assert_eq!(
            one_imports.get("third.dep").map(String::as_str),
            Some("https://mirror.example.com/third/dep@v2.0.0"),
            "the member's own pin shadows the workspace default for it alone",
        );
        assert_eq!(
            one_imports.get("member.only").map(String::as_str),
            Some("https://registry.example.com/member/only@v1.0.0"),
        );
        assert!(
            !one_imports.contains_key("two.only"),
            "a sibling's pin never leaks into another member",
        );
        assert_eq!(one_imports.len(), 2, "no workspace entry is merged in");

        let two_imports = packages[1].imports(&db).clone();
        assert_eq!(
            two_imports.get("two.only").map(String::as_str),
            Some("https://registry.example.com/two/only@v1.0.0"),
        );
        assert!(
            !two_imports.contains_key("member.only"),
            "the sibling's pin never leaks into this member",
        );
        assert!(
            !two_imports.contains_key("third.dep"),
            "neither the root default nor the sibling's pin is merged in",
        );
        assert_eq!(two_imports.len(), 1);
    }

    /// `[defaults].timing` follows the ADR-0002 §5 precedence merged at load:
    /// a member's own `[defaults]` shadows the workspace `[defaults]`; a member
    /// without one inherits the workspace default (ridl §9.1).
    #[test]
    fn defaults_timing_precedence_package_shadows_workspace() {
        let dir = TempDir::new("defaults-timing");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"m-own\", \"m-inherit\"]\n\n[defaults]\ntiming = \"[100ms..1000ms]\"\n",
        );
        // m-own configures its own default — it shadows the workspace default.
        dir.write(
            "m-own/ridl.toml",
            "[package]\nname = \"veh.own\"\nversion = \"1.0.0\"\n\n[defaults]\ntiming = \"[50ms..2s]\"\n",
        );
        dir.write("m-own/own.typl", "package veh.own\ntype A: m\n");
        // m-inherit configures none — it inherits the workspace default.
        dir.write(
            "m-inherit/ridl.toml",
            "[package]\nname = \"veh.inherit\"\nversion = \"1.0.0\"\n",
        );
        dir.write("m-inherit/inherit.typl", "package veh.inherit\ntype B: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean workspace");

        let packages = loaded.workspace.packages(&db).clone();
        let own = packages
            .iter()
            .find(|p| p.name(&db) == "veh.own")
            .expect("m-own loads");
        assert_eq!(
            own.defaults(&db).timing.as_deref(),
            Some("[50ms..2s]"),
            "the member's own `[defaults]` shadows the workspace default",
        );
        let inherit = packages
            .iter()
            .find(|p| p.name(&db) == "veh.inherit")
            .expect("m-inherit loads");
        assert_eq!(
            inherit.defaults(&db).timing.as_deref(),
            Some("[100ms..1000ms]"),
            "a member without `[defaults]` inherits the workspace default",
        );
    }

    /// Each `[defaults]` key resolves on its own: a member's value shadows the
    /// workspace's for that key only.
    #[test]
    fn defaults_precedence_is_per_key() {
        let dir = TempDir::new("defaults-per-key");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"m\"]\n\n[defaults]\ncommand_timing = \"[..2s]\"\nquery_timing = \"[..4s]\"\n",
        );
        dir.write(
            "m/ridl.toml",
            "[package]\nname = \"veh.m\"\nversion = \"1.0.0\"\n\n[defaults]\nquery_timing = \"[..5s]\"\n",
        );
        dir.write("m/m.typl", "package veh.m\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean workspace");
        let packages = loaded.workspace.packages(&db).clone();
        let member = packages
            .iter()
            .find(|p| p.name(&db) == "veh.m")
            .expect("the member loads");
        let defaults = member.defaults(&db);
        assert_eq!(defaults.command_timing.as_deref(), Some("[..2s]"));
        assert_eq!(defaults.query_timing.as_deref(), Some("[..5s]"));
        assert_eq!(defaults.timing, None);
    }

    /// Per-key precedence in the other direction: a member's `command_timing`
    /// is not overridden by the workspace's, and a member that leaves
    /// `query_timing` unset inherits the workspace's.
    #[test]
    fn defaults_precedence_is_per_key_in_both_directions() {
        let dir = TempDir::new("defaults-per-key-reverse");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"m\"]\n\n[defaults]\ncommand_timing = \"[..2s]\"\nquery_timing = \"[..4s]\"\n",
        );
        dir.write(
            "m/ridl.toml",
            "[package]\nname = \"veh.m\"\nversion = \"1.0.0\"\n\n[defaults]\ncommand_timing = \"[..7s]\"\n",
        );
        dir.write("m/m.typl", "package veh.m\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean workspace");
        let packages = loaded.workspace.packages(&db).clone();
        let member = packages
            .iter()
            .find(|p| p.name(&db) == "veh.m")
            .expect("the member loads");
        let defaults = member.defaults(&db);
        assert_eq!(
            defaults.command_timing.as_deref(),
            Some("[..7s]"),
            "the member's own `command_timing` wins over the workspace's",
        );
        assert_eq!(
            defaults.query_timing.as_deref(),
            Some("[..4s]"),
            "a member without `query_timing` inherits the workspace's",
        );
        assert_eq!(defaults.timing, None);
    }

    /// A standalone package's `command_timing` and `query_timing` ride on the
    /// root package and on a nested package directory alike (ridl §9.3).
    #[test]
    fn standalone_rpc_defaults_ride_on_the_tree() {
        let dir = TempDir::new("standalone-rpc-defaults");
        dir.write(
            "ridl.toml",
            "[package]\nname = \"veh.common\"\nversion = \"1.0.0\"\n\n[defaults]\ncommand_timing = \"[..2s]\"\nquery_timing = \"[5ms..4s]\"\n",
        );
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("sub/s.typl", "package veh.common.sub\ntype S: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package tree loads");
        assert_eq!(loaded.diagnostics, Vec::new());
        let packages = loaded.workspace.packages(&db).clone();
        let names: Vec<_> = packages.iter().map(|p| p.name(&db).clone()).collect();
        assert!(
            names.iter().any(|name| name == "veh.common")
                && names.iter().any(|name| name == "veh.common.sub"),
            "the root and the nested package both load: {names:?}",
        );
        for package in &packages {
            let defaults = package.defaults(&db);
            assert_eq!(
                defaults.command_timing.as_deref(),
                Some("[..2s]"),
                "{}",
                package.name(&db),
            );
            assert_eq!(
                defaults.query_timing.as_deref(),
                Some("[5ms..4s]"),
                "{}",
                package.name(&db),
            );
        }
    }

    /// A standalone package's `[defaults].timing` rides on every package in its
    /// directory tree, and single-file mode carries none (ridl §9.1).
    #[test]
    fn standalone_defaults_timing_rides_on_the_tree() {
        let dir = TempDir::new("standalone-defaults");
        dir.write(
            "ridl.toml",
            "[package]\nname = \"veh.common\"\nversion = \"1.0.0\"\n\n[defaults]\ntiming = \"[20ms..200ms]\"\n",
        );
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("sub/s.typl", "package veh.common.sub\ntype S: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package tree loads");
        assert_eq!(loaded.diagnostics, Vec::new());
        for package in loaded.workspace.packages(&db) {
            assert_eq!(
                package.defaults(&db).timing.as_deref(),
                Some("[20ms..200ms]"),
                "every package in the tree carries the manifest default",
            );
        }

        // Single-file mode: a bare file with no manifest anywhere up the tree.
        let bare = TempDir::new("standalone-defaults-bare");
        let single = bare.write("iface.ridl", "package solo\ntype A: m\n");
        let mut single_db = RidlDatabase::default();
        let single_loaded =
            load_workspace(&mut single_db, &single).expect("single-file mode loads");
        assert_eq!(
            single_loaded.workspace.packages(&single_db)[0].defaults(&single_db),
            &TimingDefaults::default(),
            "single-file mode carries no configured default",
        );
    }

    /// The lint scopes the loader builds in workspace mode: the root
    /// directory gets the defaults overlaid with the root `[lints]`, and
    /// each member directory gets the root levels overlaid with the member's
    /// own table (ADR-0002 §4, ADR-0024 decision 10). The scope keys share the
    /// path form of the file paths the loader records, so the path recorded
    /// for a member file resolves to the member's scope.
    #[test]
    fn lint_scopes_follow_root_then_member() {
        let dir = TempDir::new("lint-scopes");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"a\", \"b\"]\n\n[lints]\nmissing-timing = \"deny\"\nshared-error-type = \"allow\"\n",
        );
        dir.write(
            "a/ridl.toml",
            "[package]\nname = \"a\"\nversion = \"1.0.0\"\n\n[lints]\nmissing-timing = \"warn\"\n",
        );
        let a_file = dir.write("a/a.typl", "package a\ntype A: m\n");
        dir.write(
            "b/ridl.toml",
            "[package]\nname = \"b\"\nversion = \"1.0.0\"\n",
        );
        let b_file = dir.write("b/b.typl", "package b\ntype B: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean workspace");

        let missing_timing = lint_by_name("missing-timing").expect("missing-timing is a lint");
        let shared_error_type =
            lint_by_name("shared-error-type").expect("shared-error-type is a lint");
        let levels = |path: &Path| {
            loaded
                .lints
                .for_path(path)
                .unwrap_or_else(|| panic!("`{}` is in a scope", path.display()))
        };

        let in_a = levels(&a_file);
        assert_eq!(in_a.level(missing_timing), Some(LintLevel::Warn));
        assert_eq!(in_a.level(shared_error_type), Some(LintLevel::Allow));
        assert_eq!(levels(&b_file).level(missing_timing), Some(LintLevel::Deny));
        let root = levels(&dir.path().join("ridl.toml"));
        assert_eq!(root.level(missing_timing), Some(LintLevel::Deny));
        assert_eq!(root.level(shared_error_type), Some(LintLevel::Allow));
        assert_eq!(
            levels(&dir.path().join("a/ridl.toml")).level(missing_timing),
            Some(LintLevel::Warn),
        );

        // The path the loader recorded for the member file, not one built by
        // hand, is in the member's scope.
        let packages = loaded.workspace.packages(&db).clone();
        let a = packages
            .iter()
            .find(|p| p.name(&db) == "a")
            .expect("member a loads");
        let recorded = a.files(&db)[0].path(&db).clone();
        assert_eq!(
            levels(Path::new(&recorded)).level(missing_timing),
            Some(LintLevel::Warn),
            "the recorded path `{recorded}` resolves to the member's scope",
        );
    }

    /// A manifest diagnostic's file path resolves to the scope of the
    /// manifest's own directory, so a member's `[lints]` table sets the level
    /// of the MANI-010 it causes (ADR-0024 decision 11).
    #[test]
    fn a_member_manifest_diagnostic_is_in_the_member_scope() {
        let dir = TempDir::new("lint-scope-manifest");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"a\"]\n\n[lints]\nunknown-lint = \"deny\"\n",
        );
        dir.write(
            "a/ridl.toml",
            "[package]\nname = \"a\"\nversion = \"1.0.0\"\n\n[lints]\nunknown-lint = \"allow\"\nnope = \"warn\"\n",
        );
        dir.write("a/a.typl", "package a\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["MANI-010"]);
        let unknown_lint = lint_by_name("unknown-lint").expect("unknown-lint is a lint");
        let path = loaded
            .sources
            .path(loaded.diagnostics[0].primary.file)
            .expect("the manifest has a path");
        assert_eq!(
            loaded
                .lints
                .for_path(Path::new(path))
                .expect("the member manifest is in a scope")
                .level(unknown_lint),
            Some(LintLevel::Allow),
            "the recorded manifest path `{path}` resolves to the member's scope",
        );

        let mut diagnostics = loaded.diagnostics.clone();
        apply_lint_levels(&mut diagnostics, &loaded.sources, &loaded.lints);
        assert_eq!(
            diagnostics,
            Vec::new(),
            "`unknown-lint = \"allow\"` silences the MANI-010"
        );
    }

    /// A standalone package gets one scope for its directory, which covers
    /// every package in its tree; single-file mode gets none.
    #[test]
    fn standalone_lint_scope_covers_the_tree_and_single_file_has_none() {
        let dir = TempDir::new("lint-scope-standalone");
        dir.write(
            "ridl.toml",
            "[package]\nname = \"veh.common\"\nversion = \"1.0.0\"\n\n[lints]\nmissing-timing = \"deny\"\n",
        );
        let top = dir.write("a.typl", "package veh.common\ntype A: m\n");
        let nested = dir.write("sub/s.typl", "package veh.common.sub\ntype S: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package tree loads");
        assert_eq!(loaded.diagnostics, Vec::new());
        let missing_timing = lint_by_name("missing-timing").expect("missing-timing is a lint");
        for path in [&top, &nested] {
            assert_eq!(
                loaded
                    .lints
                    .for_path(path)
                    .unwrap_or_else(|| panic!("`{}` is in a scope", path.display()))
                    .level(missing_timing),
                Some(LintLevel::Deny),
            );
        }

        let bare = TempDir::new("lint-scope-bare");
        let single = bare.write("iface.ridl", "package solo\ntype A: m\n");
        let mut single_db = RidlDatabase::default();
        let single_loaded =
            load_workspace(&mut single_db, &single).expect("single-file mode loads");
        assert!(
            single_loaded.lints.for_path(&single).is_none(),
            "single-file mode has no lint scope",
        );
    }

    /// (e) A member manifest that declares `[workspace]` is a nested
    /// workspace: MANI-004, and the member loads nothing.
    #[test]
    fn mani_004_on_a_nested_workspace_member() {
        let dir = TempDir::new("nested");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"m-bad\", \"m-good\"]\n",
        );
        let bad_text = "[workspace]\nmembers = []\n";
        let bad_path = dir.write("m-bad/ridl.toml", bad_text);
        dir.write(
            "m-good/ridl.toml",
            "[package]\nname = \"veh.good\"\nversion = \"1.0.0\"\n",
        );
        dir.write("m-good/good.typl", "package veh.good\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let mut loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["MANI-004"]);

        let diag = &loaded.diagnostics[0];
        assert_eq!(diag.severity, Severity::Error);
        assert_eq!(
            diag.primary.file,
            loaded.sources.file_id(&path_string(&bad_path), bad_text),
            "the span points into the member's own manifest",
        );
        assert_eq!(
            diag.primary.range,
            byte_range(0, "[workspace]".len()),
            "the span is the `[workspace]` section header",
        );

        let packages = loaded.workspace.packages(&db).clone();
        let names: Vec<String> = packages.iter().map(|p| p.name(&db).clone()).collect();
        assert_eq!(names, vec!["veh.good"], "the nested member loads nothing");
    }

    /// A workspace member path with no manifest is MANI-008 and skipped; the
    /// rest of the workspace still loads.
    #[test]
    fn mani_008_on_a_missing_member_directory() {
        let dir = TempDir::new("missing-member");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"m-gone\", \"m-good\"]\n",
        );
        dir.write(
            "m-good/ridl.toml",
            "[package]\nname = \"veh.good\"\nversion = \"1.0.0\"\n",
        );
        dir.write("m-good/good.typl", "package veh.good\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["MANI-008"]);
        assert_eq!(loaded.diagnostics[0].severity, Severity::Error);
        assert!(loaded.diagnostics[0].message.contains("m-gone"));

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1);
        assert_eq!(packages[0].name(&db).as_str(), "veh.good");
    }

    /// A subdirectory of a package root is its own package, named by its
    /// directory path relative to the manifest root (ADR-0002 §1); every
    /// package in the tree carries the governing manifest's `[imports]`.
    #[test]
    fn a_subdirectory_is_its_own_package_named_by_its_path() {
        let dir = TempDir::new("subdir");
        dir.write(
            "ridl.toml",
            "[package]\nname = \"veh.common\"\nversion = \"1.0.0\"\n\n[imports]\n\"some.dep\" = \"https://registry.example.com/some/dep@v1.0.0\"\n",
        );
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("types/t.typl", "package veh.common.types\ntype T: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package tree loads");
        assert_eq!(loaded.diagnostics, Vec::new());

        let packages = loaded.workspace.packages(&db).clone();
        let names: Vec<String> = packages.iter().map(|p| p.name(&db).clone()).collect();
        assert_eq!(names, vec!["veh.common", "veh.common.types"]);
        for package in &packages {
            assert_eq!(
                package.imports(&db).get("some.dep").map(String::as_str),
                Some("https://registry.example.com/some/dep@v1.0.0"),
                "every package in the manifest's tree carries its `[imports]`",
            );
        }
        assert_eq!(
            loaded.workspace.imports(&db),
            &BTreeMap::new(),
            "a standalone load leaves the workspace map empty",
        );
    }

    /// A package directory may mix `.typl` and `.ridl`
    /// files — `.ridl` is accepted everywhere `.typl` is, under the same
    /// package↔directory law.
    #[test]
    fn a_package_directory_mixes_typl_and_ridl_files() {
        let dir = TempDir::new("mixed");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("b.ridl", "package veh.common\ntype B: s\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean mixed package");

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "one package directory, one package");
        let files = packages[0].files(&db).clone();
        assert_eq!(files.len(), 2, "both the .typl and the .ridl file load");
        for file in &files {
            assert_eq!(
                parse_file(&db, *file).errors(),
                &[],
                "both files parse clean"
            );
        }
        assert!(files.iter().any(|f| f.path(&db).ends_with("a.typl")));
        assert!(files.iter().any(|f| f.path(&db).ends_with("b.ridl")));
    }

    /// A package directory loads its `.rsdl` files beside its `.typl` and
    /// `.ridl` files (rsdl reference §2: a package may hold all three), each
    /// parsed under the profile its extension selects.
    #[test]
    fn a_package_directory_loads_its_rsdl_files() {
        let dir = TempDir::new("rsdl");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        dir.write("b.ridl", "package veh.common\ntype B: s\n");
        dir.write("c.rsdl", "package veh.common\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "a clean mixed package");

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "one package directory, one package");
        let files = packages[0].files(&db).clone();
        let paths: Vec<&str> = files.iter().map(|f| f.path(&db).as_str()).collect();
        assert_eq!(files.len(), 3, "the .rsdl file loads too: {paths:?}");
        let rsdl = files
            .iter()
            .find(|f| f.path(&db).ends_with("c.rsdl"))
            .expect("the .rsdl file is a package file");
        assert_eq!(
            crate::db::profile_of_path(rsdl.path(&db)),
            ridl_syntax::Profile::Rsdl
        );
        assert_eq!(
            parse_file(&db, *rsdl).errors(),
            &[],
            "the .rsdl file parses clean"
        );
    }

    /// Single-file mode accepts a bare `.ridl` entry, like a bare `.typl`.
    #[test]
    fn single_file_mode_accepts_a_bare_ridl_entry() {
        let dir = TempDir::new("single-ridl");
        let path = dir.write("iface.ridl", "package veh.iface\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, &path).expect("single-file mode loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "exempt from TYPL-002");

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "one synthetic package");
        assert_eq!(
            packages[0].name(&db).as_str(),
            "veh.iface",
            "named from the file's declared package",
        );
    }

    /// A symlinked directory is not followed by the tree walk — following it
    /// could revisit the tree in a cycle and duplicate packages endlessly.
    #[cfg(unix)]
    #[test]
    fn a_symlinked_directory_is_not_followed() {
        let dir = TempDir::new("symlink");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        // A symlink pointing back at the package root: a cycle.
        std::os::unix::fs::symlink(dir.path(), dir.path().join("loop"))
            .expect("create the directory symlink");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(loaded.diagnostics, Vec::new());

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "the symlink cycle adds no packages");
        assert_eq!(packages[0].name(&db).as_str(), "veh.common");
    }

    /// A `.typl` file that is not valid UTF-8 becomes a diagnostic and is
    /// skipped; the rest of the package still loads (ADR-0004 §5 — never a
    /// hard error for content problems).
    #[test]
    fn a_non_utf8_file_is_reported_and_skipped() {
        let dir = TempDir::new("non-utf8");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.typl", "package veh.common\ntype A: m\n");
        fs::write(dir.path().join("bad.typl"), [0xFF, 0xFE, 0x00, 0x9F])
            .expect("write the non-UTF8 fixture");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the load continues");
        assert_eq!(loaded.diagnostics.len(), 1);
        assert!(
            loaded.diagnostics[0].message.contains("UTF-8"),
            "the diagnostic names the encoding problem",
        );

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1);
        let files = packages[0].files(&db).clone();
        assert_eq!(files.len(), 1, "only the valid file loads");
        assert!(files[0].path(&db).ends_with("a.typl"));
    }

    /// (g) Single-file mode: a bare `.typl` file with no manifest up the tree
    /// loads as one synthetic package named from its declared package, exempt
    /// from TYPL-002. The E0 walking-skeleton fixture is the contract input.
    #[test]
    fn single_file_mode_loads_the_e0_fixture() {
        let fixture = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../ridl-syntax/fixtures/walking_skeleton.typl",
        );
        let text = fs::read_to_string(fixture).expect("the E0 fixture exists");
        assert!(
            text.contains("package fixtures"),
            "the fixture declares `package fixtures`",
        );

        // Copied into an empty temp dir so no manifest exists up the tree —
        // and the directory name never matches the declared package, which
        // proves the TYPL-002 exemption.
        let dir = TempDir::new("single-file");
        let path = dir.write("walking_skeleton.typl", &text);

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, &path).expect("single-file mode loads");
        assert_eq!(loaded.diagnostics, Vec::new(), "exempt from TYPL-002");

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 1, "one synthetic package");
        assert_eq!(
            packages[0].name(&db).as_str(),
            "fixtures",
            "named from the file's declared package",
        );
        assert_eq!(*packages[0].origin(&db), PackageOrigin::WorkspaceMember);

        let files = packages[0].files(&db).clone();
        assert_eq!(files.len(), 1);
        assert_eq!(
            parse_file(&db, files[0]).errors(),
            &[],
            "the fixture parses clean"
        );
    }

    // --- the interface lock (lock design §2, §8) --------------------------

    const LOCK_TEXT: &str = "\
# interfaces.lock — written by ridl lock; do not edit by hand.
next 3
Cabin 1
service:veh.common.climate 2
";

    /// A well-formed `interfaces.lock` beside the sources rides on the
    /// package: its path, its text and the parsed table (the text and path
    /// travel so a later checker diagnostic can point into the file).
    #[test]
    fn a_lock_beside_the_sources_rides_on_the_package() {
        let dir = TempDir::new("lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");
        let lock_path = dir.write("interfaces.lock", LOCK_TEXT);

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(
            loaded.diagnostics,
            Vec::new(),
            "a well-formed lock draws nothing"
        );

        let packages = loaded.workspace.packages(&db).clone();
        let lock = packages[0]
            .lock(&db)
            .as_ref()
            .expect("the lock rides on the package");
        assert_eq!(lock.path, path_string(&lock_path));
        assert_eq!(lock.text, LOCK_TEXT);
        assert_eq!(lock.lock.next, 3);
        assert_eq!(lock.lock.entries.len(), 2);
        assert_eq!(
            lock.lock.entries[1].key,
            crate::interface_lock::LockKey::Service("veh.common.climate".to_string())
        );
    }

    #[test]
    fn a_package_with_no_lock_has_none() {
        let dir = TempDir::new("no-lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(loaded.diagnostics, Vec::new());
        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(*packages[0].lock(&db), None);
    }

    /// RIDL-410 is reported on the offending line of the lock file itself,
    /// through the loader's source map (PD-3), and the package then carries
    /// no lock.
    #[test]
    fn a_malformed_lock_is_ridl_410_on_its_own_line() {
        let dir = TempDir::new("bad-lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");
        let text = "# interfaces.lock — written by ridl lock; do not edit by hand.\n\
                    next 2\n\
                    Cabin 1\n\
                    Door 1\n";
        let lock_path = dir.write("interfaces.lock", text);

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), ["RIDL-410"]);
        let diagnostic = &loaded.diagnostics[0];
        assert_eq!(diagnostic.severity, Severity::Error);
        assert_eq!(
            loaded.sources.path(diagnostic.primary.file),
            Some(path_string(&lock_path).as_str()),
            "the span is in the lock file"
        );
        assert_eq!(loaded.sources.text(diagnostic.primary.file), Some(text));
        let line_start = text
            .find("Door 1")
            .expect("the offending line is in the text");
        assert_eq!(
            diagnostic.primary.range,
            byte_range(line_start, line_start + "Door 1".len()),
            "the span is the offending line"
        );
        assert_eq!(
            diagnostic.message,
            "`interfaces.lock` is malformed: number 1 is on two entries: `Cabin` and `Door` — \
             resolve the conflict or restore the file from version control, then run `ridl lock`"
        );

        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(
            *packages[0].lock(&db),
            None,
            "a malformed lock does not ride on the package"
        );
    }

    /// PD-3: an empty lock file, which has no `next` line, is reported at
    /// 0..0 of the file.
    #[test]
    fn an_empty_lock_is_ridl_410_at_the_start_of_the_file() {
        let dir = TempDir::new("empty-lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");
        dir.write("interfaces.lock", "");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), ["RIDL-410"]);
        assert_eq!(loaded.diagnostics[0].primary.range, byte_range(0, 0));
        assert!(
            loaded.diagnostics[0].message.contains("no `next` line"),
            "got: {}",
            loaded.diagnostics[0].message
        );
    }

    /// A lock file that is not valid UTF-8 is RIDL-410 at 0..0 too — the
    /// treatment the loader gives a source file that is not valid UTF-8.
    #[test]
    fn a_lock_that_is_not_utf8_is_ridl_410() {
        let dir = TempDir::new("binary-lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");
        fs::write(dir.path().join("interfaces.lock"), [0xff, 0xfe, b'\n'])
            .expect("write the bytes");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), ["RIDL-410"]);
        assert!(
            loaded.diagnostics[0].message.contains("not valid UTF-8"),
            "got: {}",
            loaded.diagnostics[0].message
        );
        assert_eq!(loaded.diagnostics[0].primary.range, byte_range(0, 0));
        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(*packages[0].lock(&db), None);
    }

    /// PD-8: a bare `.ridl` file with no manifest reads `interfaces.lock`
    /// from the file's directory.
    #[test]
    fn single_file_mode_reads_the_lock_beside_the_file() {
        let dir = TempDir::new("single-lock");
        let path = dir.write("iface.ridl", "package veh.iface\ntype A: m\n");
        dir.write("interfaces.lock", LOCK_TEXT);

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, &path).expect("single-file mode loads");
        assert_eq!(loaded.diagnostics, Vec::new());
        let packages = loaded.workspace.packages(&db).clone();
        let lock = packages[0]
            .lock(&db)
            .as_ref()
            .expect("the lock rides on the synthetic package");
        assert_eq!(lock.lock.next, 3);
    }

    /// The file is per package (lock design §2): a subdirectory package reads
    /// its own directory's lock, not its parent's.
    #[test]
    fn a_subdirectory_package_reads_its_own_lock() {
        let dir = TempDir::new("subdir-lock");
        dir.write("ridl.toml", PACKAGE_MANIFEST);
        dir.write("a.ridl", "package veh.common\ntype A: m\n");
        dir.write("interfaces.lock", LOCK_TEXT);
        dir.write("sub/b.ridl", "package veh.common.sub\ntype B: m\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the tree loads");
        assert_eq!(loaded.diagnostics, Vec::new());
        let packages = loaded.workspace.packages(&db).clone();
        assert_eq!(packages.len(), 2);
        assert!(
            packages[0].lock(&db).is_some(),
            "the root package has a lock"
        );
        assert_eq!(
            *packages[1].lock(&db),
            None,
            "the subdirectory package has none"
        );
    }

    // Root discovery from a member (ADR-0002 §4, issue #529).

    const PACKAGE_A: &str = "[package]\nname = \"a\"\nversion = \"1.0.0\"\n";
    const PACKAGE_B: &str = "[package]\nname = \"b\"\nversion = \"1.0.0\"\n";

    #[test]
    fn find_root_walks_from_a_member_to_its_workspace() {
        let dir = TempDir::new("find-root-member");
        dir.write("ridl.toml", "[workspace]\nmembers = [\"a\", \"b\"]\n");
        dir.write("a/ridl.toml", PACKAGE_A);
        dir.write("a/src/a.typl", "package a.src\n");
        dir.write("b/ridl.toml", PACKAGE_B);

        assert_eq!(
            find_root(&dir.path().join("a/src")),
            Some(dir.path().to_path_buf())
        );
        assert_eq!(
            find_root(&dir.path().join("a")),
            Some(dir.path().to_path_buf())
        );
    }

    /// A member listed as `./a/` still names the package directory `a`.
    #[test]
    fn find_root_normalises_the_member_path() {
        let dir = TempDir::new("find-root-normalise");
        dir.write("ridl.toml", "[workspace]\nmembers = [\"./a/\"]\n");
        dir.write("a/ridl.toml", PACKAGE_A);

        assert_eq!(
            find_root(&dir.path().join("a")),
            Some(dir.path().to_path_buf())
        );
    }

    #[test]
    fn find_root_keeps_an_unlisted_package_standalone() {
        let dir = TempDir::new("find-root-unlisted");
        dir.write("ridl.toml", "[workspace]\nmembers = [\"b\"]\n");
        dir.write("a/ridl.toml", PACKAGE_A);
        dir.write("b/ridl.toml", PACKAGE_B);

        assert_eq!(find_root(&dir.path().join("a")), Some(dir.path().join("a")));
    }

    #[test]
    fn find_root_stops_at_the_first_workspace() {
        let dir = TempDir::new("find-root-first-workspace");
        dir.write("ridl.toml", "[workspace]\nmembers = [\"inner/a\"]\n");
        dir.write("inner/ridl.toml", "[workspace]\nmembers = [\"b\"]\n");
        dir.write("inner/a/ridl.toml", PACKAGE_A);

        assert_eq!(
            find_root(&dir.path().join("inner/a")),
            Some(dir.path().join("inner/a"))
        );
    }

    #[test]
    fn find_root_stops_at_a_git_directory() {
        let dir = TempDir::new("find-root-git");
        dir.write("ridl.toml", "[workspace]\nmembers = [\"repo/a\"]\n");
        fs::create_dir_all(dir.path().join("repo/.git")).expect("create .git");
        dir.write("repo/a/ridl.toml", PACKAGE_A);

        assert_eq!(
            find_root(&dir.path().join("repo/a")),
            Some(dir.path().join("repo/a"))
        );
    }

    /// The directory that holds `.git` is still checked for its own
    /// `ridl.toml` before the walk stops.
    #[test]
    fn find_root_checks_the_manifest_beside_a_git_directory() {
        let dir = TempDir::new("find-root-git-root");
        dir.write("ridl.toml", "[workspace]\nmembers = [\"a\"]\n");
        fs::create_dir_all(dir.path().join(".git")).expect("create .git");
        dir.write("a/ridl.toml", PACKAGE_A);

        assert_eq!(
            find_root(&dir.path().join("a")),
            Some(dir.path().to_path_buf())
        );
    }

    /// A manifest above the package that cannot be read stops the walk and is
    /// returned, so the loader reports why.
    #[test]
    fn find_root_returns_an_unreadable_manifest_above_the_package() {
        let dir = TempDir::new("find-root-unreadable");
        fs::write(dir.path().join("ridl.toml"), [0xff, 0xfe]).expect("write the manifest");
        dir.write("a/ridl.toml", PACKAGE_A);

        assert_eq!(
            find_root(&dir.path().join("a")),
            Some(dir.path().to_path_buf())
        );
    }

    /// A relative entry inside the current directory's member reaches the
    /// workspace above the current directory, and the root keeps the
    /// relative form.
    #[test]
    fn up_keeps_the_relative_form_of_the_entry() {
        assert_eq!(up(Path::new("members/a"), 2), PathBuf::from("."));
        assert_eq!(up(Path::new("a"), 1), PathBuf::from("."));
        assert_eq!(up(Path::new("a"), 2), PathBuf::from(".."));
        assert_eq!(up(Path::new("."), 2), PathBuf::from("../.."));
        assert_eq!(up(Path::new(""), 1), PathBuf::from(".."));
        assert_eq!(up(Path::new("a/.."), 1), PathBuf::from("a/../.."));
        assert_eq!(up(Path::new("/w/a"), 1), PathBuf::from("/w"));
    }

    #[test]
    fn member_entry_sets_report_scope() {
        let dir = TempDir::new("report-scope");
        dir.write("ridl.toml", "[workspace]\nmembers = [\"a\", \"b\"]\n");
        dir.write("a/ridl.toml", PACKAGE_A);
        dir.write("a/a.typl", "package a\ntype A: integer [0..1]\n");
        dir.write("b/ridl.toml", PACKAGE_B);
        let b_file = dir.write("b/b.typl", "package b\ntype B: integer [0..1]\n");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, &dir.path().join("a")).expect("the workspace loads");
        assert_eq!(loaded.report_scope, Some(dir.path().join("a")));
        let mut names: Vec<_> = loaded
            .workspace
            .packages(&db)
            .iter()
            .map(|p| p.name(&db).clone())
            .collect();
        names.sort();
        assert_eq!(names, vec!["a", "b"], "both members compile");

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, &b_file).expect("the workspace loads");
        assert_eq!(loaded.report_scope, Some(dir.path().join("b")));

        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(loaded.report_scope, None, "the root reports on everything");
    }

    #[test]
    fn codegen_header_is_read_and_normalised() {
        let dir = TempDir::new("codegen-header");
        dir.write(
            "ridl.toml",
            &format!("{PACKAGE_A}\n[codegen]\nheader-file = \"H.txt\"\n"),
        );
        dir.write("a.typl", "package a\ntype A: integer [0..1]\n");
        dir.write("H.txt", "SPDX-License-Identifier: MIT\r\n");
        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
        assert_eq!(
            loaded.codegen_header.as_deref(),
            Some("SPDX-License-Identifier: MIT")
        );
    }

    #[test]
    fn codegen_header_file_missing_is_mani_011() {
        let dir = TempDir::new("codegen-header-missing");
        let manifest = format!("{PACKAGE_A}\n[codegen]\nheader-file = \"nope.txt\"\n");
        dir.write("ridl.toml", &manifest);
        dir.write("a.typl", "package a\ntype A: integer [0..1]\n");
        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["MANI-011"]);
        let diag = &loaded.diagnostics[0];
        let start = usize::from(diag.primary.range.start());
        let end = usize::from(diag.primary.range.end());
        assert_eq!(&manifest[start..end], "\"nope.txt\"");
        let resolved = dir.path().join("nope.txt");
        assert!(
            diag.message.contains(&resolved.display().to_string()),
            "{}",
            diag.message
        );
        assert_eq!(loaded.codegen_header, None);
    }

    #[test]
    fn codegen_header_file_that_is_not_utf8_is_mani_011() {
        let dir = TempDir::new("codegen-header-not-utf8");
        dir.write(
            "ridl.toml",
            &format!("{PACKAGE_A}\n[codegen]\nheader-file = \"H.txt\"\n"),
        );
        dir.write("a.typl", "package a\ntype A: integer [0..1]\n");
        fs::write(dir.path().join("H.txt"), [0xffu8, 0xfe]).expect("write the header");
        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["MANI-011"]);
        assert!(
            loaded.diagnostics[0].message.contains("H.txt"),
            "{}",
            loaded.diagnostics[0].message
        );
        assert_eq!(loaded.codegen_header, None);
    }

    #[test]
    fn codegen_header_file_with_a_control_character_is_mani_011() {
        let dir = TempDir::new("codegen-header-control");
        dir.write(
            "ridl.toml",
            &format!("{PACKAGE_A}\n[codegen]\nheader-file = \"H.txt\"\n"),
        );
        dir.write("a.typl", "package a\ntype A: integer [0..1]\n");
        dir.write("H.txt", "A\u{2028}B\u{0}\n");
        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the package loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["MANI-011"]);
        let diag = &loaded.diagnostics[0];
        let manifest = fs::read_to_string(dir.path().join("ridl.toml")).unwrap();
        let start = usize::from(diag.primary.range.start());
        let end = usize::from(diag.primary.range.end());
        assert_eq!(&manifest[start..end], "\"H.txt\"");
        let message = &diag.message;
        assert!(message.contains("control character"), "{message}");
        assert!(message.contains("U+2028"), "{message}");
        assert!(
            message.contains(&dir.path().join("H.txt").display().to_string()),
            "{message}"
        );
        assert_eq!(loaded.codegen_header, None);
    }

    #[test]
    fn codegen_header_file_in_a_member_is_mani_012() {
        let dir = TempDir::new("codegen-header-member");
        dir.write(
            "ridl.toml",
            "[workspace]\nmembers = [\"a\"]\n\n[codegen]\nheader-file = \"H.txt\"\n",
        );
        dir.write("H.txt", "root header\n");
        let member = format!("{PACKAGE_A}\n[codegen]\nheader-file = \"M.txt\"\n");
        dir.write("a/ridl.toml", &member);
        dir.write("a/a.typl", "package a\ntype A: integer [0..1]\n");
        let mut db = RidlDatabase::default();
        let loaded = load_workspace(&mut db, dir.path()).expect("the workspace loads");
        assert_eq!(codes(&loaded.diagnostics), vec!["MANI-012"]);
        let diag = &loaded.diagnostics[0];
        let start = usize::from(diag.primary.range.start());
        let end = usize::from(diag.primary.range.end());
        assert_eq!(&member[start..end], "\"M.txt\"");
        assert_eq!(loaded.codegen_header.as_deref(), Some("root header"));
    }
}