ridl-cli 0.2.0

The `ridl` command-line toolchain: check, build, fmt, lock, diff, lsp, and mcp, over the shared compiler crates.
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
//! The `ridl` toolchain facade — the porcelain layer (concept note §8.1,
//! docs/ROADMAP.md epic E1.13). The cargo/deno-style front door with humane
//! defaults: `PATH` defaults to the current directory.
//!
//! `ridl check` and `ridl build` delegate to the `ridlc` library face;
//! `ridl fmt` runs the `ridl-fmt` formatter over `.typl` files (E1.14). The exit
//! code is 0 clean, 1 on a diagnostic error (or, for `fmt --check`, a file that
//! would change), and 2 on an input/output or usage error.
//!
//! `ridl diff` compares two IR snapshots or source trees through the
//! `ridl-diff` engine (E2.8a). It carries its own exit contract — 0 compatible
//! or identical, 1 breaking, 2 error (concept note §9.1, ADR-0008 decision 9) —
//! and never touches `ridlc`'s source→IR boundary beyond compiling each side.
//!
//! `ridl test` runs the property suite over a workspace (E2.11a): the range
//! self-corpora derived from the E1.18 generators, and satisfiability sampling
//! of every `require` clause. It carries the same 0/1/2 exit contract, with 1
//! reserved for a self-corpus failure or an evaluation error.
//!
//! `ridl baseline` and `ridl check --baseline` are the desk-time half of that
//! engine (E2.9, general form §6.3): `baseline` publishes one `.ir.json`
//! snapshot per package, and `check` compares the workspace against those
//! snapshots and warns (RIDL-407) when an interaction's ordinal moved. Both live
//! here rather than in `ridlc` because reading a workspace-local baseline is not
//! part of the source→IR function the tool qualification argument covers
//! (ADR-0008 decision 9).
//!
//! `ridl lsp` and `ridl mcp` are the two stdio servers this one binary hosts:
//! the language server an editor drives (`ridl-lsp`) and the Model Context
//! Protocol server an agent drives (`ridl-mcp`). Both delegate every behavior
//! to their library and only wire the transport here, so one installed binary
//! serves the editor, the agent, and the command line.
//!
//! `ridl lock` writes a package's `interfaces.lock` (lock design §5): plain, it
//! allocates a number to every interface that has none; with `--rename` or
//! `--retire`, it rewrites one package's entries in place. It lives here
//! beside `ridl baseline` because it reads and writes a file in the workspace
//! that is not a source (`ridlc` gains no `lock` subcommand); the compile it
//! runs first is `ridlc`'s own.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

mod lock;
mod property;

use clap::{Parser, Subcommand};
use ridl_core::diag::{DiagCode, Diagnostic, FileId, Label, Severity, SourceMap, Span, render};
use ridl_core::interface_lock::LockKey;
use ridl_fmt::{FormatOutcome, format};
use ridl_syntax::ast::{AstNode as _, HasName as _, InterfaceMember, Name, SourceFile};
use ridlc::{CliRun, Emit};
use rowan::{TextRange, TextSize};

#[derive(Parser)]
#[command(
    name = "ridl",
    about = "The RIDL toolchain",
    version = env!("RIDL_BUILD_VERSION")
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Type-check a file, package, or workspace (defaults to the current
    /// directory).
    Check {
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Verify remote imports against `ridl.lock` without fetching or
        /// regenerating it (CI mode, ADR-0002 §7).
        #[arg(long)]
        frozen: bool,
        /// Compare the checked workspace against a published baseline — a
        /// directory of `.ir.json` snapshots or one snapshot file — and warn
        /// (RIDL-407) on every interaction whose ordinal moved. Without the
        /// flag, `.ridl/baseline/` at the workspace root is used when it
        /// exists.
        #[arg(long, value_name = "DIR|FILE")]
        baseline: Option<PathBuf>,
        /// Output format for the report: text renders to stderr (the
        /// default); json goes to stdout instead — see the CLI reference
        /// (docs/book/cli-reference.md) for its schema.
        #[arg(long, value_enum, default_value_t = CheckFormat::Text)]
        format: CheckFormat,
    },
    /// Publish the current workspace as a baseline: one `<pkg-name>.ir.json`
    /// snapshot per package, written to `.ridl/baseline/` at the workspace
    /// root.
    Baseline {
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Write the snapshots here instead of `.ridl/baseline/`.
        #[arg(long, value_name = "DIR")]
        out: Option<PathBuf>,
    },
    /// Compile to the selected artifacts (defaults to the current directory).
    Build {
        #[arg(default_value = ".")]
        path: PathBuf,
        #[arg(long, default_value = "out")]
        out_dir: PathBuf,
        #[arg(long, value_delimiter = ',', default_value = "rust")]
        emit: Vec<Emit>,
        /// Verify remote imports against `ridl.lock` without fetching or
        /// regenerating it (CI mode, ADR-0002 §7).
        #[arg(long)]
        frozen: bool,
    },
    /// Run the property suite over a workspace: the range self-corpora and the
    /// contract-clause sampling (ridl §13). Exit 0 when every run passes, 1 on
    /// a self-corpus failure or an evaluation error, 2 on a compile error.
    Test {
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Random parameter tuples drawn per `require` clause (minimum 1). Each
        /// clause also runs its parameters' boundary corpus, which is drawn
        /// first and is not counted here, so the total per clause is larger.
        #[arg(long, default_value_t = 256)]
        samples: usize,
        /// Output format for the report.
        #[arg(long, value_enum, default_value = "text")]
        format: property::TestFormat,
    },
    /// Reformat `.typl`, `.ridl` and `.rsdl` files in place (defaults to the
    /// current directory).
    Fmt {
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Do not write; exit 1 if any file would change.
        #[arg(long)]
        check: bool,
    },
    /// Compare two IR snapshots or source trees and classify the change:
    /// exit 0 compatible or identical, 1 breaking, 2 error.
    Diff {
        /// The baseline: an `.ir.json` snapshot, a `.typl`/`.ridl` file, a
        /// package directory, or a workspace root.
        old: Option<PathBuf>,
        /// The candidate, in the same forms as the baseline.
        new: Option<PathBuf>,
        /// Output format for the report.
        #[arg(long, value_enum, default_value = "text")]
        format: DiffFormat,
        /// Print the classification rule for one change category and exit,
        /// instead of comparing snapshots. Takes a category exactly as the
        /// report prints it, e.g. `timing_changed`.
        #[arg(long, value_name = "CATEGORY")]
        explain: Option<String>,
    },
    /// Allocate a number to every interface that has none and write each
    /// package's `interfaces.lock`; with `--rename` or `--retire`, rewrite one
    /// package's entries in place instead. Exit 0 when the file is written or
    /// nothing changes, 1 on a diagnostic error, 2 on a bad flag or a path or
    /// I/O failure. `ridl lock merge` is the git merge driver for the file.
    #[command(args_conflicts_with_subcommands = true)]
    Lock {
        /// A package directory, a workspace root, or a file. A directory
        /// named `merge` is spelled `./merge`, since the bare word is the
        /// subcommand.
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Rewrite the live entry OLD to hold the key NEW, keeping its number
        /// (repeatable). NEW must be a declaration without an entry.
        #[arg(long, value_name = "OLD=NEW")]
        rename: Vec<String>,
        /// Mark the live entry NAME retired, keeping its line and its number
        /// (repeatable). NAME must no longer be declared.
        #[arg(long, value_name = "NAME")]
        retire: Vec<String>,
        #[command(subcommand)]
        sub: Option<LockCommand>,
    },
    /// Run the language server over stdio: exit 0 on a clean shutdown, 2 on a
    /// transport error. Editors spawn this; it takes no flag of its own.
    Lsp,
    /// Run the MCP server over stdio for an agent host: exit 0 on a clean
    /// shutdown, 2 on a transport error. It takes no flag of its own.
    Mcp,
}

/// The subcommands of `ridl lock`.
#[derive(Subcommand)]
enum LockCommand {
    /// The git merge driver for `interfaces.lock`: a three-way merge over
    /// entries matched by number, written to OURS. Exit 0 when the merge is
    /// clean, 1 when entries disagree (they are left between conflict markers
    /// of MARKER_SIZE, and the file is RIDL-410 until resolved), 2 when an
    /// input cannot be read or does not parse (OURS is left as it was).
    /// Register it with `.gitattributes` and `git config` as the CLI
    /// reference documents.
    Merge {
        /// The common ancestor's file (`%O`); an empty file reads as `next 1`.
        base: PathBuf,
        /// The current branch's file (`%A`); the result is written here.
        ours: PathBuf,
        /// The other branch's file (`%B`).
        theirs: PathBuf,
        /// The length of a conflict marker line (`%L`, 7 by default).
        #[arg(value_parser = clap::value_parser!(u16).range(1..))]
        marker_size: u16,
    },
}

/// The `ridl diff` output format — human-readable text or machine-readable
/// JSON with a stable schema.
#[derive(Clone, Copy, Debug, clap::ValueEnum)]
enum DiffFormat {
    Text,
    Json,
}

/// The `ridl check` output format.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
enum CheckFormat {
    Text,
    Json,
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    match cli.command {
        Command::Check {
            path,
            frozen,
            baseline,
            format,
        } => run_check(&path, frozen, baseline.as_deref(), format),
        Command::Baseline { path, out } => run_baseline(&path, out.as_deref()),
        Command::Build {
            path,
            out_dir,
            emit,
            frozen,
        } => finish(ridlc::run_build(&path, &out_dir, &emit, frozen.into())),
        Command::Test {
            path,
            samples,
            format,
        } => property::run(&path, samples, format),
        Command::Fmt { path, check } => run_fmt(&path, check),
        Command::Diff {
            old,
            new,
            format,
            explain,
        } => match explain {
            Some(category) => run_explain(&category),
            None => match (old, new) {
                (Some(old), Some(new)) => run_diff(&old, &new, format),
                _ => {
                    eprintln!(
                        "error: `ridl diff` needs both an old and a new input, \
                         or `--explain <CATEGORY>`"
                    );
                    ExitCode::from(2)
                }
            },
        },
        Command::Lock {
            sub:
                Some(LockCommand::Merge {
                    base,
                    ours,
                    theirs,
                    marker_size,
                }),
            ..
        } => lock::run_lock_merge(&base, &ours, &theirs, usize::from(marker_size)),
        Command::Lock {
            path,
            rename,
            retire,
            sub: None,
        } => lock::run_lock(&path, &rename, &retire),
        Command::Lsp => run_lsp(),
        Command::Mcp => run_mcp(),
    }
}

/// `ridl lsp`: the language server over stdio. Every behavior lives in
/// `ridl-lsp`; this wires the transport and maps the outcome onto the exit
/// codes of ADR-0010 decision 1 — 0 when the client shut the server down, 2
/// when the transport failed or ended before the handshake, which is the tool
/// being unable to answer rather than a negative answer.
fn run_lsp() -> ExitCode {
    let (connection, io_threads) = lsp_server::Connection::stdio();
    if let Err(err) =
        ridl_lsp::server::run_with_version(connection, Some(env!("RIDL_BUILD_VERSION")))
    {
        eprintln!("error: {err}");
        return ExitCode::from(2);
    }
    if let Err(err) = io_threads.join() {
        eprintln!("error: {err}");
        return ExitCode::from(2);
    }
    ExitCode::SUCCESS
}

/// `ridl mcp`: the Model Context Protocol server over stdio. `rmcp` is async,
/// so this builds the only Tokio runtime the binary ever has — no other
/// subcommand is async, and none pays for this one.
fn run_mcp() -> ExitCode {
    let runtime = match tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
    {
        Ok(runtime) => runtime,
        Err(err) => {
            eprintln!("error: {err}");
            return ExitCode::from(2);
        }
    };
    match runtime.block_on(ridl_mcp::serve_stdio_with_version(Some(env!(
        "RIDL_BUILD_VERSION"
    )))) {
        Ok(()) => ExitCode::SUCCESS,
        Err(err) => {
            eprintln!("error: {err}");
            ExitCode::from(2)
        }
    }
}

/// Prints the classification rule for one change category — the table of
/// ADR-0008 decision 14 as text, and the CI-facing documentation of record until
/// the E4 error index publishes it. An unknown category is a usage error: exit 2
/// with the valid words listed.
fn run_explain(category: &str) -> ExitCode {
    match ridl_diff::category_from_word(category) {
        Some(category) => {
            println!("{}", ridl_diff::category_word(category));
            println!("{}", ridl_diff::explain(category));
            ExitCode::SUCCESS
        }
        None => {
            eprintln!("error: unknown change category `{category}`");
            eprintln!("the categories `ridl diff` reports are:");
            for known in ridl_diff::CATEGORIES {
                eprintln!("  {}", ridl_diff::category_word(known));
            }
            ExitCode::from(2)
        }
    }
}

/// Compares the `old` and `new` inputs and renders the report to stdout,
/// returning the diff exit code: 2 on an I/O or compile error while loading
/// either side, 1 when the change is breaking, 0 when it is compatible or the
/// two are identical.
fn run_diff(old: &Path, new: &Path, format: DiffFormat) -> ExitCode {
    let old_side = match load_diff_side(old) {
        Ok(side) => side,
        Err(code) => return code,
    };
    let new_side = match load_diff_side(new) {
        Ok(side) => side,
        Err(code) => return code,
    };

    // The verdict is the contracts' alone: the system's placement and
    // composition changes are listed under their headings with no verdict
    // (rsdl reference §14).
    let report = ridl_diff::diff_workspaces(
        &old_side.packages,
        old_side.system.as_ref(),
        &new_side.packages,
        new_side.system.as_ref(),
    );
    // `render_text` already terminates every line, so it prints as is; the JSON
    // rendering has no trailing newline and gets one.
    match format {
        DiffFormat::Text => print!("{}", ridl_diff::render_text(&report)),
        DiffFormat::Json => println!("{}", ridl_diff::render_json(&report)),
    }

    match report.verdict {
        ridl_diff::Verdict::Breaking => ExitCode::FAILURE,
        ridl_diff::Verdict::Compatible | ridl_diff::Verdict::Identical => ExitCode::SUCCESS,
    }
}

/// One side of a diff: its resolved packages, and its lowered system when the
/// side carries one (rsdl reference §13).
struct DiffSide {
    packages: Vec<ridl_ir::v2::Package>,
    system: Option<ridl_ir::v2::System>,
}

/// Loads one side of a diff into a set of resolved packages and, when the side
/// carries one, its lowered system.
///
/// Three input forms, in order:
///
/// 1. an `.ir.json` file — deserialized directly;
/// 2. a directory holding `.ir.json` files — deserialized as a snapshot set.
///    This is the form `.ridl/baseline/` takes, and an N-package workspace
///    publishes N snapshots, so `ridl diff .ridl/baseline .` has to read the
///    whole directory. Falling through to a compile here would silently diff
///    the current source against itself and always report `identical`
///    (ADR-0008 decision 14: `ridl diff` reads the workspace-local baseline);
/// 3. anything else — a source file, a package directory, or a workspace
///    root — compiled in process through `ridlc::compile_workspace`.
///
/// Only IR artifacts are recognised by name — the suffix table (issue #218
/// item 4). Three inputs are refused rather than parsed as source: a file in
/// a non-JSON IR encoding; a directory that holds IR artifacts but neither an
/// `.ir.json` snapshot nor source — no `ridl.toml` and no `.typl`/`.ridl`
/// file directly inside it; and a directory with no source whose `.ir.json`
/// snapshots sit one level below it rather than inside it, which is a path
/// aimed one level too high (issue #230). Everything else is source.
/// Recognising *source*
/// by extension was tried and reverted — it refused inputs the compiler
/// accepts, such as a `ridl.toml` path designating its workspace, an
/// extensionless source file, or a symlink — so a renamed artifact whose
/// name lost the `.ir.` infix still falls through to the compiler (recorded
/// on issue #218).
///
/// A read, parse, or compile error renders to stderr and yields exit code 2 —
/// `ridl diff` never emits a diff report over a snapshot it could not build.
///
/// Only a source input carries a system, the one the compile lowered: a
/// snapshot is a package snapshot, and `ridl baseline` publishes no system.
fn load_diff_side(entry: &Path) -> Result<DiffSide, ExitCode> {
    if is_ir_json(entry) {
        return Ok(DiffSide {
            packages: load_snapshots(&[entry.to_path_buf()], None)?,
            system: None,
        });
    }

    // The other IR encodings are refused by name, before the source
    // fallback below can parse prototext or binary as `.typl` and report its
    // syntax errors — a misdiagnosis of the actual mistake.
    if is_non_json_ir(entry) {
        eprintln!(
            "error: {}: `ridl diff` compares `.ir.json` snapshots only (ADR-0014 decision 5); \
             emit the package with `--emit ir-json` to compare it",
            entry.display()
        );
        return Err(ExitCode::from(2));
    }

    if entry.is_dir() {
        let snapshots = snapshot_files(entry)?;
        if !snapshots.is_empty() {
            return Ok(DiffSide {
                packages: load_snapshots(&snapshots, None)?,
                system: None,
            });
        }
        // Two directory shapes are described rather than compiled: one
        // holding IR artifacts and no `.ir.json` — a snapshot directory in an
        // encoding this surface refuses, `ridl diff out/ src/` after `--emit
        // ir-text` (issue #218 item 4) — and one whose `.ir.json` snapshots
        // sit a level below it, a path aimed one level too high (issue #230).
        // The second failed open: the directory fell through to the compiler,
        // which walked up to the workspace's own manifest and compiled the
        // current source as the baseline side, so the gate reported
        // `identical` over a breaking change.
        //
        // Neither applies to a source tree. A build can write its artifacts
        // into the workspace itself (`--out-dir .`) and a workspace can
        // publish its baseline inside itself (`--out ws/published`); such a
        // tree compiles below exactly as `ridl check` reads it, artifacts and
        // snapshots included.
        if !is_source_dir(entry) {
            if let Some(witness) = first_non_json_ir_in(entry) {
                return Err(refuse_artifact_directory(
                    entry,
                    &witness,
                    "`ridl diff` compares `.ir.json` snapshots only (ADR-0014 decision 5); emit \
                     the packages with `--emit ir-json` to compare them",
                ));
            }
            if let Some(nested) = first_nested_snapshot_dir(entry)? {
                return Err(refuse_nested_snapshot_directory(
                    entry,
                    &nested,
                    &format!("compare `{}` instead", nested.display()),
                ));
            }
        }
    }

    let mut db = ridl_core::RidlDatabase::default();
    match ridlc::compile_workspace(&mut db, entry) {
        Ok(output) => {
            if output
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.severity == ridl_core::diag::Severity::Error)
            {
                eprint!("{}", render(&output.diagnostics, &output.sources));
                return Err(ExitCode::from(2));
            }
            Ok(DiffSide {
                packages: output
                    .checked
                    .into_iter()
                    .map(|checked| checked.ir)
                    .collect(),
                system: output.system,
            })
        }
        Err(err) => {
            eprintln!("error: {}: {err}", entry.display());
            Err(ExitCode::from(2))
        }
    }
}

/// The one snapshot suffix this surface accepts — baselines and diffs stay
/// `.ir.json` (ADR-0014 decision 5). Drawn from the emit table in `ridlc`
/// rather than spelled here, so the recognition cannot drift from the name
/// the artifact writer uses (issue #218 item 4).
const IR_JSON_SUFFIX: &str = match Emit::IrJson.ir_dump_suffix() {
    Some(suffix) => suffix,
    None => panic!("`ir-json` is an IR dump"),
};

/// Whether `path` is an `.ir.json` snapshot (a file whose name ends
/// [`IR_JSON_SUFFIX`]) rather than a source input.
fn is_ir_json(path: &Path) -> bool {
    path.is_file()
        && path
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| name.ends_with(IR_JSON_SUFFIX))
}

/// Whether `path` is an IR artifact in an encoding the snapshot surface must
/// refuse: every suffix the emit table names except `.ir.json` — prototext
/// (`.ir.txtpb`) and binary (`.ir.binpb`) today. Baselines and diffs stay
/// `.ir.json` (ADR-0014 decision 5) — a committed baseline must be
/// reviewable in a pull request. The suffixes are iterated from the table
/// rather than spelled here, so an encoding added to `ridlc` is refused by
/// name with no edit on this side (issue #218 item 4).
fn is_non_json_ir(path: &Path) -> bool {
    path.is_file()
        && path
            .file_name()
            .and_then(|name| name.to_str())
            .is_some_and(|name| {
                Emit::ir_dump_suffixes()
                    .any(|(emit, suffix)| emit != Emit::IrJson && name.ends_with(suffix))
            })
}

/// Whether `path` is a source file by the rule the workspace loader collects
/// with: a file whose extension is `typl`, `ridl` or `rsdl`. Used only to tell
/// a source tree from a snapshot directory ([`is_source_dir`]) — a diff
/// *argument* is never gated on this, because a source file's own name is
/// unconstrained ([`load_diff_side`]).
fn is_source_file(path: &Path) -> bool {
    path.is_file()
        && path.extension().is_some_and(|extension| {
            extension == "typl" || extension == "ridl" || extension == "rsdl"
        })
}

/// Whether `dir` is a source tree by its direct contents: it holds a
/// `ridl.toml` or at least one `.typl`, `.ridl` or `.rsdl` file. A snapshot
/// directory — `.ridl/baseline/`, or a build `--out-dir` — holds neither.
fn is_source_dir(dir: &Path) -> bool {
    dir.join("ridl.toml").is_file()
        || files_matching(dir, is_source_file).is_ok_and(|files| !files.is_empty())
}

// ==========================================================================
// The baseline-aware desk check (E2.9, general form §6.3, ADR-0008 decision 9)
// ==========================================================================

/// The change categories the desk check reports: the four that move a live
/// interaction's ordinal, and no others.
///
/// General form §6.3 asks for one thing at the desk — a reorder or an insertion
/// caught before CI, because declaration order is wire identity and a reorder
/// looks like tidying. The other breaking categories (a payload type change, a
/// narrowed constraint, a timing change) are already loud in review and stay
/// `ridl diff`'s job in CI: this is the §6.3 mitigation, not a second diff
/// gate. A service's list is a set (ADR-0015 decision 19 as amended on
/// 2026-09-15): its order is not an identity, so no service-level category
/// belongs here.
///
/// All four classify [`Breaking`](ridl_diff::Verdict::Breaking) in every
/// direction, so the category alone selects them.
const ORDINAL_CATEGORIES: [ridl_diff::Category; 4] = [
    ridl_diff::Category::InteractionInserted,
    ridl_diff::Category::InteractionReordered,
    ridl_diff::Category::InteractionRemoved,
    ridl_diff::Category::ReservedNameRedeclared,
];

/// Runs `check` and, when a baseline is available and the compile produced no
/// error other than RIDL-409, the desk check on top of it.
///
/// The desk check only ever *adds* to the diagnostics — RIDL-407 warnings,
/// and the rename label on a RIDL-409 (lock design §4) — so `ridl check`
/// keeps its 0/1/2 exit contract: a reordered but otherwise clean workspace
/// still exits 0, and a workspace with an orphan lock entry still exits 1. It
/// is skipped entirely when the compile produced any other error — a diff
/// against IR that failed to check would report noise on top of the real
/// problem — while RIDL-409 stops nothing in lowering (an entry with no
/// declaration has nothing to lower), so the IR it runs over is whole.
fn run_check(path: &Path, frozen: bool, baseline: Option<&Path>, format: CheckFormat) -> ExitCode {
    let mut run = match ridlc::run_check(path, frozen.into()) {
        Ok(run) => run,
        Err(err) => {
            eprintln!("error: {err}");
            return ExitCode::from(2);
        }
    };

    if lock::only_lock_orphans(&run.diagnostics) {
        match baseline_location(path, baseline) {
            Ok(Some(location)) => {
                if let Err(code) = desk_check(path, &location, baseline.is_some(), &mut run) {
                    return code;
                }
            }
            Ok(None) => {}
            Err(code) => return code,
        }
    }

    finish_check(run, format)
}

/// Publishes the workspace at `path` as a baseline.
///
/// The compile and the write are `ridlc`'s own `build --emit ir-json`, so the
/// snapshot a desk compares against is byte for byte the snapshot CI compares
/// against. One `.ir.json` holds exactly one package, so an N-package workspace
/// writes N files, one per package name; `ridl check` matches them back up by
/// the package name inside each file, never by file name.
///
/// The baseline is regenerated **wholesale**: the published directory ends up
/// holding exactly the packages the workspace declares now, so renaming a
/// package leaves no snapshot behind under the old name. Publishing goes
/// through a staging directory to get that without risking the opposite
/// failure — clearing the directory up front would destroy a good baseline
/// whenever the workspace happens not to compile.
fn run_baseline(path: &Path, out: Option<&Path>) -> ExitCode {
    let out_dir = out
        .map(Path::to_path_buf)
        .unwrap_or_else(|| default_baseline_dir(path));
    let staging = staging_dir(&out_dir);
    let _ = std::fs::remove_dir_all(&staging);

    let mut run = match ridlc::run_build(path, &staging, &[Emit::IrJson], false.into()) {
        Ok(run) => run,
        Err(err) => {
            let _ = std::fs::remove_dir_all(&staging);
            eprintln!("error: {err}");
            return ExitCode::from(2);
        }
    };

    // An error-bearing run publishes nothing, and the existing baseline stays
    // exactly as it was. The staging directory is discarded rather than left:
    // `ridlc` gates every emit on a clean compile except for an RSDL-7xx error,
    // which writes every artifact and still reports the error (rsdl reference
    // §13), so a staging directory may hold artifacts here.
    if run.has_error() {
        let _ = std::fs::remove_dir_all(&staging);
        return finish(Ok(run));
    }

    // The published baseline is the only record that a removed interaction's
    // ordinal was ever taken. Replacing it with a snapshot that drops the
    // interaction with no `reserved` tombstone destroys that record, and a
    // later append then reuses the ordinal with nothing to compare against.
    // The comparison happens here, against the directory publication is about
    // to overwrite (driftsys/ridl#315). The interface level is the lock's:
    // `interface_refusals` refuses a provisional interface number and a
    // published number the fresh snapshot neither carries nor retires (lock
    // design §8). Both gates run, so one run reports every refusal.
    let mut refused = false;
    for gate in [untombstoned_removals, interface_refusals] {
        match gate(path, &out_dir, &staging, &mut run) {
            Ok(hit) => refused |= hit,
            Err(code) => {
                let _ = std::fs::remove_dir_all(&staging);
                return code;
            }
        }
    }
    if refused {
        let _ = std::fs::remove_dir_all(&staging);
        return finish(Ok(run));
    }

    if let Err(err) = publish_baseline(&staging, &out_dir) {
        let _ = std::fs::remove_dir_all(&staging);
        eprintln!(
            "error: cannot publish the baseline to {}: {err}",
            out_dir.display()
        );
        return ExitCode::from(2);
    }

    finish(Ok(run))
}

/// Compares the baseline about to be replaced against the snapshots just built
/// and records a RIDL-408 for every interaction the replacement would drop with
/// no `reserved` tombstone in its own slot, and for every live interaction the
/// replacement declares under a name the baseline retires. Returns whether any
/// was recorded.
///
/// The published snapshots are read flat from `out_dir`, which is exactly where
/// [`publish_baseline`] writes them. This deliberately does not go through
/// [`load_baseline`], whose discovery rules exist to interpret a user-supplied
/// `--baseline` path: inheriting them would let the comparison become a
/// comparison against nothing in the cases driftsys/ridl#235 describes, and a
/// gate that a directory layout can defeat is not a gate.
///
/// Only the interaction level is covered. The interface level is the lock's:
/// an interface's identity is its number in `interfaces.lock`, not a slot in
/// a service's list, so a removed or renumbered interface is refused by the
/// lock's own publication rules, not here. `ReservedNameRedeclared` is an
/// interaction-level category, refused when the published IR holds a
/// tombstone for the name.
fn untombstoned_removals(
    entry: &Path,
    out_dir: &Path,
    staging: &Path,
    run: &mut CliRun,
) -> Result<bool, ExitCode> {
    if !out_dir.is_dir() {
        return Ok(false);
    }
    let published = load_snapshots(&snapshot_files(out_dir)?, Some(PUBLISHED_PARSE_REMEDY))?;
    if published.is_empty() {
        return Ok(false);
    }
    let fresh = load_snapshots(&snapshot_files(staging)?, None)?;

    let report = ridl_diff::diff_sets(&published, &fresh);
    // Parsing every source file is wasted work on the common republish that
    // carries no refused change at all, so the index is built only once the
    // first one is actually met.
    let mut index: Option<DeclIndex> = None;
    let mut refusals = Vec::new();
    for change in &report.changes {
        let refused = match change.category {
            ridl_diff::Category::InteractionRemoved => true,
            ridl_diff::Category::ReservedNameRedeclared => {
                published_reserves(&published, &change.path)
            }
            _ => false,
        };
        if !refused {
            continue;
        }
        let index = index.get_or_insert_with(|| DeclIndex::build(entry));
        refusals.push(Diagnostic {
            code: DiagCode::RIDL_408,
            severity: Severity::Error,
            message: untombstoned_removal_message(change, &published),
            primary: index.span_of(&change.path, &mut run.sources),
            labels: Vec::new(),
            fixits: Vec::new(),
        });
    }
    let refused = !refusals.is_empty();
    run.diagnostics.extend(refusals);
    Ok(refused)
}

/// The RIDL-408 message for one refused change, worded for the shape
/// `ridl_diff::walk`'s `diff_interface` emitted it in:
///
/// - a **redeclared name** is the one `ReservedNameRedeclared` shape the gate
///   refuses, told apart by its category;
/// - a **misplaced tombstone** — the source retires the interaction, but not
///   at its own ordinal — is told apart by `change.after`, which only this
///   `InteractionRemoved` shape carries (the tombstone's own ordinal);
/// - a **bare removal** and a **dropped tombstone** both carry no
///   `change.after`, so they are told apart by asking the published IR
///   itself whether it already reserved the name — never by reading the
///   words in `change.before`, which is display text `ridl_diff` owns and may
///   reword.
///
/// The ordinal each message names is read from the published IR too
/// ([`published_ordinal`]), for the same reason. The shape and the name come
/// from the diff path through [`shape_and_name`], as RIDL-407's do, so two
/// interfaces removing the same name draw two distinct messages.
fn untombstoned_removal_message(
    change: &ridl_diff::Change,
    published: &[ridl_ir::v2::Package],
) -> String {
    let (shape, name) = shape_and_name(&change.path);
    let in_shape = shape.map_or(String::new(), |shape| format!(" in `{shape}`"));
    let ordinal = published_ordinal(published, &change.path);
    let held = ordinal.map_or(String::new(), |ordinal| format!(" (ordinal {ordinal})"));
    let slot = ordinal.map_or("that ordinal".to_string(), |ordinal| {
        format!("ordinal {ordinal}")
    });
    if change.category == ridl_diff::Category::ReservedNameRedeclared {
        format!(
            "`{name}` is declared again{in_shape}, but the baseline being replaced retires that \
             name with `reserved`{held}. A tombstone is a permanent reservation (ridl §11): a \
             consumer still holding the old contract would read the new interaction as the \
             retired one. Give the new interaction a different name and keep `reserved {name}` \
             at {slot}."
        )
    } else if change.after.is_some() {
        format!(
            "The source retires `{name}`{in_shape} with a tombstone, but not at the ordinal the \
             interaction held{held}. A tombstone must hold the retired interaction's own ordinal \
             (ridl §11); otherwise the surviving interactions slide into the freed slot. Move \
             `reserved {name}` to {slot}."
        )
    } else if published_reserves(published, &change.path) {
        format!(
            "The baseline being replaced records `{name}`{in_shape} as retired{held}, but the \
             source has dropped the tombstone. A tombstone is a permanent reservation (ridl \
             §11). Put `reserved {name}` back at {slot}."
        )
    } else {
        format!(
            "`{name}` is gone from the source but the baseline being replaced still declares \
             it{in_shape}{held}. Publishing would free its ordinal for a later interaction to \
             reuse, with nothing left to record that it was ever taken. Retire it in place with \
             `reserved {name}`."
        )
    }
}

/// The interaction a `<package>/<container>/<name>` diff path names, as the
/// published IR declares it: the live declaration, or the `reserved <name>`
/// tombstone that retires it.
///
/// This reads the same shape `ridl_diff`'s own `live_interactions` and
/// `reserved_names` walks read (`Interface::interactions`, a `Decl` whose
/// `kind` says whether it is a `ReservedSlot`), so nothing the gate says about
/// the published side depends on the wording of a `Change`'s rendered
/// `before`/`after` text. The container is found through `Package::shapes`,
/// which yields a top-level interface and an inline-form service's own shape
/// alike — the two containers `ridl_diff`'s interaction walk is ever called
/// on. A named-form service is not a shape, so a service-level diff path
/// finds nothing here.
fn published_interaction<'a>(
    published: &'a [ridl_ir::v2::Package],
    path: &str,
) -> Option<&'a ridl_ir::v2::Decl> {
    let mut parts = path.split('/');
    let (Some(pkg), Some(container), Some(name)) = (parts.next(), parts.next(), parts.next())
    else {
        return None;
    };
    let package = published.iter().find(|package| package.name == pkg)?;
    let shape = package.shapes().find(|shape| shape.name == container)?;
    shape
        .interface
        .interactions
        .iter()
        .find(|decl| match &decl.kind {
            Some(ridl_ir::v2::decl::Kind::ReservedSlot(reserved)) => {
                reserved.name.as_deref() == Some(name)
            }
            Some(_) => decl.name == name,
            None => false,
        })
}

/// Whether the published IR already retires the interaction a diff path names
/// — a `reserved <name>` tombstone already present in the baseline being
/// replaced.
fn published_reserves(published: &[ridl_ir::v2::Package], path: &str) -> bool {
    published_interaction(published, path)
        .is_some_and(|decl| matches!(&decl.kind, Some(ridl_ir::v2::decl::Kind::ReservedSlot(_))))
}

/// The ordinal the interaction a diff path names holds in the published IR,
/// live or retired — the slot every RIDL-408 remedy tells the author to keep.
fn published_ordinal(published: &[ridl_ir::v2::Package], path: &str) -> Option<u32> {
    published_interaction(published, path).map(|decl| decl.ordinal)
}

/// The interface level of the publication gate — the lock's own rules (lock
/// design §8; the design's §4 table, `ridl baseline` column): a RIDL-411 for
/// every interface in the fresh snapshots whose number is provisional, and a
/// RIDL-412 for every interface the baseline being replaced holds under a
/// non-zero number that the fresh snapshots neither carry nor retire. Returns
/// whether any was recorded.
///
/// RIDL-411 reads the fresh snapshots alone, so a first publication is
/// refused too: a provisional number is no identity, and a snapshot holding
/// one records nothing a later comparison can hold the interface to. RIDL-412
/// reads the same `diff_sets` report the RIDL-408 gate walks, keeping the
/// interface-level `DeclRemoved` changes: `ridl_diff` matches interfaces by
/// number, so such a change is a number the fresh side carries under no name
/// and does not list as retired. A published `number` 0 predates the lock and
/// was matched by name, so its removal is not refused (plan decision PD-9). In
/// practice RIDL-412 is a lock line deleted by hand: a live entry with no
/// declaration fails the build with RIDL-409 before publication.
///
/// The published snapshots are read flat from `out_dir`, as
/// [`untombstoned_removals`] reads them and for the same reason.
fn interface_refusals(
    entry: &Path,
    out_dir: &Path,
    staging: &Path,
    run: &mut CliRun,
) -> Result<bool, ExitCode> {
    let fresh = load_snapshots(&snapshot_files(staging)?, None)?;
    let mut index: Option<DeclIndex> = None;
    let mut refusals = Vec::new();
    for package in &fresh {
        for shape in package.shapes() {
            if !shape.interface.provisional {
                continue;
            }
            let index = index.get_or_insert_with(|| DeclIndex::build(entry));
            refusals.push(Diagnostic {
                code: DiagCode::RIDL_411,
                severity: Severity::Error,
                message: provisional_number_message(&package.name, &shape, entry),
                primary: index.shape_span(&package.name, shape.name, &mut run.sources),
                labels: Vec::new(),
                fixits: Vec::new(),
            });
        }
    }

    if out_dir.is_dir() {
        let published = load_snapshots(&snapshot_files(out_dir)?, Some(PUBLISHED_PARSE_REMEDY))?;
        if !published.is_empty() {
            let report = ridl_diff::diff_sets(&published, &fresh);
            for change in &report.changes {
                let Some((package, shape)) = dropped_number(change, &published, &fresh) else {
                    continue;
                };
                refusals.push(Diagnostic {
                    code: DiagCode::RIDL_412,
                    severity: Severity::Error,
                    message: dropped_number_message(&package.name, &shape),
                    primary: detached_span(),
                    labels: Vec::new(),
                    fixits: Vec::new(),
                });
            }
        }
    }

    let refused = !refusals.is_empty();
    run.diagnostics.extend(refusals);
    Ok(refused)
}

/// The RIDL-411 message: the lock key the entry would carry, the provisional
/// number the checker showed, and the command that records it.
fn provisional_number_message(
    package: &str,
    shape: &ridl_ir::v2::InterfaceShape<'_>,
    entry: &Path,
) -> String {
    let key = lock::shape_key(shape);
    format!(
        "`{key}` has a provisional interface number ({}) in package `{package}`: no entry in \
         `interfaces.lock` records it, and a provisional number is no identity. Run `ridl lock \
         {}` to allocate and record the number, then publish.",
        shape.interface.number,
        entry.display()
    )
}

/// The published shape an interface-level `DeclRemoved` names, when the
/// number it held is one the lock allocated (not 0) and the fresh package
/// does not retire — the RIDL-412 shape. An interface-level change has a
/// two-segment path and the walk's `interface` marker as its `before`; a
/// service's own `DeclRemoved` carries `service` there, and a package's has
/// one segment.
fn dropped_number<'a>(
    change: &ridl_diff::Change,
    published: &'a [ridl_ir::v2::Package],
    fresh: &[ridl_ir::v2::Package],
) -> Option<(&'a ridl_ir::v2::Package, ridl_ir::v2::InterfaceShape<'a>)> {
    if change.category != ridl_diff::Category::DeclRemoved
        || change.before.as_deref() != Some("interface")
    {
        return None;
    }
    let mut parts = change.path.split('/');
    let (Some(pkg), Some(name), None) = (parts.next(), parts.next(), parts.next()) else {
        return None;
    };
    let package = published.iter().find(|package| package.name == pkg)?;
    let shape = package.shapes().find(|shape| shape.name == name)?;
    let number = shape.interface.number;
    if number == 0 {
        return None;
    }
    let retired = fresh
        .iter()
        .find(|package| package.name == pkg)
        .is_some_and(|package| package.retired.iter().any(|entry| entry.number == number));
    (!retired).then_some((package, shape))
}

/// The RIDL-412 message: the name and number the baseline holds, and the
/// line that restores the record.
fn dropped_number_message(package: &str, shape: &ridl_ir::v2::InterfaceShape<'_>) -> String {
    let key = lock::shape_key(shape);
    let number = shape.interface.number;
    format!(
        "`{key}` holds interface number {number} in the baseline being replaced, in package \
         `{package}`, but the fresh snapshot neither declares that number nor retires it. \
         Publishing would lose the only record that the number was allocated, and `next` could \
         hand it to a later interface. Restore the line `{key} {number}` in the package's \
         `interfaces.lock` from version control — `{key} {number} retired` when the interface is \
         gone."
    )
}

/// The directory the snapshots are built into before they are published: a
/// hidden sibling of `out_dir`, so the move into place is a rename within one
/// filesystem.
fn staging_dir(out_dir: &Path) -> PathBuf {
    let name = out_dir
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("baseline");
    out_dir
        .parent()
        .unwrap_or(Path::new("."))
        .join(format!(".{name}.staging"))
}

/// Replaces the `.ir.json` set in `out_dir` with the freshly built one in
/// `staging`, dropping any snapshot whose package the workspace no longer
/// declares. Only `.ir.json` files are touched: `out_dir` may be a directory a
/// user pointed `--out` at, and nothing else in it is this command's to delete.
///
/// The fresh snapshots move in first, each rename replacing the stale file of
/// the same name, and only then are the stale snapshots no fresh one replaced
/// removed. A failure part-way — a rename refused, a disk that fills — leaves
/// `out_dir` holding one snapshot per package, some fresh and some stale,
/// which the next run compares against package by package. The other order,
/// delete then move, left `out_dir` empty after the same failure, and an
/// empty directory is a first publication to [`untombstoned_removals`]: the
/// next run would have skipped the gate.
fn publish_baseline(staging: &Path, out_dir: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(out_dir)?;
    let mut published = BTreeSet::new();
    for fresh in ir_json_files(staging)? {
        let name = fresh
            .file_name()
            .expect("a listed snapshot path has a file name")
            .to_os_string();
        std::fs::rename(&fresh, out_dir.join(&name))?;
        published.insert(name);
    }
    for stale in ir_json_files(out_dir)? {
        if stale
            .file_name()
            .is_some_and(|name| !published.contains(name))
        {
            std::fs::remove_file(stale)?;
        }
    }
    std::fs::remove_dir_all(staging)
}

/// Where to read the baseline from, if anywhere.
///
/// An explicit `--baseline` that does not exist is an input error (exit 2) —
/// asking for a baseline that is not there is a mistake worth hearing about.
/// Auto-discovery is the silent path: with no flag and no `.ridl/baseline/`
/// directory, `ridl check` behaves exactly as it did before this command
/// existed.
fn baseline_location(entry: &Path, flag: Option<&Path>) -> Result<Option<PathBuf>, ExitCode> {
    match flag {
        // A prototext or binary IR artifact is refused by name — baselines
        // stay `.ir.json` (ADR-0014 decision 5) — before the snapshot loader
        // can report it as malformed JSON, which misdiagnoses the mistake.
        Some(explicit) if is_non_json_ir(explicit) => {
            eprintln!(
                "error: the baseline `{}` is not an `.ir.json` snapshot: a baseline stays \
                 `.ir.json` (ADR-0014 decision 5); publish one with `ridl baseline`",
                explicit.display()
            );
            Err(ExitCode::from(2))
        }
        Some(explicit) if explicit.exists() => Ok(Some(explicit.to_path_buf())),
        Some(explicit) => {
            eprintln!(
                "error: the baseline `{}` does not exist",
                explicit.display()
            );
            Err(ExitCode::from(2))
        }
        None => {
            let default = default_baseline_dir(entry);
            Ok(default.is_dir().then_some(default))
        }
    }
}

/// `.ridl/baseline/` at the workspace root (ADR-0008 decision 14). The root is
/// the nearest directory at or above `entry` holding a `ridl.toml` — the same
/// root the compile scopes itself to — falling back to `entry`'s own directory
/// when there is no manifest anywhere above it (single-file mode).
fn default_baseline_dir(entry: &Path) -> PathBuf {
    let start = if entry.is_file() {
        entry.parent().unwrap_or(Path::new(".")).to_path_buf()
    } else {
        entry.to_path_buf()
    };
    let mut cursor = start.as_path();
    loop {
        if cursor.join("ridl.toml").is_file() {
            return cursor.join(".ridl").join("baseline");
        }
        match cursor.parent() {
            Some(parent) => cursor = parent,
            None => break,
        }
    }
    start.join(".ridl").join("baseline")
}

/// Compares the checked workspace against the baseline at `location`, appends
/// a RIDL-407 warning for every ordinal-affecting change, and adds the rename
/// label to every RIDL-409 whose orphan entry has exactly one same-shape
/// candidate ([`rename_labels`]).
///
/// The workspace is compiled a second time here, through
/// [`ridlc::compile_workspace`], because `run_check` renders diagnostics but
/// does not hand back the IR. The cost is paid only when a baseline is actually
/// present, and never on a run that failed for anything but RIDL-409.
/// `explicit` — whether
/// `location` came from a `--baseline` flag rather than auto-discovery — is
/// passed straight through to [`load_baseline`], which it uses to tell an
/// explicit `--baseline` holding no snapshot (a refusal) from an
/// auto-discovered directory holding none (a silent skip).
fn desk_check(
    entry: &Path,
    location: &Path,
    explicit: bool,
    run: &mut CliRun,
) -> Result<(), ExitCode> {
    let baseline = load_baseline(location, explicit)?;
    if baseline.is_empty() {
        return Ok(());
    }

    let mut db = ridl_core::RidlDatabase::default();
    let current: Vec<ridl_ir::v2::Package> = match ridlc::compile_workspace(&mut db, entry) {
        Ok(output) => output
            .checked
            .into_iter()
            .map(|checked| checked.ir)
            .collect(),
        Err(err) => {
            eprintln!("error: {}: {err}", entry.display());
            return Err(ExitCode::from(2));
        }
    };

    let report = ridl_diff::diff_sets(&baseline, &current);
    let index = DeclIndex::build(entry);
    let mut warnings = Vec::new();
    for change in &report.changes {
        if !ORDINAL_CATEGORIES.contains(&change.category) {
            continue;
        }
        warnings.push(Diagnostic {
            code: DiagCode::RIDL_407,
            severity: Severity::Warning,
            message: drift_message(change),
            primary: index.span_of(&change.path, &mut run.sources),
            labels: Vec::new(),
            fixits: Vec::new(),
        });
    }
    run.diagnostics.extend(warnings);
    rename_labels(&baseline, &current, &index, run);
    Ok(())
}

/// The rename hint (lock design §4; plan decision PD-5). For every RIDL-409
/// the compile produced, when exactly one declaration without an entry in
/// the same package has the orphan entry's shape in the published baseline,
/// a secondary label goes on that diagnostic, at the candidate's declaration,
/// naming the one `ridl lock <pkg> --rename Old=New`. Nothing otherwise — no
/// baseline package, no candidate of that shape, or several — and never a
/// second diagnostic. The orphan's key is read from the lock line the
/// diagnostic points at (its span is the entry's line, plan decision PD-3),
/// and its package from the lock file's directory through the index.
fn rename_labels(
    baseline: &[ridl_ir::v2::Package],
    current: &[ridl_ir::v2::Package],
    index: &DeclIndex,
    run: &mut CliRun,
) {
    let orphans: Vec<(usize, LockKey, String)> = run
        .diagnostics
        .iter()
        .enumerate()
        .filter(|(_, diagnostic)| diagnostic.code == DiagCode::RIDL_409)
        .filter_map(|(position, diagnostic)| {
            let (key, dir) = orphan_entry(&run.sources, diagnostic)?;
            Some((position, key, dir))
        })
        .collect();
    for (position, old, dir) in orphans {
        let Some(package) = index.package_of_dir(&dir) else {
            continue;
        };
        let Some(published) = baseline
            .iter()
            .find(|candidate| candidate.name == package)
            .and_then(|published| {
                published
                    .shapes()
                    .find(|shape| lock::shape_key(shape) == old)
            })
        else {
            continue;
        };
        let candidates: Vec<ridl_ir::v2::InterfaceShape<'_>> = current
            .iter()
            .find(|candidate| candidate.name == package)
            .map(|fresh| {
                fresh
                    .shapes()
                    .filter(|shape| {
                        shape.interface.provisional
                            && same_shape(published.interface, shape.interface)
                    })
                    .collect()
            })
            .unwrap_or_default();
        let [candidate] = candidates.as_slice() else {
            continue;
        };
        let new = lock::shape_key(candidate);
        let span = index.shape_span(package, candidate.name, &mut run.sources);
        run.diagnostics[position].labels.push(Label {
            span,
            message: format!(
                "same shape as `{old}` in the published baseline: run `ridl lock {dir} --rename \
                 {old}={new}`"
            ),
        });
    }
}

/// The orphan entry a RIDL-409 points at: its key, read from the first field
/// of the lock line under the diagnostic's span, and the package directory —
/// the lock file's parent — as the message names it (plan decision PD-4).
fn orphan_entry(sources: &SourceMap, diagnostic: &Diagnostic) -> Option<(LockKey, String)> {
    let path = sources.path(diagnostic.primary.file)?;
    let text = sources.text(diagnostic.primary.file)?;
    let range = diagnostic.primary.range;
    let line = text.get(usize::from(range.start())..usize::from(range.end()))?;
    let key = line.split(' ').next()?.parse().ok()?;
    Some((key, directory_of(path)))
}

/// Whether two interface bodies are the same shape (lock design §4): their
/// `interactions` lists compare equal once each interaction's `doc`, `labels`
/// and `deprecated` are blanked on both sides. Every other field of an
/// interaction — name, kind, ordinal, payload, timing, parameters, return,
/// contracts, visibility — and every `reserved` tombstone must match. The
/// `Interface`'s own fields — name, visibility, doc, number, provisional flag
/// — are not members and are not compared: the baseline's interface is frozen
/// and the candidate is provisional, so whole values would never match.
fn same_shape(old: &ridl_ir::v2::Interface, new: &ridl_ir::v2::Interface) -> bool {
    fn members(interface: &ridl_ir::v2::Interface) -> Vec<ridl_ir::v2::Decl> {
        interface
            .interactions
            .iter()
            .cloned()
            .map(|mut decl| {
                decl.doc = String::new();
                decl.labels = Vec::new();
                decl.deprecated = None;
                decl
            })
            .collect()
    }
    members(old) == members(new)
}

/// The directory a file path sits in, as a string: its parent, or `.` when
/// the path has none — the form the loader records a package directory in and
/// the RIDL-409 message names it in.
fn directory_of(path: &str) -> String {
    match Path::new(path).parent() {
        Some(dir) if !dir.as_os_str().is_empty() => dir.to_string_lossy().into_owned(),
        _ => ".".to_string(),
    }
}

/// The RIDL-407 message for one ordinal-affecting change.
///
/// Written for the reader of a `.ridl` file, not for a reader of the diff
/// report. It names the interaction and the shape it is declared in — the words
/// in the source — rather than the slash-separated diff path, states the one
/// consequence that makes the warning worth reading (declaration order is the
/// wire identity, ridl §11), and names the edit that keeps the baseline intact.
/// It used to read `interaction ordinal changed against the baseline:
/// fx.audit/Motion/reset (interaction_reordered)`: "ordinal" is an IR word, the
/// path is a diff-report word, `interaction_reordered` is the enum variant's
/// own spelling, and between them they stated neither consequence nor remedy.
fn drift_message(change: &ridl_diff::Change) -> String {
    let (shape, name) = shape_and_name(&change.path);
    // "in `Motion`" when the shape is known, dropped when the path is not the
    // three-segment form every ordinal category emits.
    let in_shape = shape.map_or(String::new(), |shape| format!(" in `{shape}`"));
    match change.category {
        ridl_diff::Category::InteractionReordered => format!(
            "`{name}` has moved{in_shape} since the published baseline{}. Declaration order is \
             the wire identity of an interaction (ridl §11), so a consumer built against the \
             baseline would now bind this slot to a different interaction — put the declarations \
             back in the baseline's order and add new ones at the end",
            baseline_position(change),
        ),
        ridl_diff::Category::InteractionInserted => format!(
            "`{name}` is declared{in_shape} ahead of interactions the published baseline already \
             numbers. An interaction inserted above an existing one shifts every later wire \
             identity (ridl §11) — declare it at the end of the body instead",
        ),
        ridl_diff::Category::InteractionRemoved => format!(
            "`{name}` is gone{in_shape} but the published baseline still declares it. Deleting \
             the line frees its slot and every later interaction slides into a wire identity \
             that is not its own (ridl §11) — retire it in place with `reserved {name}`, which \
             holds the slot for ever",
        ),
        ridl_diff::Category::ReservedNameRedeclared => format!(
            "`{name}` is declared again{in_shape}, and the published baseline retires that name \
             with `reserved`. A retired name is a permanent wire reservation (ridl §11) — a \
             consumer still holding the old contract would read the new interaction as the \
             retired one, so give this interaction a different name",
        ),
        // `ORDINAL_CATEGORIES` is the caller's filter and holds exactly the
        // categories of the arms above. Another category reaching here would
        // be a filter that grew without its messages, so this says only what
        // it can defend — and says it without the raw category token, which
        // is the vocabulary this code exists to keep out of the message.
        _ => format!(
            "`{name}`{in_shape} changed against the published baseline in a way that moves a \
             wire identity (ridl §11)"
        ),
    }
}

/// The shape and interaction name of a `<package>/<shape>/<interaction>` diff
/// path. A path of any other arity yields no shape and its last segment as the
/// name, so the message degrades to naming what it can rather than printing the
/// raw path.
fn shape_and_name(path: &str) -> (Option<&str>, &str) {
    let parts: Vec<&str> = path.split('/').collect();
    match parts.as_slice() {
        [_package, shape, name] => (Some(shape), name),
        _ => (None, parts.last().copied().unwrap_or(path)),
    }
}

/// ` (position 2 there, position 4 here)` for a reorder whose two sides carry
/// two *different* positions, and the empty string otherwise.
///
/// The walk renders a live reorder's sides as bare ordinals (`"2"`) and a
/// tombstone's as `"reserved at ordinal 2"`, so the trailing integer is what
/// the two spellings share.
///
/// The equal case is dropped rather than printed. A reorder is detected on
/// *relative* order among the survivors, so an interaction can change rank
/// while its absolute ordinal stays put — an insertion above it shifts the
/// others past it — and "`doorClosed` has moved (position 3 there, position 3
/// here)" contradicts itself in the same breath. The sentence about relative
/// order stands on its own; the numbers are a convenience that only helps when
/// they differ.
fn baseline_position(change: &ridl_diff::Change) -> String {
    let position = |side: &Option<String>| -> Option<u32> {
        side.as_ref()?
            .rsplit(' ')
            .next()?
            .parse()
            .ok()
            .filter(|slot| *slot > 0)
    };
    match (position(&change.before), position(&change.after)) {
        (Some(was), Some(now)) if was != now => {
            format!(" (position {was} there, position {now} here)")
        }
        _ => String::new(),
    }
}

/// Loads the baseline packages: every `.ir.json` in a directory, in file-name
/// order, or the single file `location` names.
///
/// Three directory shapes are refused rather than read as an *empty*
/// baseline, because skipping any of them silently would report a clean desk
/// check that ran against nothing: one holding IR artifacts but no `.ir.json`
/// (issue #218 item 4), one whose `.ir.json` snapshots sit a level below it
/// (issue #230), and, when `explicit` is true, any other directory that
/// yields no snapshot at all (driftsys/ridl#235). A directory that fits none
/// of the three and was found by auto-discovery (`explicit` false) keeps
/// yielding an empty baseline — that is the ordinary "no baseline published
/// yet" state, and [`desk_check`] skips it silently.
fn load_baseline(location: &Path, explicit: bool) -> Result<Vec<ridl_ir::v2::Package>, ExitCode> {
    let files = if location.is_dir() {
        let snapshots = snapshot_files(location)?;
        if snapshots.is_empty() {
            // What is directly inside is the more specific complaint, so it
            // is the one reported when a directory somehow has both.
            if let Some(witness) = first_non_json_ir_in(location) {
                return Err(refuse_artifact_directory(
                    location,
                    &witness,
                    "a baseline stays `.ir.json` (ADR-0014 decision 5); publish one with \
                     `ridl baseline`",
                ));
            }
            if let Some(nested) = first_nested_snapshot_dir(location)? {
                return Err(refuse_nested_snapshot_directory(
                    location,
                    &nested,
                    &format!("pass `--baseline {}` instead", nested.display()),
                ));
            }
            // The two refusals above name a specific, fixable mistake. This one
            // catches every remaining way a directory yields no snapshot —
            // snapshots two or more levels down, or an empty directory — and
            // refuses rather than comparing against nothing. Auto-discovery is
            // exempt: with no flag, "no baseline published yet" is legitimate.
            if explicit {
                return Err(refuse_empty_baseline(location));
            }
        }
        snapshots
    } else {
        vec![location.to_path_buf()]
    };
    load_snapshots(&files, None)
}

/// An explicit `--baseline` path that holds no snapshot at the depth the loader
/// reads is an input error, not a silent pass. The caller asserted that a
/// baseline is there. A comparison against nothing reports no drift and exits
/// 0, which is indistinguishable from a clean check — the same failure shape
/// ADR-0010 decision 6 closed for `ridl fmt` (driftsys/ridl#235).
///
/// The remedy names the likely mistake first — the path is aimed above the
/// snapshots, which is #235's own case (`--baseline ws` where
/// `ws/.ridl/baseline/` holds them) — and publishing into the named directory
/// second. Offered alone, the second would have `ridl baseline --out ws` write
/// snapshots into the workspace root.
fn refuse_empty_baseline(location: &Path) -> ExitCode {
    eprintln!(
        "error: the baseline `{}` holds no `.ir.json` snapshot directly inside it; point \
         `--baseline` at the directory that holds the snapshots (`ridl baseline` publishes \
         them to `.ridl/baseline/` at the workspace root), or publish a first one there with \
         `ridl baseline --out {}`",
        location.display(),
        location.display(),
    );
    ExitCode::from(2)
}

/// The files directly inside `dir` that satisfy `keep`, in file-name order.
fn files_matching(dir: &Path, keep: fn(&Path) -> bool) -> std::io::Result<Vec<PathBuf>> {
    let mut files: Vec<PathBuf> = std::fs::read_dir(dir)?
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| keep(path))
        .collect();
    files.sort();
    Ok(files)
}

/// The `.ir.json` snapshots directly inside `dir`, in file-name order.
fn ir_json_files(dir: &Path) -> std::io::Result<Vec<PathBuf>> {
    files_matching(dir, is_ir_json)
}

/// The first non-JSON IR artifact directly inside `dir`, in file-name order —
/// the witness a directory refusal names. A read failure yields `None`: every
/// caller has just listed the same directory through [`snapshot_files`], so
/// its own fallback reports the cause.
fn first_non_json_ir_in(dir: &Path) -> Option<PathBuf> {
    files_matching(dir, is_non_json_ir)
        .unwrap_or_default()
        .into_iter()
        .next()
}

/// The first immediate subdirectory of `dir` that itself holds an `.ir.json`
/// snapshot, in name order — the witness a nesting refusal names.
///
/// One level down, and no further. `ridl baseline` publishes one flat
/// directory of snapshots and stages into a *sibling* of it, so snapshots
/// below a snapshot directory are never a layout the toolchain writes: they
/// are the signature of a path aimed one level too high (`.ridl` where
/// `.ridl/baseline` was meant), which is the mistake worth telling apart from
/// an unpublished baseline. Searching deeper would mean walking an arbitrary
/// tree — `--baseline .` at a repository root — to answer a question about
/// the one directory the author named, so a path aimed two or more levels
/// high yields no snapshot from this scan (issue #230). What that empty
/// result means is the caller's decision: [`load_baseline`] refuses it for an
/// explicit `--baseline` (driftsys/ridl#235) and reads it as an unpublished
/// baseline under auto-discovery.
///
/// A subdirectory that cannot be listed is exit 2, not a silent `None`. This
/// is the one scan in this file that reads a level *no caller has listed* —
/// [`first_non_json_ir_in`] and [`snapshot_files`] both read only `dir`
/// itself, which the caller has already been through — so the rule
/// [`snapshot_files`] states has to be restated here rather than inherited:
/// a directory that cannot be read must not quietly become a directory that
/// holds nothing. Swallowing the error would let an unreadable
/// `.ridl/baseline/` read as an unpublished baseline and skip the desk check
/// in silence, which is the failure this whole refusal exists to close.
fn first_nested_snapshot_dir(dir: &Path) -> Result<Option<PathBuf>, ExitCode> {
    let unreadable = |path: &Path, err: &std::io::Error| {
        eprintln!("error: cannot read {}: {err}", path.display());
        ExitCode::from(2)
    };
    let mut subdirectories: Vec<PathBuf> = std::fs::read_dir(dir)
        .map_err(|err| unreadable(dir, &err))?
        .flatten()
        .map(|entry| entry.path())
        .filter(|path| path.is_dir())
        .collect();
    subdirectories.sort();
    for subdirectory in subdirectories {
        if !ir_json_files(&subdirectory)
            .map_err(|err| unreadable(&subdirectory, &err))?
            .is_empty()
        {
            return Ok(Some(subdirectory));
        }
    }
    Ok(None)
}

/// Reports a directory whose `.ir.json` snapshots sit one level below it
/// rather than inside it, and yields exit 2 (issue #230).
///
/// Such a directory holds no IR artifact *directly*, so
/// [`refuse_artifact_directory`] cannot see it, and the snapshot scan reads it
/// as an *empty* set — indistinguishable from the ordinary "no baseline
/// published yet" state, which stays a silent pass under auto-discovery. The
/// snapshots are
/// described where they are rather than descended into: descending would
/// accept a layout `ridl baseline` never writes, and would have to choose
/// between subdirectories when more than one holds snapshots, silently
/// merging two unrelated baselines.
///
/// `nested` is the subdirectory the message names; `remedy` finishes the
/// message with the path the calling command should have been given.
fn refuse_nested_snapshot_directory(dir: &Path, nested: &Path, remedy: &str) -> ExitCode {
    eprintln!(
        "error: {}: no `.ir.json` snapshot directly inside, but the subdirectory `{}` holds one; \
         snapshots are read from one directory, never from the directories below it; {remedy}",
        dir.display(),
        nested
            .file_name()
            .unwrap_or(nested.as_os_str())
            .to_string_lossy()
    );
    ExitCode::from(2)
}

/// Reports a directory that holds IR artifacts but no `.ir.json` snapshot —
/// a snapshot directory in an encoding this surface refuses, not a source
/// tree or an unpublished baseline — and yields exit 2 (issue #218 item 4).
/// `witness` is the artifact the message names; `expectation` finishes the
/// message with what the calling command accepts and the remedy.
fn refuse_artifact_directory(dir: &Path, witness: &Path, expectation: &str) -> ExitCode {
    eprintln!(
        "error: {}: the directory holds IR artifacts (`{}`) but no `.ir.json` snapshot; \
         {expectation}",
        dir.display(),
        witness
            .file_name()
            .unwrap_or(witness.as_os_str())
            .to_string_lossy()
    );
    ExitCode::from(2)
}

/// [`ir_json_files`] with an unreadable directory turned into exit 2 — a
/// comparison against a directory that cannot be listed must not quietly become
/// a comparison against nothing.
fn snapshot_files(dir: &Path) -> Result<Vec<PathBuf>, ExitCode> {
    ir_json_files(dir).map_err(|err| {
        eprintln!(
            "error: cannot read the snapshot directory {}: {err}",
            dir.display()
        );
        ExitCode::from(2)
    })
}

/// The remedy [`untombstoned_removals`] appends when the snapshot it cannot
/// parse is the published baseline `ridl baseline` is about to replace.
///
/// The file stays fail-closed rather than being overwritten: a baseline that
/// cannot be read cannot be shown safe to replace, and replacing it would
/// destroy whatever ordinal record it held without any report — the exact
/// failure the gate exists to prevent. The reader cannot tell a damaged file
/// from one a toolchain with a different IR schema wrote (`from_json` rejects
/// an unknown field, ADR-0014 decision 14, and a snapshot carries no schema
/// marker), so the remedy names both causes. Neither branch tells the author
/// to delete the record unread: the second has the toolchain that wrote the
/// snapshot check the source against it first, and only then replaces it.
const PUBLISHED_PARSE_REMEDY: &str = "the file is left as it is, because a record that cannot be \
     read cannot be shown safe to replace. If the file is damaged, restore it from version \
     control or resolve the merge conflict left in it. If a toolchain with a different IR schema \
     wrote it, check the source against it with that toolchain (`ridl check --baseline`), then \
     remove the file and run `ridl baseline` with this one";

/// Deserializes every snapshot in `files`. One that cannot be read or parsed is
/// exit 2 — a comparison against half a baseline would be a lie about what is
/// published. This is shared by `ridl check --baseline` (through
/// [`load_baseline`], where the file may be the single `.ir.json` the flag
/// names), `ridl diff` (through [`load_diff_side`], for either side) and
/// `ridl baseline` (through [`untombstoned_removals`], for the published and
/// the freshly built side alike).
///
/// `parse_remedy`, when given, finishes the parse-error message. Only the
/// caller knows which file it handed over, so only the caller can say what to
/// do about it: the published baseline gets [`PUBLISHED_PARSE_REMEDY`], and
/// every other input gets the bare parse error, because "remove the file"
/// would be wrong advice for a diff input or a `--baseline` path.
fn load_snapshots(
    files: &[PathBuf],
    parse_remedy: Option<&str>,
) -> Result<Vec<ridl_ir::v2::Package>, ExitCode> {
    let mut packages = Vec::new();
    for file in files {
        match ridl_diff::load_ir_json(file) {
            Ok(package) => packages.push(package),
            Err(err @ ridl_diff::LoadError::Parse(_)) => {
                let remedy = parse_remedy.map_or(String::new(), |remedy| format!("; {remedy}"));
                eprintln!("error: {}: {err}{remedy}", file.display());
                return Err(ExitCode::from(2));
            }
            Err(err) => {
                eprintln!("error: {}: {err}", file.display());
                return Err(ExitCode::from(2));
            }
        }
    }
    Ok(packages)
}

/// Where every interaction and every interface shape of the current source tree
/// is declared, so a diff path can be pointed back at the code on the desk.
///
/// The diff engine reads only the IR, which carries no source locations, so the
/// span comes from a separate parse of the same tree. Matching is by name —
/// package, shape, interaction — which is exactly the identity the diff path
/// carries. "Shape" is an `interface` declaration or a service's inline body
/// (ridl §14.0, §14.5); the two are indexed together through
/// `SourceFile::shapes`, because a diff path names either one the same way. A
/// named-form service is indexed as well: its shape-list elements under the
/// interface names its diff paths carry, and the service's dotted name as the
/// fallback for an element that is gone.
#[derive(Default)]
struct DeclIndex {
    /// The text of each indexed file, by path: the renderer needs the text as
    /// well as the path to draw a snippet.
    texts: BTreeMap<String, String>,
    /// `(package, container, member)` to the member's declaration: an
    /// interaction inside an interface body, or one element of a named-form
    /// service's shape list, keyed by the interface name the diff path
    /// carries.
    members: BTreeMap<(String, String, String), (String, TextRange)>,
    /// `(package, container)` to the container's declared name. This is the
    /// fallback for a removed member, whose own declaration no longer exists
    /// in the source being checked. A service — inline or named-form — is
    /// keyed by its dotted name, exactly as its diff paths are.
    shapes: BTreeMap<(String, String), (String, TextRange)>,
    /// The package each indexed directory declares, by the directory's path
    /// as [`directory_of`] spells it. A package's `interfaces.lock` sits in
    /// the package directory, so the lock file's parent names the package a
    /// RIDL-409 belongs to.
    packages: BTreeMap<String, String>,
}

impl DeclIndex {
    /// Indexes every `.typl`, `.ridl` and `.rsdl` file under `entry` (an
    /// `.rsdl` file declares no shape and no service, so it adds nothing). A
    /// file that cannot be read is skipped rather than reported: the compile
    /// already ran clean over this tree, so anything unreadable here is outside
    /// what any caller of this index reports — neither the desk check nor the
    /// publication gate. An unreadable *directory* is not skipped in the same sense —
    /// `collect_source_files` fails on the first one it meets, and
    /// `unwrap_or_default` turns that into an empty index rather than a
    /// partial one — but the compile that already succeeded over this tree
    /// makes the case unreachable in practice, which is why it is not
    /// reported here either.
    fn build(entry: &Path) -> Self {
        let mut index = Self::default();
        for file in collect_source_files(entry).unwrap_or_default() {
            let Ok(text) = std::fs::read_to_string(&file) else {
                continue;
            };
            let path = file.to_string_lossy().into_owned();
            let parse = ridl_syntax::parse(&text, ridl_core::profile_of_path(&path));
            let Some(source) = SourceFile::cast(parse.syntax()) else {
                continue;
            };
            let Some(package) = package_name(&source) else {
                continue;
            };
            index.packages.insert(directory_of(&path), package.clone());

            // Every interface shape, `interface` declarations and services'
            // inline shapes alike (`SourceFile::shapes`). A service's inline
            // shape is an interface body in every way that matters to wire
            // identity, and the diff paths it produces are keyed by the service
            // name — so it earns a fallback entry exactly as a named interface
            // does, or a removal from it renders with no span at all.
            for shape in source.shapes() {
                let Some(name) = shape.identity() else {
                    continue;
                };
                let Some(range) = shape.identity_range() else {
                    continue;
                };
                index
                    .shapes
                    .insert((package.clone(), name.clone()), (path.clone(), range));
                index.record_members(&package, &name, &path, &text, shape.members());
            }

            // Named-form services (ridl §14.5). `SourceFile::shapes` yields
            // only inline-form services, so without this pass a service-level
            // diff path found nothing and rendered detached. Each listed
            // reference is indexed under its final segment, and the service's
            // dotted name is the fallback for one that is gone from the
            // source.
            for service in source
                .services()
                .filter(|service| service.colon_token().is_some())
            {
                let Some(dotted) = service.name() else {
                    continue;
                };
                let name = dotted.text();
                if name.is_empty() {
                    continue;
                }
                index.shapes.insert(
                    (package.clone(), name.clone()),
                    (path.clone(), dotted.syntax().text_range()),
                );
                for reference in service.shapes() {
                    let Some(final_segment) = final_ident(reference.syntax()) else {
                        continue;
                    };
                    index.members.insert(
                        (package.clone(), name.clone(), final_segment),
                        (path.clone(), reference.syntax().text_range()),
                    );
                }
            }

            index.texts.insert(path, text);
        }
        index
    }

    /// Records one interface body's interactions.
    fn record_members(
        &mut self,
        package: &str,
        shape: &str,
        path: &str,
        text: &str,
        members: impl Iterator<Item = InterfaceMember>,
    ) {
        for member in members {
            let Some(name) = member.name() else { continue };
            let Some(member_name) = name_text(&name) else {
                continue;
            };
            self.members.insert(
                (package.to_string(), shape.to_string(), member_name),
                (path.to_string(), declaration_range(&member, text)),
            );
        }
    }

    /// The span a `<package>/<shape>/<interaction>` diff path points at: the
    /// interaction's declaration, the shape's name when the interaction itself
    /// is gone (a removal), and a detached span when neither is in the source —
    /// a detached diagnostic renders as the coded message alone.
    fn span_of(&self, diff_path: &str, sources: &mut SourceMap) -> Span {
        let mut parts = diff_path.split('/');
        let (Some(package), Some(shape), Some(member)) = (parts.next(), parts.next(), parts.next())
        else {
            return detached_span();
        };

        let key = (package.to_string(), shape.to_string(), member.to_string());
        let found = self
            .members
            .get(&key)
            .or_else(|| self.shapes.get(&(key.0, key.1)));
        let Some((path, range)) = found else {
            return detached_span();
        };
        let Some(text) = self.texts.get(path) else {
            return detached_span();
        };
        Span {
            file: sources.file_id(path, text),
            range: *range,
        }
    }

    /// The package declared in the directory `dir` — the parent of a lock
    /// file's path — or `None` when no indexed file sits in it.
    fn package_of_dir(&self, dir: &str) -> Option<&str> {
        self.packages.get(dir).map(String::as_str)
    }

    /// The span of a shape's declared name — an `interface` declaration's
    /// name, or a service's dotted name for its inline shape — or a detached
    /// span when the source does not declare it.
    fn shape_span(&self, package: &str, shape: &str, sources: &mut SourceMap) -> Span {
        let Some((path, range)) = self.shapes.get(&(package.to_string(), shape.to_string())) else {
            return detached_span();
        };
        let Some(text) = self.texts.get(path) else {
            return detached_span();
        };
        Span {
            file: sources.file_id(path, text),
            range: *range,
        }
    }
}

/// A span pointing at no file at all.
fn detached_span() -> Span {
    Span {
        file: FileId::DETACHED,
        range: TextRange::empty(TextSize::new(0)),
    }
}

/// The declaration's own range, with trailing whitespace trimmed off: a node's
/// range can run to the start of the next line, and an underline that reaches
/// past the declaration reads as if the next one were implicated too.
fn declaration_range(member: &InterfaceMember, text: &str) -> TextRange {
    let range = member.syntax().text_range();
    let start = usize::from(range.start());
    let end = usize::from(range.end()).min(text.len());
    let trimmed = text
        .get(start..end)
        .map(|slice| slice.trim_end().len())
        .unwrap_or(0);
    TextRange::at(range.start(), TextSize::new(trimmed as u32))
}

/// The package a source file declares.
fn package_name(source: &SourceFile) -> Option<String> {
    dotted_text(source.package_decl()?.qualified_name()?.syntax())
}

/// The final identifier segment of a path node — `DiagBlock` of
/// `fleet.c2.DiagBlock` — under which a listed reference is indexed.
fn final_ident(node: &ridl_syntax::SyntaxNode) -> Option<String> {
    node.descendants_with_tokens()
        .filter_map(|element| element.into_token())
        .filter(|token| token.kind() == ridl_syntax::SyntaxKind::Ident)
        .last()
        .map(|token| token.text().to_string())
}

/// The identifier a `Name` node carries.
fn name_text(name: &Name) -> Option<String> {
    Some(name.ident_token()?.text().to_string())
}

/// The dotted text of a qualified or dotted name node — its non-trivia tokens
/// joined, e.g. `veh.cluster`.
fn dotted_text(node: &ridl_syntax::SyntaxNode) -> Option<String> {
    let text: String = node
        .children_with_tokens()
        .filter_map(|element| element.into_token())
        .filter(|token| !token.kind().is_trivia())
        .map(|token| token.text().to_string())
        .collect();
    (!text.is_empty()).then_some(text)
}

/// The 1/0 rule every `check`/`build` run turns its diagnostics into: 1 when
/// any diagnostic is an error, 0 otherwise. Shared by [`finish`] and
/// [`finish_check`]'s JSON arm so the rule is stated once.
fn exit_code(run: &CliRun) -> ExitCode {
    if run.has_error() {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

/// Ends `ridl check`: text renders to stderr through [`finish`]; JSON prints
/// the contract to stdout and keeps the same exit code.
fn finish_check(run: CliRun, format: CheckFormat) -> ExitCode {
    match format {
        CheckFormat::Text => finish(Ok(run)),
        CheckFormat::Json => {
            let json = ridl_core::diag::to_json(&run.diagnostics, &run.sources);
            println!(
                "{}",
                serde_json::to_string_pretty(&json).expect("diagnostics serialize")
            );
            exit_code(&run)
        }
    }
}

/// Renders a check/build run's diagnostics to stderr and turns the outcome into
/// an exit code: 2 on an I/O error, 1 when any diagnostic is an error, 0
/// otherwise.
fn finish(run: std::io::Result<CliRun>) -> ExitCode {
    match run {
        Ok(run) => {
            eprint!("{}", render(&run.diagnostics, &run.sources));
            exit_code(&run)
        }
        Err(err) => {
            eprintln!("error: {err}");
            ExitCode::from(2)
        }
    }
}

/// Formats every `.typl`, `.ridl` and `.rsdl` file under `path`, each parsed
/// under the profile its extension selects.
///
/// A file with parse errors is never rewritten (a formatter must not eat broken
/// code); its diagnostics render to stderr and the run exits 1. In `--check`
/// mode nothing is written and a file that would change also exits 1.
fn run_fmt(path: &Path, check: bool) -> ExitCode {
    let mut sources = SourceMap::new();
    let mut diagnostics = Vec::new();
    let mut any_would_change = false;
    let mut any_broken = false;

    let files = match collect_source_files(path) {
        Ok(files) => files,
        Err((dir, err)) => {
            eprintln!("error: cannot read {}: {err}", dir.display());
            return ExitCode::from(2);
        }
    };

    for file in files {
        let text = match std::fs::read_to_string(&file) {
            Ok(text) => text,
            Err(err) => {
                eprintln!("error: cannot read {}: {err}", file.display());
                return ExitCode::from(2);
            }
        };
        let profile = ridl_core::profile_of_path(&file.to_string_lossy());
        match format(&text, profile) {
            FormatOutcome::Formatted(formatted) => {
                if formatted != text {
                    any_would_change = true;
                    if !check && let Err(err) = std::fs::write(&file, &formatted) {
                        eprintln!("error: cannot write {}: {err}", file.display());
                        return ExitCode::from(2);
                    }
                }
            }
            FormatOutcome::ParseErrors(errors) => {
                any_broken = true;
                let file_id = sources.file_id(&file.to_string_lossy(), &text);
                for error in &errors {
                    diagnostics.push(ridlc::syntax_error_diagnostic(error, file_id));
                }
            }
        }
    }

    eprint!("{}", render(&diagnostics, &sources));
    if any_broken || (check && any_would_change) {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

/// Every `.typl`, `.ridl` and `.rsdl` file under `path`: `path` itself when it
/// is a file, otherwise a recursive walk that skips hidden directories.
///
/// A directory the walk cannot read — `path` itself, when it does not exist
/// or is not readable, or a subdirectory the walk descends into — is an error
/// rather than zero files: `Err` carries the directory `read_dir` failed on
/// and the underlying `io::Error`. The walk cannot tell "empty" from
/// "absent" or "unreadable" any other way, and treating those as zero files
/// is what let `ridl fmt` report success over a tree it never read.
fn collect_source_files(path: &Path) -> Result<Vec<PathBuf>, (PathBuf, std::io::Error)> {
    if path.is_file() {
        return Ok(vec![path.to_path_buf()]);
    }
    let mut files = Vec::new();
    let mut stack = vec![path.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let entries = std::fs::read_dir(&dir).map_err(|err| (dir.clone(), err))?;
        for entry in entries.flatten() {
            let child = entry.path();
            if child.is_dir() {
                let hidden = child
                    .file_name()
                    .and_then(|name| name.to_str())
                    .is_some_and(|name| name.starts_with('.'));
                if !hidden {
                    stack.push(child);
                }
            } else if child
                .extension()
                .is_some_and(|ext| ext == "typl" || ext == "ridl" || ext == "rsdl")
            {
                files.push(child);
            }
        }
    }
    files.sort();
    Ok(files)
}