dive-cli 0.1.0

The dive TLA+ model checker command-line tool, with a TLC-compatible `tlc` command
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
//! Shared command dispatch for the `dive` and `tlc` binaries.
//!
//! Native commands retain their own defaults. The checking-only TLC adapter
//! selects TLC evaluation and accepts common checking spellings through
//! `dive tlc` or an executable named `tlc`. Unimplemented commands and features
//! return named refusals.
#![forbid(unsafe_code)]

mod debug;
mod explain;
mod help;
mod tlc;
mod translate;

use std::io::Write as _;
use std::process::ExitCode;

/// Implemented commands advertised in help, each with a one-line description.
const COMMANDS: &[(&str, &str)] = &[
    ("check", "Check a model exhaustively"),
    ("worker", "Serve safety work for a distributed `dive check`"),
    ("tlc", "Check a model with TLC's command-line arguments"),
    ("dfid", "Check a model by bounded iterative deepening"),
    ("simulate", "Explore random bounded behaviors"),
    ("parse", "Parse a specification or configuration"),
    ("analyze", "Resolve modules and analyze a specification"),
    ("translate", "Translate PlusCal into TLA+"),
    ("validate-trace", "Validate a counterexample independently"),
    ("explain", "Explain an error code"),
    (
        "debug",
        "Debug a safety check over the Debug Adapter Protocol (experimental)",
    ),
];

/// What `--lncheck final --lasso short` adds to Core's refusal of a model's
/// temporal properties. A model without temporal properties is checked as
/// usual.
pub(crate) const FINAL_SHORT_REFUSAL: &str =
    "bounded final checking (--lncheck final --lasso short) is not implemented on Core";

/// The command list of `dive --help`: names in a column, then descriptions.
fn command_list() -> String {
    let width = COMMANDS
        .iter()
        .map(|(name, _)| name.len())
        .max()
        .unwrap_or(0);
    COMMANDS
        .iter()
        .map(|(name, description)| format!("{name:width$}  {description}"))
        .collect::<Vec<_>>()
        .join("\n    ")
}

/// Exit code when the input is rejected (`parse`: syntax or cfg errors;
/// `analyze`: any error SANY would report).
const EXIT_REJECTED: u8 = 1;
/// Exit code for a malformed command line or unreadable input.
const EXIT_USAGE: u8 = 2;
/// Exit code for a request that `dive` recognises but does not implement.
const EXIT_UNSUPPORTED: u8 = 3;

/// Validates an `--engine` value. Core is the only engine: the earlier
/// `auto` and `reference` values name engines that no longer exist and are
/// rejected with an explanation. `--engine core` is still accepted, and no
/// longer advertised.
fn engine_option(name: Option<&str>) -> Result<(), String> {
    match name {
        Some("core") => Ok(()),
        Some("auto") => Err(
            "--engine auto was removed: Core is the only engine and refuses by \
             name what it does not implement"
                .to_owned(),
        ),
        Some("reference") => Err(
            "--engine reference was removed: the reference engine is no longer part of \
             dive check, simulate, dfid or tlc; Core refuses by name what it does not implement"
                .to_owned(),
        ),
        _ => Err("--engine expects `core`, the only engine".to_owned()),
    }
}

/// Validates `DIVE_ENGINE`, which may be unset, empty or `core`.
fn engine_from_env() -> Result<(), String> {
    match std::env::var("DIVE_ENGINE").ok().as_deref() {
        None | Some("") => Ok(()),
        Some(name) => engine_option(Some(name))
            .map_err(|message| message.replacen("--engine", "DIVE_ENGINE", 1)),
    }
}

fn usage() -> String {
    format!(
        "dive {}\nDeterministic Invariant Verification Engine\n\nUSAGE:\n    dive <COMMAND> [ARGS]\n\nCOMMANDS:\n    {}\n\n    dive parse [FILE.tla] [--config FILE.cfg] [--output human|json] [--cst]\n    dive translate <FILE.tla> [--compat=tlc] [--rewrite|--write] [--checksums tla|full] [--replace-modified] [--ast|-writeAST] [--output human|json] [--library-path DIR]... [--module-path DIR]...\n    dive analyze <FILE.tla> [--output human|json] [--library-path DIR]... [--module-path DIR]...\n    dive debug <FILE.tla> [--stdio|--listen 127.0.0.1:PORT] [--compat=tlc]\n    dive explain <CODE> [--output human|json]\n    dive tlc [OPTIONS] SPEC[.tla] (TLC checking arguments; see dive tlc -help)\n    dive check <FILE.tla> [--config FILE.cfg] [--compat=tlc] [--exit-codes native|tlc] [--store fp|exact] [--seed N] [--fp N]\n               [--workers N|auto] [--sequential] [-deadlock] [--action-composition off|tla]\n               [--symmetry-liveness unreduced|refuse|tlc]\n               [--frontier-memory-bytes N] [--frontier-directory DIR] [--candidate-memory-bytes N] [--candidate-directory DIR] [--store-compact-bytes N] [--output human|json]\n               [--time-limit DURATION|none] [--max-memory BYTES|auto|none]
               [--max-states N|none] [--max-depth N|none]
               [--predecessor-memory-bytes N] [--predecessor-directory DIR]\n               [--seen-disk-entries N] [--seen-directory DIR] [--seen-key-bytes N]\n               [--seen-probe-steps N] [--seen-summary-pairs N]
               [--checkpoint FILE --checkpoint-after-levels N | --recover FILE]
               [--checkpoint-counters tlc|retain]
               [--distributed-worker IP:port]... [--worker-key FILE] [--worker-timeout-ms N] [--distributed-retries N]
               [--core-sample N] [--library-path DIR]... [--module-path DIR]...\n    dive worker <FILE.tla> --seed N --fp N --worker-key FILE [--listen IP:port] [--worker-timeout-ms N] [--worker-max-units N]\n                [--config FILE.cfg] [--compat=tlc] [--store fp|exact] [--output human|json]\n    dive simulate <FILE.tla> --traces N [--generate] [--exit-codes native|tlc] [--depth N] [--seed N] [--aril N] [--stats none|basic] [--time-limit DURATION|none] [--max-memory BYTES|auto|none] [--compat=tlc] [--output human|json]\n    dive dfid <FILE.tla> --max-level N [--compat=tlc] [--seed N] [--worker-seeds S,...] [--time-limit DURATION|none] [--max-memory BYTES|auto|none] [--output human|json]\n    dive validate-trace <FILE.tla> [--trace TRACE.json] [--inputs RUN.json] [--config FILE.cfg] [--claim ENDING] [--sample]\n               [--compat=tlc] [--symmetry-liveness unreduced|refuse|tlc] [--seed N] [--fp N] [-deadlock] [--output human|json] [--library-path DIR]... [--module-path DIR]...\n\n    Eligible ordinary temporal checks use deterministic completed-level checks in the dive
    profile and final checking in the TLC profile.
    dive check uses TLC process statuses by default, independently of semantic profile.\n    --exit-codes native retains: 0 no error, 1 rejected input, 10 property violated, 11 deadlock,\n    12 assumption, 13 evaluation error. Both conventions keep 2 usage, 3 unsupported/resource\n    limit, 4 internal error and 5 stopped by a run budget (no verdict).\n    --time-limit defaults to none in both profiles, as in TLC; --max-memory defaults to\n    half of physical memory (auto) in both. --compat=tlc (or DIVE_COMPAT=tlc) selects existing TLC-compatible behavior; known gaps are documented.\n    The compiled Core is the engine of check, simulate, dfid and tlc; what it does not\n    implement is a named refusal, never a fallback. --core-sample N\n    also compares the successors of N sampled states with an independent evaluator's, in the JSON\n    report (core.sample); it is diagnostic and changes no result.
    Options Core does not implement are not listed; they still parse and refuse by name\n    (exit 3).\n",
        env!("CARGO_PKG_VERSION"),
        command_list()
    )
}

/// Parsed `dive parse` arguments.
#[derive(Default)]
struct ParseArgs<'a> {
    file: Option<&'a str>,
    config: Option<&'a str>,
    json: bool,
    cst: bool,
}

fn parse_args<'a>(args: &'a [String], err: &mut impl std::io::Write) -> Option<ParseArgs<'a>> {
    let mut p = ParseArgs::default();
    let mut it = args.iter();
    while let Some(a) = it.next() {
        match a.as_str() {
            "--output" => match it.next().map(String::as_str) {
                Some("json") => p.json = true,
                Some("human") => p.json = false,
                other => {
                    let _ = writeln!(
                        err,
                        "error: --output expects `human` or `json`, got {}",
                        other.unwrap_or("nothing")
                    );
                    return None;
                }
            },
            "--config" => {
                let Some(c) = it.next() else {
                    let _ = writeln!(err, "error: --config expects a .cfg file");
                    return None;
                };
                if p.config.replace(c).is_some() {
                    let _ = writeln!(err, "error: --config given twice");
                    return None;
                }
            }
            "--cst" => p.cst = true,
            s if s.starts_with('-') => {
                let _ = writeln!(err, "error: unknown option `{s}` for `dive parse`");
                return None;
            }
            s => {
                if p.file.replace(s).is_some() {
                    let _ = writeln!(err, "error: `dive parse` takes one file");
                    return None;
                }
            }
        }
    }
    if p.file.is_none() && p.config.is_none() {
        let _ = writeln!(
            err,
            "error: `dive parse` needs a file or --config\n\n{}",
            usage()
        );
        return None;
    }
    Some(p)
}

/// `dive parse [file] [--config cfg] [--output human|json] [--cst]`.
fn parse_command(
    args: &[String],
    out: &mut impl std::io::Write,
    err: &mut impl std::io::Write,
) -> ExitCode {
    let Some(p) = parse_args(args, err) else {
        return ExitCode::from(EXIT_USAGE);
    };
    let report = match p
        .file
        .map(|f| dive_api::parse_file(std::path::Path::new(f)))
    {
        None => None,
        Some(Ok(r)) => Some(r),
        Some(Err(e)) => {
            let _ = writeln!(err, "error: {e}");
            return ExitCode::from(EXIT_USAGE);
        }
    };
    let config = match p
        .config
        .map(|c| dive_api::parse_config_file(std::path::Path::new(c)))
    {
        None => None,
        Some(Ok(r)) => Some(r),
        Some(Err(e @ dive_api::ApiError::Unsupported { .. })) => {
            let _ = writeln!(err, "{e}; no result produced");
            return ExitCode::from(EXIT_UNSUPPORTED);
        }
        Some(Err(e)) => {
            let _ = writeln!(err, "error: {e}");
            return ExitCode::from(EXIT_USAGE);
        }
    };
    let accepted = report.as_ref().is_none_or(dive_api::ParseReport::accepted)
        && config.as_ref().is_none_or(dive_api::ConfigReport::accepted);
    if p.json {
        let mut v = match &report {
            Some(r) => r.to_json(p.cst),
            None => serde_json::json!({
                "schema_version": dive_api::PARSE_SCHEMA_VERSION,
                "command": "parse",
                "file": null,
                "module": null,
                "modules": [],
                "diagnostics": [],
            }),
        };
        if let Some(obj) = v.as_object_mut() {
            obj.insert("accepted".to_owned(), serde_json::Value::Bool(accepted));
            if let Some(c) = &config {
                obj.insert("config".to_owned(), c.to_json());
            }
        }
        let _ = writeln!(out, "{v}");
    } else {
        if let Some(r) = &report {
            let _ = write!(err, "{}", r.render_human());
            if p.cst {
                let _ = write!(out, "{:#?}", r.parse().syntax());
            }
            if r.accepted() {
                let _ = writeln!(
                    out,
                    "ok: {} parsed ({})",
                    p.file.unwrap_or_default(),
                    r.modules().join(", ")
                );
            }
        }
        if let Some(c) = &config {
            let _ = write!(err, "{}", c.render_human());
            if let Some(m) = c.config() {
                let _ = writeln!(
                    out,
                    "ok: {} read ({} constants, {} invariants, {} properties)",
                    p.config.unwrap_or_default(),
                    m.constants.len(),
                    m.invariants.len(),
                    m.properties.len()
                );
            }
        }
    }
    if accepted {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(EXIT_REJECTED)
    }
}

/// `dive analyze <file> [--output human|json] [--library-path DIR]... [--module-path DIR]...`.
///
/// SANY-equivalent semantic analysis of the specification rooted at the file.
/// Modules are found in the file's directory, the library paths, the standard
/// modules, then the module paths.
fn analyze_command(
    args: &[String],
    out: &mut impl std::io::Write,
    err: &mut impl std::io::Write,
) -> ExitCode {
    let mut file: Option<&str> = None;
    let mut json = false;
    let mut opts = dive_api::AnalyzeOptions::default();
    let mut it = args.iter();
    while let Some(a) = it.next() {
        match a.as_str() {
            "--output" => match it.next().map(String::as_str) {
                Some("json") => json = true,
                Some("human") => json = false,
                other => {
                    let _ = writeln!(
                        err,
                        "error: --output expects `human` or `json`, got {}",
                        other.unwrap_or("nothing")
                    );
                    return ExitCode::from(EXIT_USAGE);
                }
            },
            "--library-path" | "--module-path" => {
                let Some(dir) = it.next() else {
                    let _ = writeln!(err, "error: {a} expects a directory");
                    return ExitCode::from(EXIT_USAGE);
                };
                if a == "--library-path" {
                    opts.library_paths.push(dir.into());
                } else {
                    opts.after_standard.push(dir.into());
                }
            }
            s if s.starts_with('-') => {
                let _ = writeln!(err, "error: unknown option `{s}` for `dive analyze`");
                return ExitCode::from(EXIT_USAGE);
            }
            s => {
                if file.replace(s).is_some() {
                    let _ = writeln!(err, "error: `dive analyze` takes one file");
                    return ExitCode::from(EXIT_USAGE);
                }
            }
        }
    }
    let Some(file) = file else {
        let _ = writeln!(err, "error: `dive analyze` needs a file\n\n{}", usage());
        return ExitCode::from(EXIT_USAGE);
    };
    let report = match dive_api::analyze_file(std::path::Path::new(file), &opts) {
        Ok(r) => r,
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return ExitCode::from(EXIT_USAGE);
        }
    };
    if json {
        let _ = writeln!(out, "{}", report.to_json());
    } else {
        let _ = write!(err, "{}", report.render_human());
        if report.accepted() {
            let _ = writeln!(
                out,
                "ok: {} analysed ({})",
                file,
                report.modules().join(", ")
            );
        }
    }
    if report.accepted() {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(EXIT_REJECTED)
    }
}

/// Parses a numeric option value.
fn number<T: std::str::FromStr>(
    flag: &str,
    v: Option<&String>,
    err: &mut impl std::io::Write,
) -> Option<T> {
    let parsed = v.and_then(|v| v.parse().ok());
    if parsed.is_none() {
        let _ = writeln!(err, "error: {flag} expects a number");
    }
    parsed
}

/// `--time-limit`: `none`, or a positive duration in seconds by default, or
/// with a unit (`ms`, `s`, `m`, `h`).
fn time_limit(text: &str) -> Option<dive_api::BudgetSetting<std::time::Duration>> {
    if text == "none" {
        return Some(dive_api::BudgetSetting::Unlimited);
    }
    let split = text
        .find(|c: char| !c.is_ascii_digit())
        .unwrap_or(text.len());
    let (digits, unit) = text.split_at(split);
    let n: u64 = digits.parse().ok().filter(|n| *n > 0)?;
    let duration = match unit {
        "ms" => std::time::Duration::from_millis(n),
        "" | "s" => std::time::Duration::from_secs(n),
        "m" => std::time::Duration::from_secs(n.checked_mul(60)?),
        "h" => std::time::Duration::from_secs(n.checked_mul(3600)?),
        _ => return None,
    };
    Some(dive_api::BudgetSetting::Explicit(duration))
}

/// `--max-memory`: `auto`, `none`, or a positive byte count, optionally with a
/// binary unit as for the JVM's `-Xmx` (`k`, `m`, `g`, `t`, either case).
fn max_memory(text: &str) -> Option<dive_api::BudgetSetting<u64>> {
    match text {
        "auto" => return Some(dive_api::BudgetSetting::Default),
        "none" => return Some(dive_api::BudgetSetting::Unlimited),
        _ => {}
    }
    let split = text
        .find(|c: char| !c.is_ascii_digit())
        .unwrap_or(text.len());
    let (digits, unit) = text.split_at(split);
    let n: u64 = digits.parse().ok().filter(|n| *n > 0)?;
    let shift = match unit.to_ascii_lowercase().as_str() {
        "" => 0,
        "k" => 10,
        "m" => 20,
        "g" => 30,
        "t" => 40,
        _ => return None,
    };
    n.checked_mul(1 << shift)
        .map(dive_api::BudgetSetting::Explicit)
}

/// Search limits admit zero and use `none` for TLC-equivalent unlimited search.
fn search_limit(text: &str) -> Result<Option<u64>, std::num::ParseIntError> {
    if text == "none" {
        Ok(None)
    } else {
        text.parse().map(Some)
    }
}

/// `dive check <file> [options]`: safety model checking (see `usage`).
#[allow(clippy::too_many_lines, reason = "one flag per arm")]
fn check_command(
    args: &[String],
    out: &mut impl std::io::Write,
    err: &mut impl std::io::Write,
) -> ExitCode {
    check_command_mode(args, out, err, false)
}

#[allow(
    clippy::too_many_lines,
    reason = "one shared checker/worker option parser preserves source and policy flags"
)]
fn check_command_mode(
    args: &[String],
    out: &mut impl std::io::Write,
    err: &mut impl std::io::Write,
    worker_mode: bool,
) -> ExitCode {
    let mut req = dive_api::CheckRequest {
        compat_tlc: std::env::var("DIVE_COMPAT").is_ok_and(|v| v == "tlc"),
        // Test-only (hidden): chaos scheduling for determinism testing.
        chaos: std::env::var("DIVE_CHAOS")
            .ok()
            .and_then(|v| v.parse().ok()),
        ..dive_api::CheckRequest::default()
    };
    let mut seen_policy = dive_api::SeenOptions::default();
    let mut host_access_given = false;
    let mut seen_entries = false;
    let mut seen_extra = false;
    let mut checkpoint_path: Option<std::path::PathBuf> = None;
    let mut recover_path: Option<std::path::PathBuf> = None;
    let mut checkpoint_after: Option<u64> = None;
    let mut checkpoint_counters = dive_api::checkpoint::Counters::Tlc;
    let mut counters_given = false;
    let mut final_check = false;
    let mut short_lasso = false;
    let mut file: Option<&str> = None;
    let mut json = false;
    let mut remote_workers = Vec::new();
    let mut worker_key: Option<std::path::PathBuf> = None;
    let mut worker_listen = "127.0.0.1:0".parse::<std::net::SocketAddr>().ok();
    let mut worker_timeout = std::time::Duration::from_secs(5);
    let mut worker_timeout_given = false;
    let mut worker_retries = 2;
    let mut worker_retries_given = false;
    let mut worker_max_units = None;
    let mut exit_convention = dive_api::ExitConvention::Tlc;
    if !worker_mode && let Err(message) = engine_from_env() {
        let _ = writeln!(err, "error: {message}");
        return ExitCode::from(EXIT_USAGE);
    }
    let usage_error = |err: &mut dyn std::io::Write, m: &str| {
        let _ = writeln!(err, "error: {m}");
        ExitCode::from(EXIT_USAGE)
    };
    let mut it = args.iter();
    while let Some(a) = it.next() {
        let (flag, inline) = match a.split_once('=') {
            Some((f, v)) if f.starts_with('-') => (f, Some(v.to_owned())),
            _ => (a.as_str(), None),
        };
        let mut value = || inline.clone().or_else(|| it.next().cloned());
        match flag {
            "--distributed-worker" if !worker_mode => match value()
                .as_deref()
                .and_then(|s| s.parse::<std::net::SocketAddr>().ok())
            {
                Some(address) => remote_workers.push(address),
                None => {
                    return usage_error(err, "--distributed-worker expects an IP:port endpoint");
                }
            },
            "--worker-key" => match value() {
                Some(path) => worker_key = Some(path.into()),
                None => return usage_error(err, "--worker-key expects a local key-file path"),
            },
            "--listen" if worker_mode => match value()
                .as_deref()
                .and_then(|s| s.parse::<std::net::SocketAddr>().ok())
            {
                Some(address) => worker_listen = Some(address),
                None => return usage_error(err, "--listen expects an IP:port endpoint"),
            },
            "--worker-timeout-ms" => match value()
                .as_deref()
                .and_then(|s| s.parse::<u64>().ok())
                .filter(|ms| (1..=60_000).contains(ms))
            {
                Some(ms) => {
                    worker_timeout_given = true;
                    worker_timeout = std::time::Duration::from_millis(ms);
                }
                None => {
                    return usage_error(
                        err,
                        "--worker-timeout-ms expects milliseconds in 1..60000",
                    );
                }
            },
            "--distributed-retries" if !worker_mode => {
                match value()
                    .as_deref()
                    .and_then(|s| s.parse::<u8>().ok())
                    .filter(|n| *n <= 8)
                {
                    Some(n) => {
                        worker_retries_given = true;
                        worker_retries = n;
                    }
                    None => return usage_error(err, "--distributed-retries expects 0..8"),
                }
            }
            "--worker-max-units" if worker_mode => {
                match value().as_deref().and_then(|s| s.parse::<u64>().ok()) {
                    Some(n) => worker_max_units = Some(n),
                    None => return usage_error(err, "--worker-max-units expects a work count"),
                }
            }
            "--output" => match value().as_deref() {
                Some("json") => json = true,
                Some("human") => json = false,
                _ => return usage_error(err, "--output expects `human` or `json`"),
            },
            "--exit-codes" => match value().as_deref() {
                Some("native") => exit_convention = dive_api::ExitConvention::Native,
                Some("tlc") => exit_convention = dive_api::ExitConvention::Tlc,
                _ => return usage_error(err, "--exit-codes expects `native` or `tlc`"),
            },
            "--compat" => match value().as_deref() {
                Some("tlc") => req.compat_tlc = true,
                Some("dive" | "none") => req.compat_tlc = false,
                _ => return usage_error(err, "--compat expects `tlc`"),
            },
            "--config" | "-config" => match value() {
                Some(c) => req.config = Some(c.into()),
                None => return usage_error(err, "--config expects a .cfg file"),
            },
            "--lncheck" => match value().as_deref() {
                Some("final") => final_check = true,
                _ => {
                    return usage_error(
                        err,
                        "--lncheck currently supports explicit `final` with --lasso short",
                    );
                }
            },
            "--lasso" => match value().as_deref() {
                Some("short") => short_lasso = true,
                Some("tlc") => {
                    return usage_error(
                        err,
                        "--lasso tlc is not supported: dive does not reproduce TLC's lasso choice; use --lasso short (an independently validated counterexample)",
                    );
                }
                _ => return usage_error(err, "--lasso expects `short` with --lncheck final"),
            },
            "--store" => match value().as_deref() {
                Some("exact") => req.store = dive_api::Store::Exact,
                Some("fp" | "fingerprint") => req.store = dive_api::Store::Fingerprint,
                _ => return usage_error(err, "--store expects `fp` or `exact`"),
            },
            "--allow-io" => {
                if host_access_given {
                    return usage_error(err, "--allow-io given twice");
                }
                let Some(text) = value() else {
                    return usage_error(err, "--allow-io expects categories");
                };
                match dive_api::HostAccess::parse(&text) {
                    Ok(access) => req.host_access = access,
                    Err(message) => return usage_error(err, message),
                }
                host_access_given = true;
            }
            "--seed" | "-seed" => {
                let v = value();
                match v.as_deref().and_then(dive_api::parse_seed) {
                    Some(s) => req.seed = Some(s),
                    None => return usage_error(err, "--seed expects a 64-bit integer"),
                }
            }
            "--fp" | "-fp" => {
                let v = value();
                match number::<usize>(flag, v.as_ref(), err) {
                    Some(n) if n < 131 => req.fp = Some(n),
                    _ => return usage_error(err, "--fp expects a polynomial index from 0 to 130"),
                }
            }
            "--workers" | "-workers" => {
                let v = value();
                if v.as_deref() == Some("auto") {
                    req.workers = None;
                } else {
                    match number::<usize>(flag, v.as_ref(), err) {
                        Some(n) if n > 0 => req.workers = Some(n),
                        _ => {
                            return usage_error(
                                err,
                                "--workers expects a positive number or `auto`",
                            );
                        }
                    }
                }
            }
            "-deadlock" => req.no_deadlock = true,
            "--symmetry-liveness" => {
                let Some(policy) = value().as_deref().and_then(symmetry_liveness) else {
                    return usage_error(
                        err,
                        "--symmetry-liveness expects unreduced, refuse or tlc",
                    );
                };
                req.symmetry_liveness = Some(policy);
            }
            "--action-composition" => match value().as_deref() {
                Some("off") => req.action_composition = Some(dive_api::ActionComposition::Off),
                Some("tlc") => req.action_composition = Some(dive_api::ActionComposition::Tlc),
                Some("tla") => req.action_composition = Some(dive_api::ActionComposition::Tla),
                _ => return usage_error(err, "--action-composition expects off, tlc or tla"),
            },
            // TLC's JVM switch, spelled as TLC users pass it.
            "-Dtlc2.tool.impl.Tool.cdot" => match value().as_deref() {
                Some("true") => req.action_composition = Some(dive_api::ActionComposition::Tlc),
                _ => {
                    return usage_error(
                        err,
                        "-Dtlc2.tool.impl.Tool.cdot expects true (or use --action-composition)",
                    );
                }
            },
            "--sequential" => req.sequential = true,
            "--source-coverage" => req.source_coverage = true,
            "--coverage" => match value().as_deref() {
                Some("0") => req.tlc_coverage = true,
                _ => {
                    return usage_error(
                        err,
                        "--coverage currently supports final reporting only: use 0",
                    );
                }
            },
            "--engine" => {
                if let Err(message) = engine_option(value().as_deref()) {
                    return usage_error(err, &message);
                }
            }
            "--core-sample" => match value().and_then(|v| v.parse().ok()) {
                Some(n) => req.core_sample = Some(n),
                None => return usage_error(err, "--core-sample expects a state count"),
            },
            "--seen-disk-entries" => match value().and_then(|v| v.parse().ok()) {
                Some(n) => {
                    seen_policy.limits.entries = n;
                    seen_entries = true;
                }
                None => {
                    return usage_error(
                        err,
                        "--seen-disk-entries expects a positive bounded entry count",
                    );
                }
            },
            "--seen-key-bytes" => match value().and_then(|v| v.parse().ok()) {
                Some(n) => {
                    seen_policy.limits.key_bytes = n;
                    seen_extra = true;
                }
                None => return usage_error(err, "--seen-key-bytes expects a key byte bound"),
            },
            "--seen-probe-steps" => match value().and_then(|v| v.parse().ok()) {
                Some(n) => {
                    seen_policy.limits.probe_steps = n;
                    seen_extra = true;
                }
                None => {
                    return usage_error(err, "--seen-probe-steps expects a positive probe bound");
                }
            },
            "--seen-summary-pairs" => match value().and_then(|v| v.parse().ok()) {
                Some(n) => {
                    seen_policy.limits.summary_pairs = n;
                    seen_extra = true;
                }
                None => {
                    return usage_error(
                        err,
                        "--seen-summary-pairs expects a pair-comparison bound",
                    );
                }
            },
            "--seen-directory" => match value() {
                Some(dir) => {
                    seen_policy.directory = Some(dir.into());
                    seen_extra = true;
                }
                None => return usage_error(err, "--seen-directory expects a parent directory"),
            },
            "--candidate-memory-bytes" => match value().as_deref().map(str::parse::<usize>) {
                Some(Ok(n)) => req.candidate_memory_bytes = Some(n),
                _ => {
                    return usage_error(
                        err,
                        "--candidate-memory-bytes expects a byte count (zero forces disk)",
                    );
                }
            },
            "--candidate-directory" => match value() {
                Some(dir) => req.candidate_directory = Some(dir.into()),
                None => return usage_error(err, "--candidate-directory expects a directory"),
            },
            "--store-compact-bytes" => match value().as_deref().map(str::parse::<usize>) {
                Some(Ok(n)) => req.store_compact_bytes = Some(n),
                _ => {
                    return usage_error(
                        err,
                        "--store-compact-bytes expects a byte trigger (zero forces each completed level)",
                    );
                }
            },
            "--frontier-memory-bytes" => match value().as_deref().map(str::parse::<usize>) {
                Some(Ok(n)) => req.frontier_memory_bytes = Some(n),
                _ => {
                    return usage_error(
                        err,
                        "--frontier-memory-bytes expects a byte count (zero forces disk)",
                    );
                }
            },
            "--frontier-directory" => match value() {
                Some(dir) => req.frontier_directory = Some(dir.into()),
                None => return usage_error(err, "--frontier-directory expects a directory"),
            },
            "--checkpoint" => match value() {
                Some(path) if checkpoint_path.is_none() => checkpoint_path = Some(path.into()),
                _ => return usage_error(err, "--checkpoint expects one native file"),
            },
            "--recover" => match value() {
                Some(path) if recover_path.is_none() => recover_path = Some(path.into()),
                _ => return usage_error(err, "--recover expects one native file"),
            },
            "--checkpoint-after-levels" => match value().and_then(|s| s.parse().ok()) {
                Some(n) if checkpoint_after.is_none() => checkpoint_after = Some(n),
                _ => {
                    return usage_error(
                        err,
                        "--checkpoint-after-levels expects a nonnegative count",
                    );
                }
            },
            "--checkpoint-counters" => {
                counters_given = true;
                checkpoint_counters = match value().as_deref() {
                    Some("tlc") => dive_api::checkpoint::Counters::Tlc,
                    Some("retain") => dive_api::checkpoint::Counters::Retain,
                    _ => return usage_error(err, "--checkpoint-counters expects tlc or retain"),
                };
            }
            "--predecessor-memory-bytes" => {
                let v = value();
                match number::<usize>(flag, v.as_ref(), err) {
                    Some(n) => req.predecessor_memory_bytes = Some(n),
                    None => {
                        return usage_error(
                            err,
                            "--predecessor-memory-bytes expects a nonnegative byte count",
                        );
                    }
                }
            }
            "--predecessor-directory" => match value() {
                Some(dir) => req.predecessor_directory = Some(dir.into()),
                None => return usage_error(err, "--predecessor-directory expects a directory"),
            },
            "--time-limit" => match value().as_deref().map(time_limit) {
                Some(Some(setting)) => req.time_limit = setting,
                _ => {
                    return usage_error(
                        err,
                        "--time-limit expects a positive duration (90, 90s, 500ms, 10m, 2h) or `none`",
                    );
                }
            },
            "--max-memory" => match value().as_deref().map(max_memory) {
                Some(Some(setting)) => req.max_memory = setting,
                _ => {
                    return usage_error(
                        err,
                        "--max-memory expects a positive byte count (3g, 512m, 1048576), `auto` or `none`",
                    );
                }
            },
            "--max-states" | "--max-depth" => match value().as_deref().map(search_limit) {
                Some(Ok(limit)) => {
                    if flag == "--max-states" {
                        req.max_states = limit;
                    } else {
                        req.max_depth = limit;
                    }
                }
                _ => {
                    return usage_error(
                        err,
                        &format!("{flag} expects a nonnegative integer or `none`"),
                    );
                }
            },
            // Hidden, test-only: randomized scheduling that must not change
            // any result (chaos mode).
            "--chaos" => match value().as_deref().map(str::parse::<u64>) {
                Some(Ok(seed)) => req.chaos = Some(seed),
                _ => return usage_error(err, "--chaos expects a 64-bit unsigned seed"),
            },
            "--library-path" | "--module-path" => match value() {
                Some(dir) if flag == "--library-path" => req.library_paths.push(dir.into()),
                Some(dir) => req.module_paths.push(dir.into()),
                None => return usage_error(err, &format!("{flag} expects a directory")),
            },
            s if s.starts_with('-') => {
                return usage_error(err, &format!("unknown option `{s}` for `dive check`"));
            }
            s => {
                if file.replace(s).is_some() {
                    return usage_error(err, "`dive check` takes one file");
                }
            }
        }
    }
    let Some(file) = file else {
        let _ = writeln!(err, "error: `dive check` needs a file\n\n{}", usage());
        return ExitCode::from(EXIT_USAGE);
    };
    if seen_extra && !seen_entries {
        return usage_error(
            err,
            "--seen-directory and seen limits require --seen-disk-entries",
        );
    }
    if seen_entries {
        if let Err(error) = seen_policy.limits.validate() {
            return usage_error(err, &error.to_string());
        }
        if final_check {
            return usage_error(
                err,
                "disk seen-state retention with temporal/capture is not implemented",
            );
        }
        req.seen_disk = Some(seen_policy);
    }
    if final_check != short_lasso {
        return usage_error(
            err,
            "bounded temporal checking needs --lncheck final and --lasso short",
        );
    }
    if req.candidate_directory.is_some() && req.candidate_memory_bytes.is_none() {
        return usage_error(
            err,
            "--candidate-directory requires --candidate-memory-bytes",
        );
    }
    if req.frontier_directory.is_some() && req.frontier_memory_bytes.is_none() {
        return usage_error(err, "--frontier-directory requires --frontier-memory-bytes");
    }
    if final_check && short_lasso {
        req.temporal_refusal = Some(FINAL_SHORT_REFUSAL.into());
    }
    if req.predecessor_directory.is_some() && req.predecessor_memory_bytes.is_none() {
        return usage_error(
            err,
            "--predecessor-directory requires --predecessor-memory-bytes",
        );
    }
    let checkpoint = match (checkpoint_path, recover_path, checkpoint_after) {
        (Some(path), None, Some(n)) => Some(dive_api::checkpoint::Request {
            path,
            action: dive_api::checkpoint::Action::PauseAfterLevels(n),
            counters: checkpoint_counters,
            config_source_sha256: None,
        }),
        (None, Some(path), None) => Some(dive_api::checkpoint::Request {
            path,
            action: dive_api::checkpoint::Action::Recover,
            counters: checkpoint_counters,
            config_source_sha256: None,
        }),
        (None, None, None) if !counters_given => None,
        _ => {
            return usage_error(
                err,
                "use --checkpoint FILE --checkpoint-after-levels N or --recover FILE, exclusively",
            );
        }
    };
    req.file = file.into();
    if worker_mode {
        if checkpoint.is_some() {
            return usage_error(
                err,
                "worker command requires pure Core roles without checkpoint/recovery",
            );
        }
        let Some(key) = worker_key else {
            return usage_error(err, "worker requires --worker-key FILE");
        };
        let worker = match dive_api::prepare_core_worker(&req, &key, worker_timeout) {
            Ok(worker) => worker,
            Err(error) => {
                let _ = writeln!(err, "{error}");
                return ExitCode::from(EXIT_UNSUPPORTED);
            }
        };
        let Some(address) = worker_listen else {
            return usage_error(err, "missing worker listener");
        };
        let listener = match std::net::TcpListener::bind(address) {
            Ok(listener) => listener,
            Err(error) => {
                let _ = writeln!(err, "worker listener: {error}");
                return ExitCode::from(EXIT_USAGE);
            }
        };
        let address = match listener.local_addr() {
            Ok(address) => address,
            Err(error) => {
                let _ = writeln!(err, "worker address: {error}");
                return ExitCode::from(EXIT_USAGE);
            }
        };
        if json {
            let _ = writeln!(
                out,
                "{}",
                serde_json::json!({"command":"worker","status":"ready","address":address.to_string(),"process_id":std::process::id(),"model_proved":false})
            );
        } else {
            let _ = writeln!(out, "native worker ready on {address}");
        }
        let _ = out.flush();
        return match worker.serve(&listener, worker_max_units, &|| false) {
            Ok(facts) => {
                if json {
                    let _ = writeln!(
                        out,
                        "{}",
                        serde_json::json!({"command":"worker","status":"stopped","work":facts,"model_proved":false})
                    );
                }
                ExitCode::SUCCESS
            }
            Err(error) => {
                let _ = writeln!(err, "{error}");
                ExitCode::from(EXIT_UNSUPPORTED)
            }
        };
    }
    if !remote_workers.is_empty() {
        let distinct: std::collections::HashSet<_> = remote_workers.iter().collect();
        if distinct.len() != remote_workers.len() {
            return usage_error(err, "--distributed-worker endpoints must be distinct");
        }
        if !(2..=64).contains(&remote_workers.len()) {
            return usage_error(
                err,
                "distributed safety requires 2..64 --distributed-worker endpoints",
            );
        }
        let Some(key) = worker_key else {
            return usage_error(err, "distributed safety requires --worker-key FILE");
        };
        let mut options = dive_api::DistributedOptions::new(remote_workers, key);
        options.timeout = worker_timeout;
        options.retries = worker_retries;
        req.distributed = Some(options);
    } else if worker_key.is_some() || worker_timeout_given || worker_retries_given {
        return usage_error(
            err,
            "worker key/timeout/retry options require worker mode or --distributed-worker endpoints",
        );
    }
    let checked = if let Some(request) = &checkpoint {
        dive_api::check_file_checkpoint(&req, request)
    } else {
        dive_api::check_file(&req)
    };
    let report = match checked {
        Ok(r) => r,
        Err(dive_api::ApiError::BudgetStartup(error)) => {
            let _ = writeln!(err, "{error}; no verdict produced");
            return ExitCode::from(4);
        }
        Err(dive_api::ApiError::BudgetMeasurement(error)) => {
            let _ = writeln!(err, "{error}; no verdict produced");
            return ExitCode::from(4);
        }
        Err(e @ dive_api::ApiError::Unsupported { .. }) => {
            let _ = writeln!(err, "{e}; no verdict produced");
            return ExitCode::from(EXIT_UNSUPPORTED);
        }
        Err(e) => {
            let _ = writeln!(err, "error: {e}");
            return ExitCode::from(EXIT_USAGE);
        }
    };
    if json {
        let _ = writeln!(
            out,
            "{}",
            report.to_json_with_exit_convention(exit_convention)
        );
    } else {
        let _ = write!(
            out,
            "{}",
            report.render_human_with_exit_convention(exit_convention)
        );
    }
    ExitCode::from(report.exit_code_for(exit_convention))
}

/// `dive validate-trace <file> --trace <trace.json> [--config cfg] [--claim ENDING]
/// [--compat=tlc] [--seed N] [--fp N] [--deadlock] [--output human|json] [--library-path DIR]... [--module-path DIR]...`.
///
/// Validates a counterexample or behavior against the specification with
/// the independent trace validator. The trace is in dive's format
/// or TLC's `-dumpTrace json` (which needs `--claim`, e.g.
/// `invariant:Inv`). `--seed` (and `--fp`) give the checking run's seed and
/// polynomial, so that random draws are replayed. Exit status: 0 valid, 1 invalid (or the specification
/// is rejected), 2 usage or unreadable input, 3 unsupported.
#[allow(
    clippy::too_many_lines,
    reason = "one command: its options, then loading, validating and reporting"
)]
fn validate_trace_command(
    args: &[String],
    out: &mut impl std::io::Write,
    err: &mut impl std::io::Write,
) -> ExitCode {
    let mut file: Option<&str> = None;
    let mut cfg: Option<&str> = None;
    let mut trace: Option<&str> = None;
    let mut input_report: Option<&str> = None;
    let mut claim: Option<&str> = None;
    let mut json = false;
    let mut sample = false;
    let mut seed: Option<i64> = None;
    let mut fp: Option<usize> = None;
    let mut opts = dive_api::trace::TraceOptions {
        compat_tlc: std::env::var("DIVE_COMPAT").is_ok_and(|v| v == "tlc"),
        ..Default::default()
    };
    let mut it = args.iter();
    let usage_error = |err: &mut dyn std::io::Write, msg: &str| {
        let _ = writeln!(err, "error: {msg}");
        ExitCode::from(EXIT_USAGE)
    };
    while let Some(a) = it.next() {
        match a.as_str() {
            "--sample" => sample = true,
            "--output" => match it.next().map(String::as_str) {
                Some("json") => json = true,
                Some("human") => json = false,
                other => {
                    return usage_error(
                        err,
                        &format!(
                            "--output expects `human` or `json`, got {}",
                            other.unwrap_or("nothing")
                        ),
                    );
                }
            },
            "--config" | "--trace" | "--claim" | "--inputs" => {
                let Some(v) = it.next() else {
                    return usage_error(err, &format!("{a} expects a value"));
                };
                let slot = match a.as_str() {
                    "--config" => &mut cfg,
                    "--trace" => &mut trace,
                    "--inputs" => &mut input_report,
                    _ => &mut claim,
                };
                if slot.replace(v).is_some() {
                    return usage_error(err, &format!("{a} given twice"));
                }
            }
            "--compat=tlc" => opts.compat_tlc = true,
            "--compat=dive" => opts.compat_tlc = false,
            "--compat" => match it.next().map(String::as_str) {
                Some("tlc") => opts.compat_tlc = true,
                Some("dive") => opts.compat_tlc = false,
                _ => return usage_error(err, "--compat expects `tlc` or `dive`"),
            },
            "--symmetry-liveness" => {
                let Some(policy) = it.next().and_then(|v| symmetry_liveness(v)) else {
                    return usage_error(
                        err,
                        "--symmetry-liveness expects unreduced, refuse or tlc",
                    );
                };
                opts.symmetry_liveness = Some(policy);
            }
            s if s.starts_with("--symmetry-liveness=") => {
                let Some(policy) = s
                    .strip_prefix("--symmetry-liveness=")
                    .and_then(symmetry_liveness)
                else {
                    return usage_error(
                        err,
                        "--symmetry-liveness expects unreduced, refuse or tlc",
                    );
                };
                opts.symmetry_liveness = Some(policy);
            }
            "--deadlock" | "-deadlock" => opts.no_deadlock = true,
            "--seed" | "-seed" => match it.next().and_then(|v| dive_api::parse_seed(v)) {
                Some(s) => seed = Some(s),
                None => return usage_error(err, "--seed expects a 64-bit integer"),
            },
            "--fp" | "-fp" => match it.next().and_then(|v| v.parse::<usize>().ok()) {
                Some(n) if n < 131 => fp = Some(n),
                _ => return usage_error(err, "--fp expects a polynomial index from 0 to 130"),
            },
            "--library-path" | "--module-path" => {
                let Some(dir) = it.next() else {
                    return usage_error(err, &format!("{a} expects a directory"));
                };
                if a == "--library-path" {
                    opts.library_paths.push(dir.into());
                } else {
                    opts.module_paths.push(dir.into());
                }
            }
            s if s.starts_with('-') => {
                return usage_error(
                    err,
                    &format!("unknown option `{s}` for `dive validate-trace`"),
                );
            }
            s => {
                if file.replace(s).is_some() {
                    return usage_error(err, "`dive validate-trace` takes one specification");
                }
            }
        }
    }
    let Some(file) = file else {
        return usage_error(
            err,
            &format!(
                "`dive validate-trace` needs a specification and --trace or --inputs\n\n{}",
                usage()
            ),
        );
    };
    let input_document = if let Some(path) = input_report {
        let report = match read_external_input_report(path) {
            Ok(report) => report,
            Err(message) => return usage_error(err, &message),
        };
        opts.inputs = match dive_api::host_inputs::inputs_from_report(&report) {
            Ok(inputs) => Some(inputs),
            Err(error) => return usage_error(err, &error.to_string()),
        };
        Some(report)
    } else {
        None
    };
    // The checking run's seed and polynomial, as `dive check` chose them:
    // without `--fp`, TLC's (under --compat=tlc) is derived from the seed.
    opts.run = match (seed, fp) {
        (Some(s), fp) => Some((
            s,
            fp.unwrap_or_else(|| {
                if opts.compat_tlc {
                    usize::try_from(s.unsigned_abs() % 131).unwrap_or(0)
                } else {
                    0
                }
            }),
        )),
        (None, Some(_)) => return usage_error(err, "--fp needs --seed"),
        (None, None) => None,
    };
    let spec = std::path::Path::new(file);
    // TLC's default: the configuration next to the specification.
    let cfg = cfg.map_or_else(|| spec.with_extension("cfg"), std::path::PathBuf::from);
    let document = if let Some(trace) = trace {
        let text = match std::fs::read_to_string(trace) {
            Ok(text) => text,
            Err(error) => return usage_error(err, &format!("cannot read {trace}: {error}")),
        };
        match serde_json::from_str(&text) {
            Ok(document) => document,
            Err(error) => return usage_error(err, &format!("{trace}: {error}")),
        }
    } else if let Some(report) = &input_document {
        report["counterexample"]["trace"].clone()
    } else {
        return usage_error(
            err,
            "validate-trace requires --trace or a check report supplied by --inputs",
        );
    };
    let mut doc = match dive_api::trace::TraceDoc::from_json(&document) {
        Ok(d) => d,
        Err(e) => return usage_error(err, &e),
    };
    if let Some(c) = claim {
        let ending = match dive_api::trace::Ending::parse(c) {
            Ok(e) => e,
            Err(e) => return usage_error(err, &format!("--claim: {e}")),
        };
        if doc.ending.as_ref().is_some_and(|d| *d != ending) {
            return usage_error(err, "--claim contradicts the trace's own `ending`");
        }
        doc = doc.with_ending(ending);
    }
    let model = match dive_api::trace::SpecModel::load(spec, &cfg, &opts) {
        Ok(m) => m,
        Err(e @ dive_api::ApiError::Unsupported { .. }) => {
            let _ = writeln!(err, "{e}; no result produced");
            return ExitCode::from(EXIT_UNSUPPORTED);
        }
        Err(e @ dive_api::ApiError::Rejected { .. }) => {
            let _ = writeln!(err, "error: {e}");
            return ExitCode::from(EXIT_REJECTED);
        }
        Err(e) => return usage_error(err, &e.to_string()),
    };
    let report = match if sample {
        model.try_validate_sample(&doc)
    } else {
        model.try_validate(&doc)
    } {
        Ok(report) => report,
        Err(error) => return validation_exception(out, err, &error, json),
    };
    if json {
        let mut document = dive_api::trace::report_json(&report);
        if sample {
            document["validation_goal"] = serde_json::json!("sample");
        }
        let _ = writeln!(out, "{document}");
    } else {
        let _ = write!(out, "{}", dive_api::trace::render_report(&report));
    }
    match report.validation {
        dive_api::trace::Validation::Valid => ExitCode::SUCCESS,
        dive_api::trace::Validation::Unsupported(_) => ExitCode::from(EXIT_UNSUPPORTED),
        // Invalid, or any other result that is not a validation.
        _ => ExitCode::from(EXIT_REJECTED),
    }
}

fn read_external_input_report(path: &str) -> Result<serde_json::Value, String> {
    const LIMIT: usize = 8 << 20;
    let file = std::fs::File::open(path).map_err(|error| format!("cannot read {path}: {error}"))?;
    let mut reader = std::io::Read::take(file, u64::try_from(LIMIT + 1).unwrap_or(u64::MAX));
    let mut bytes = Vec::new();
    std::io::Read::read_to_end(&mut reader, &mut bytes)
        .map_err(|error| format!("cannot read {path}: {error}"))?;
    if bytes.len() > LIMIT {
        return Err("external input report exceeds 8 MiB".into());
    }
    serde_json::from_slice(&bytes).map_err(|error| format!("{path}: {error}"))
}

fn validation_exception(
    out: &mut dyn std::io::Write,
    err: &mut dyn std::io::Write,
    error: &dive_api::trace::ValidationRunError,
    json: bool,
) -> ExitCode {
    use dive_api::trace::ValidationRunError;
    let (kind, progress, status) = match error {
        ValidationRunError::ResourceLimit { progress, .. } => {
            ("resource-limit", Some(progress), EXIT_UNSUPPORTED)
        }
        ValidationRunError::Interrupted { progress, .. } => ("interrupted", Some(progress), 5),
        ValidationRunError::EvaluationFailure { progress, .. }
        | ValidationRunError::BindingFailure { progress, .. } => {
            ("execution-error", Some(progress), 4)
        }
        // A thread failure, a control conflict, or any other failure without
        // validation progress.
        _ => ("execution-error", None, 4),
    };
    if json {
        let progress=progress.map(|progress|serde_json::json!({"checks_passed":progress.checks_passed,"state":progress.state,"check":progress.check.map(dive_api::trace::Check::name)}));
        let _ = writeln!(
            out,
            "{}",
            serde_json::json!({"schema_version":dive_api::REPORT_SCHEMA_VERSION,"command":"validate-trace","validation_completed":false,"error":{"kind":kind,"phase":"validation","message":error.to_string(),"progress":progress}})
        );
    } else {
        let _ = writeln!(
            err,
            "{error}; validation did not complete; no validation verdict produced"
        );
    }
    ExitCode::from(status)
}

fn simulation_usage_error(err: &mut impl std::io::Write, message: &str) -> ExitCode {
    let _ = writeln!(err, "error: {message}");
    ExitCode::from(EXIT_USAGE)
}

/// Finite seeded simulation, with explicit sampling metadata.
#[allow(
    clippy::too_many_lines,
    reason = "one command parser keeps finite sampling options and explicit refusals together"
)]
fn simulate_command(
    args: &[String],
    out: &mut impl std::io::Write,
    err: &mut impl std::io::Write,
) -> ExitCode {
    let mut request = dive_api::SimulateRequest {
        compat_tlc: std::env::var("DIVE_COMPAT").is_ok_and(|s| s == "tlc"),
        ..Default::default()
    };
    if let Err(message) = engine_from_env() {
        return simulation_usage_error(err, &message);
    }
    let mut json = false;
    let mut exit_convention = None;
    let mut file = None;
    let mut it = args.iter();
    while let Some(arg) = it.next() {
        match arg.as_str() {
            s if matches!(
                s.split('=').next(),
                Some("--predecessor-memory-bytes" | "--predecessor-directory")
            ) =>
            {
                let _ = writeln!(err, "predecessor spill with simulation is not implemented");
                return ExitCode::from(EXIT_UNSUPPORTED);
            }
            "--compat=tlc" => request.compat_tlc = true,
            value if value.starts_with("--time-limit=") => match time_limit(&value[13..]) {
                Some(setting) => request.time_limit = setting,
                None => {
                    return simulation_usage_error(
                        err,
                        "--time-limit expects a positive duration or none",
                    );
                }
            },
            value if value.starts_with("--max-memory=") => match max_memory(&value[13..]) {
                Some(setting) => request.max_memory = setting,
                None => {
                    return simulation_usage_error(
                        err,
                        "--max-memory expects a positive byte count, auto or none",
                    );
                }
            },
            "--time-limit" => match it.next().map(String::as_str).and_then(time_limit) {
                Some(setting) => request.time_limit = setting,
                None => {
                    return simulation_usage_error(
                        err,
                        "--time-limit expects a positive duration or none",
                    );
                }
            },
            "--max-memory" => match it.next().map(String::as_str).and_then(max_memory) {
                Some(setting) => request.max_memory = setting,
                None => {
                    return simulation_usage_error(
                        err,
                        "--max-memory expects a positive byte count, auto or none",
                    );
                }
            },
            "--engine" => {
                if let Err(message) = engine_option(it.next().map(String::as_str)) {
                    return simulation_usage_error(err, &message);
                }
            }
            name if name.starts_with("--engine=") => {
                if let Err(message) = engine_option(Some(&name[9..])) {
                    return simulation_usage_error(err, &message);
                }
            }
            "--config" => {
                let Some(value) = it.next() else {
                    return simulation_usage_error(err, "--config expects a path");
                };
                if request.config.replace(value.into()).is_some() {
                    return simulation_usage_error(err, "--config given twice");
                }
            }
            "--seed" => {
                let Some(value) = it.next() else {
                    return simulation_usage_error(err, "--seed expects an integer");
                };
                let Some(seed) = dive_api::parse_seed(value) else {
                    return simulation_usage_error(err, "invalid --seed");
                };
                if request.seed.replace(seed).is_some() {
                    return simulation_usage_error(err, "--seed given twice");
                }
            }
            "--aril" | "--depth" | "--traces" | "--workers" => {
                let Some(value) = it.next() else {
                    return simulation_usage_error(
                        err,
                        "simulation numeric option expects an integer",
                    );
                };
                let Ok(number) = value.parse::<u64>() else {
                    return simulation_usage_error(
                        err,
                        "simulation option must be a nonnegative integer",
                    );
                };
                match arg.as_str() {
                    "--aril" => request.aril = number,
                    "--traces" => request.traces = number,
                    "--depth" => {
                        let Ok(number) = usize::try_from(number) else {
                            return simulation_usage_error(err, "depth exceeds addressable range");
                        };
                        request.depth = Some(number);
                    }
                    _ => {
                        let Ok(number) = usize::try_from(number) else {
                            return simulation_usage_error(
                                err,
                                "worker count exceeds addressable range",
                            );
                        };
                        if number == 0 {
                            return simulation_usage_error(
                                err,
                                "simulation workers must be positive",
                            );
                        }
                        request.workers = Some(number);
                    }
                }
            }
            "--exit-codes" => {
                exit_convention = Some(match it.next().map(String::as_str) {
                    Some("native") => dive_api::ExitConvention::Native,
                    Some("tlc") => dive_api::ExitConvention::Tlc,
                    _ => return simulation_usage_error(err, "--exit-codes expects native or tlc"),
                });
            }
            "--stats" => match it.next().map(String::as_str) {
                Some("basic") => request.action_stats = true,
                Some("none") => request.action_stats = false,
                Some("full") => {
                    let _ = writeln!(err, "unsupported: simulation full action statistics");
                    return ExitCode::from(EXIT_UNSUPPORTED);
                }
                _ => return simulation_usage_error(err, "--stats expects none or basic"),
            },
            "-deadlock" => request.no_deadlock = true,
            "--output" => match it.next().map(String::as_str) {
                Some("json") => json = true,
                Some("human") => json = false,
                _ => return simulation_usage_error(err, "--output expects human or json"),
            },
            "--library-path" | "--module-path" => {
                let Some(path) = it.next() else {
                    return simulation_usage_error(err, "module option expects a path");
                };
                if arg == "--library-path" {
                    request.library_paths.push(path.into());
                } else {
                    request.module_paths.push(path.into());
                }
            }
            "--generate" => request.generation = true,
            "--continue"
            | "--probabilistic"
            | "--rl"
            | "--distributed"
            | "--frontier-memory-bytes"
            | "--store-compact-bytes"
            | "--frontier-directory" => {
                let _ = writeln!(err, "unsupported: simulation {arg}; no result produced");
                return ExitCode::from(EXIT_UNSUPPORTED);
            }
            value if value.starts_with('-') => {
                return simulation_usage_error(err, &format!("unknown simulation option {value}"));
            }
            value => {
                if file.replace(value).is_some() {
                    return simulation_usage_error(err, "simulate takes one specification file");
                }
            }
        }
    }
    let Some(file) = file else {
        return simulation_usage_error(err, "simulate needs a specification file and --traces N");
    };
    if request.traces == 0 {
        return simulation_usage_error(err, "simulate requires a positive finite --traces N");
    }
    request.file = file.into();
    let report = match dive_api::simulate_file(&request) {
        Ok(report) => report,
        Err(dive_api::ApiError::Unsupported { feature }) => {
            let _ = writeln!(err, "unsupported: {feature}; no result produced");
            return ExitCode::from(EXIT_UNSUPPORTED);
        }
        Err(
            error @ (dive_api::ApiError::BudgetStartup(_)
            | dive_api::ApiError::BudgetMeasurement(_)),
        ) => {
            let _ = writeln!(err, "{error}; no result produced");
            return ExitCode::from(4);
        }
        Err(error) => {
            let _ = writeln!(err, "error: {error}");
            return ExitCode::from(EXIT_REJECTED);
        }
    };
    if json {
        let document = exit_convention.map_or_else(
            || report.to_json(),
            |convention| report.to_json_with_exit_convention(convention),
        );
        let _ = writeln!(out, "{document}");
    } else {
        let _ = write!(out, "{}", report.render_human());
    }
    ExitCode::from(exit_convention.map_or_else(
        || report.exit_code(),
        |convention| report.exit_code_for(convention),
    ))
}

/// Runs the native bounded iterative mode; unknown mode flags refuse by name.
#[allow(
    clippy::too_many_lines,
    reason = "explicit CLI options and typed validation"
)]
fn dfid_command(
    args: &[String],
    out: &mut impl std::io::Write,
    err: &mut impl std::io::Write,
) -> ExitCode {
    let mut req = dive_api::DfidRequest {
        compat_tlc: std::env::var("DIVE_COMPAT").is_ok_and(|v| v == "tlc"),
        ..dive_api::DfidRequest::default()
    };
    if let Err(message) = engine_from_env() {
        let _ = writeln!(err, "error: {message}");
        return ExitCode::from(EXIT_USAGE);
    }
    let mut json = false;
    let mut has_depth = false;
    let mut file = None;
    let mut it = args.iter();
    let usage_error = |err: &mut dyn std::io::Write, text: &str| {
        let _ = writeln!(err, "error: {text}");
        ExitCode::from(EXIT_USAGE)
    };
    while let Some(arg) = it.next() {
        let (flag, inline) = match arg.split_once('=') {
            Some((f, v)) if f.starts_with('-') => (f, Some(v.to_owned())),
            _ => (arg.as_str(), None),
        };
        let mut value = || inline.clone().or_else(|| it.next().cloned());
        match flag {
            "--predecessor-memory-bytes" | "--predecessor-directory" => {
                let _ = writeln!(err, "predecessor spill with DFID is not implemented");
                return ExitCode::from(EXIT_UNSUPPORTED);
            }
            "--output" => match value().as_deref() {
                Some("json") => json = true,
                Some("human") => json = false,
                _ => return usage_error(err, "--output expects human or json"),
            },
            "--compat" => match value().as_deref() {
                Some("tlc") => req.compat_tlc = true,
                Some("dive" | "none") => req.compat_tlc = false,
                _ => return usage_error(err, "--compat expects tlc or dive"),
            },
            "--engine" => {
                if let Err(message) = engine_option(value().as_deref()) {
                    return usage_error(err, &message);
                }
            }
            "--config" | "-config" => match value() {
                Some(v) => req.config = Some(v.into()),
                None => return usage_error(err, "--config expects a cfg file"),
            },
            "--max-level" | "--dfid" | "-dfid" => match value().and_then(|v| v.parse().ok()) {
                Some(n) => {
                    req.max_level = n;
                    has_depth = true;
                }
                None => return usage_error(err, "--max-level expects an unsigned integer"),
            },
            "--seed" | "-seed" => match value().as_deref().and_then(dive_api::parse_seed) {
                Some(seed) => req.seed = Some(seed),
                None => return usage_error(err, "--seed expects a 64-bit seed"),
            },
            "--worker-seeds" => match value().map(|v| {
                v.split(',')
                    .map(dive_api::parse_seed)
                    .collect::<Option<Vec<_>>>()
            }) {
                Some(Some(seeds)) if !seeds.is_empty() => req.worker_seeds = Some(seeds),
                _ => {
                    return usage_error(err, "--worker-seeds expects comma separated 64-bit seeds");
                }
            },
            "--workers" | "-workers" => match value().and_then(|v| v.parse().ok()) {
                Some(n) => req.workers = Some(n),
                None => return usage_error(err, "--workers expects an unsigned integer"),
            },
            "--fp" | "-fp" => match value().and_then(|v| v.parse::<usize>().ok()) {
                Some(n) if n < 131 => req.fp = n,
                _ => return usage_error(err, "--fp expects 0..130"),
            },
            "--time-limit" => match value().as_deref().and_then(time_limit) {
                Some(setting) => req.time_limit = setting,
                None => {
                    return usage_error(err, "--time-limit expects a positive duration or none");
                }
            },
            "--max-memory" => match value().as_deref().and_then(max_memory) {
                Some(setting) => req.max_memory = setting,
                None => {
                    return usage_error(
                        err,
                        "--max-memory expects a positive byte count, auto or none",
                    );
                }
            },
            "--store" => match value().as_deref() {
                Some("exact") => req.exact = true,
                Some("fp" | "fingerprint") => req.exact = false,
                _ => return usage_error(err, "--store expects fp or exact"),
            },
            "--library-path" => match value() {
                Some(v) => req.library_paths.push(v.into()),
                None => return usage_error(err, "--library-path expects a directory"),
            },
            "--module-path" => match value() {
                Some(v) => req.module_paths.push(v.into()),
                None => return usage_error(err, "--module-path expects a directory"),
            },
            "-deadlock" | "--no-deadlock" => req.no_deadlock = true,
            s if s.starts_with('-') => {
                let _ = writeln!(err, "unsupported DFID option: {s}; no checking performed");
                return ExitCode::from(EXIT_UNSUPPORTED);
            }
            s => {
                if file.replace(s).is_some() {
                    return usage_error(err, "dfid takes one specification file");
                }
            }
        }
    }
    let Some(file) = file else {
        return usage_error(err, "dfid requires a specification and --max-level N");
    };
    if !has_depth {
        return usage_error(err, "dfid requires explicit --max-level N");
    }
    req.file = file.into();
    let report = match dive_api::dfid_file(&req) {
        Ok(r) => r,
        Err(
            error @ (dive_api::ApiError::BudgetStartup(_)
            | dive_api::ApiError::BudgetMeasurement(_)),
        ) => {
            let _ = writeln!(err, "{error}; no result produced");
            return ExitCode::from(4);
        }
        Err(e) => {
            let _ = writeln!(err, "{e}");
            return ExitCode::from(EXIT_USAGE);
        }
    };
    if json {
        let _ = writeln!(out, "{}", report.to_json());
    } else {
        let _ = write!(out, "{}", report.render_human());
    }
    ExitCode::from(report.exit_status())
}

/// Runs the shared CLI, including an executable whose basename is `tlc`.
///
/// Both installed binaries use this entrypoint; native command defaults remain
/// independent from the TLC checking adapter.
///
/// ```no_run
/// let status = dive_cli::main();
/// # let _ = status;
/// ```
#[must_use]
pub fn main() -> ExitCode {
    let mut arguments = std::env::args_os();
    let shim = arguments.next().is_some_and(|executable| {
        std::path::Path::new(&executable)
            .file_name()
            .is_some_and(|name| name == "tlc" || name == "tlc.exe")
    });
    let arguments: Vec<_> = arguments.collect();
    let adapter = shim || arguments.first().is_some_and(|argument| argument == "tlc");
    let args = arguments
        .into_iter()
        .map(std::ffi::OsString::into_string)
        .collect::<Result<Vec<_>, _>>();
    let mut stdout = std::io::stdout().lock();
    let mut stderr = std::io::stderr().lock();
    let Ok(args) = args else {
        let _ = writeln!(stderr, "DIVE-X0001: command arguments must be valid UTF-8");
        return ExitCode::from(if adapter { 1 } else { EXIT_USAGE });
    };
    if shim {
        return tlc::command(&args, &mut stdout, &mut stderr);
    }
    if let Some((command, arguments)) = args.split_first()
        && arguments
            .iter()
            .any(|argument| matches!(argument.as_str(), "-h" | "--help"))
        && let Some(help) = help::command(command)
    {
        let _ = write!(stdout, "{help}");
        return ExitCode::SUCCESS;
    }
    // Write failures (e.g. a closed pipe) are not actionable here.
    match args.first().map(String::as_str) {
        None | Some("-h" | "--help" | "help") => {
            let _ = write!(stdout, "{}", usage());
            ExitCode::SUCCESS
        }
        Some("-V" | "--version") => {
            let _ = writeln!(
                stdout,
                "dive {} ({})",
                env!("CARGO_PKG_VERSION"),
                env!("DIVE_GIT_DESCRIBE")
            );
            ExitCode::SUCCESS
        }
        Some("parse") => parse_command(&args[1..], &mut stdout, &mut stderr),
        Some("debug") => debug::command(&args[1..], &mut stdout, &mut stderr),
        Some("explain") => explain::command(&args[1..], &mut stdout, &mut stderr),
        Some("analyze") => analyze_command(&args[1..], &mut stdout, &mut stderr),
        Some("dfid") => dfid_command(&args[1..], &mut stdout, &mut stderr),
        Some("translate") => translate::command(&args[1..], &mut stdout, &mut stderr),
        Some("check") => check_command(&args[1..], &mut stdout, &mut stderr),
        Some("worker") => check_command_mode(&args[1..], &mut stdout, &mut stderr, true),
        Some("tlc") => tlc::command(&args[1..], &mut stdout, &mut stderr),
        Some("simulate") => simulate_command(&args[1..], &mut stdout, &mut stderr),
        Some("validate-trace") => validate_trace_command(&args[1..], &mut stdout, &mut stderr),
        Some(cmd @ "lsp") => {
            let _ = writeln!(
                stderr,
                "unsupported: `dive {cmd}` is not implemented yet; no verdict produced"
            );
            ExitCode::from(EXIT_UNSUPPORTED)
        }
        Some(other) => {
            let _ = write!(stderr, "error: unknown command `{other}`\n\n{}", usage());
            ExitCode::from(EXIT_USAGE)
        }
    }
}

#[cfg(test)]
mod predecessor_tests {
    use super::*;
    #[test]
    fn orphan_directory_and_other_modes_refuse_before_input_access() {
        let args = [
            "missing.tla".into(),
            "--predecessor-directory".into(),
            "missing-parent".into(),
        ];
        let mut output = Vec::new();
        let mut errors = Vec::new();
        assert_eq!(
            check_command(&args, &mut output, &mut errors),
            ExitCode::from(EXIT_USAGE)
        );
        assert!(String::from_utf8_lossy(&errors).contains("requires --predecessor-memory-bytes"));
        for flag in [
            "--predecessor-memory-bytes=0",
            "--predecessor-directory=missing",
        ] {
            errors.clear();
            assert_eq!(
                simulate_command(&[flag.into()], &mut output, &mut errors),
                ExitCode::from(EXIT_UNSUPPORTED)
            );
            assert!(String::from_utf8_lossy(&errors).contains("predecessor spill with simulation"));
            errors.clear();
            assert_eq!(
                dfid_command(&[flag.into()], &mut output, &mut errors),
                ExitCode::from(EXIT_UNSUPPORTED)
            );
            assert!(String::from_utf8_lossy(&errors).contains("predecessor spill with DFID"));
        }
        assert_eq!(output, [] as [u8; 0]);
    }
}

#[cfg(test)]
mod seen_tests {
    use super::*;
    #[test]
    fn malformed_or_orphan_disk_policy_refuses_before_reading_model() {
        for flags in [
            vec!["--seen-directory", "unused-parent"],
            vec!["--seen-key-bytes", "64"],
            vec!["--seen-probe-steps", "1"],
            vec!["--seen-summary-pairs", "0"],
            vec!["--seen-disk-entries", "0"],
            vec!["--seen-disk-entries", "4", "--seen-key-bytes", "0"],
            vec!["--seen-disk-entries", "4", "--seen-probe-steps", "0"],
            vec![
                "--seen-disk-entries",
                "4",
                "--lncheck",
                "final",
                "--lasso",
                "short",
            ],
        ] {
            let mut arguments = vec!["missing-seen-model.tla".to_owned()];
            arguments.extend(flags.iter().map(|s| (*s).to_owned()));
            let mut output = Vec::new();
            let mut errors = Vec::new();
            assert_eq!(
                check_command(&arguments, &mut output, &mut errors),
                ExitCode::from(EXIT_USAGE)
            );
            assert_eq!(output, [] as [u8; 0]);
            let error = String::from_utf8_lossy(&errors);
            assert!(!error.contains("cannot read"), "{error}");
            assert!(
                error.contains("--seen-directory and seen limits require --seen-disk-entries")
                    || error.contains("DIVE-S0700")
                    || error.contains("is not implemented"),
                "{error}"
            );
        }
    }
}

#[cfg(test)]
mod budget_tests {
    use super::*;
    use dive_api::BudgetSetting::{Default, Explicit, Unlimited};
    use std::time::Duration;

    #[test]
    fn time_limits_parse_units_and_none() {
        assert_eq!(time_limit("90"), Some(Explicit(Duration::from_secs(90))));
        assert_eq!(time_limit("90s"), Some(Explicit(Duration::from_secs(90))));
        assert_eq!(
            time_limit("500ms"),
            Some(Explicit(Duration::from_millis(500)))
        );
        assert_eq!(time_limit("10m"), Some(Explicit(Duration::from_secs(600))));
        assert_eq!(time_limit("2h"), Some(Explicit(Duration::from_secs(7200))));
        assert_eq!(time_limit("none"), Some(Unlimited));
        for bad in ["", "0", "-1", "1.5s", "10d", "s", "auto"] {
            assert_eq!(time_limit(bad), None, "{bad}");
        }
    }

    #[test]
    fn memory_ceilings_parse_jvm_units_auto_and_none() {
        assert_eq!(max_memory("3g"), Some(Explicit(3 << 30)));
        assert_eq!(max_memory("512M"), Some(Explicit(512 << 20)));
        assert_eq!(max_memory("1048576"), Some(Explicit(1 << 20)));
        assert_eq!(max_memory("auto"), Some(Default));
        assert_eq!(max_memory("none"), Some(Unlimited));
        for bad in ["", "0", "0g", "-1", "3gb", "1.5g", "99999999999t"] {
            assert_eq!(max_memory(bad), None, "{bad}");
        }
    }

    #[test]
    fn malformed_budgets_are_usage_errors_before_reading_the_model() {
        for flags in [
            ["--time-limit", "0"],
            ["--max-memory", "lots"],
            ["--max-states", "-1"],
            ["--max-depth", "1.5"],
        ] {
            let args: Vec<String> = std::iter::once("missing.tla")
                .chain(flags)
                .map(Into::into)
                .collect();
            let (mut output, mut errors) = (Vec::new(), Vec::new());
            assert_eq!(
                check_command(&args, &mut output, &mut errors),
                ExitCode::from(EXIT_USAGE)
            );
        }
    }

    #[test]
    fn finite_mode_budgets_validate_before_loading_and_report_memory_stops() {
        for simulation in [false, true] {
            for bad in [
                vec!["--time-limit", "0"],
                vec!["--max-memory", "lots"],
                vec!["--time-limit=0"],
                vec!["--max-memory=lots"],
            ] {
                let mut args = vec!["missing.tla".to_owned()];
                args.extend(bad.into_iter().map(str::to_owned));
                let (mut output, mut errors) = (Vec::new(), Vec::new());
                let status = if simulation {
                    simulate_command(&args, &mut output, &mut errors)
                } else {
                    dfid_command(&args, &mut output, &mut errors)
                };
                assert_eq!(status, ExitCode::from(EXIT_USAGE));
                assert_eq!(output, [] as [u8; 0]);
            }
            let file = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../../docs/user/examples/Counter.tla");
            for compat in [false, true] {
                for inline in [false, true] {
                    let mut args =
                        vec![file.display().to_string(), "--output".into(), "json".into()];
                    args.extend(if simulation {
                        vec!["--traces".into(), "1".into()]
                    } else {
                        vec!["--max-level".into(), "8".into()]
                    });
                    args.extend(if inline {
                        vec!["--max-memory=1".into()]
                    } else {
                        vec!["--max-memory".into(), "1".into()]
                    });
                    if compat {
                        args.push("--compat=tlc".into());
                    }
                    let (mut output, mut errors) = (Vec::new(), Vec::new());
                    let status = if simulation {
                        simulate_command(&args, &mut output, &mut errors)
                    } else {
                        dfid_command(&args, &mut output, &mut errors)
                    };
                    assert_eq!(
                        status,
                        ExitCode::from(5),
                        "{}",
                        String::from_utf8_lossy(&errors)
                    );
                    assert!(String::from_utf8_lossy(&output).contains("\"result\":\"stopped\""));
                }
            }
        }
    }

    #[test]
    fn finite_mode_engine_flags_reach_the_actual_compiled_backend() {
        let file = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../docs/user/examples/Counter.tla");
        for simulation in [false, true] {
            for inline in [false, true] {
                let mut args = vec![
                    file.display().to_string(),
                    "--output=json".into(),
                    "-deadlock".into(),
                    "--time-limit=none".into(),
                    "--max-memory=none".into(),
                ];
                if simulation {
                    args[1] = "--output".into();
                    args.insert(2, "json".into());
                }
                args.extend(if simulation {
                    vec!["--traces".into(), "1".into(), "--depth".into(), "2".into()]
                } else {
                    vec!["--max-level".into(), "8".into()]
                });
                args.extend(if inline {
                    vec!["--engine=core".into()]
                } else {
                    vec!["--engine".into(), "core".into()]
                });
                let (mut output, mut errors) = (Vec::new(), Vec::new());
                let status = if simulation {
                    simulate_command(&args, &mut output, &mut errors)
                } else {
                    dfid_command(&args, &mut output, &mut errors)
                };
                assert_eq!(
                    status,
                    ExitCode::SUCCESS,
                    "{}",
                    String::from_utf8_lossy(&errors)
                );
                assert!(String::from_utf8_lossy(&output).contains("\"engine\":\"core\""));
            }
        }
    }

    #[test]
    fn search_ceilings_parse_zero_exact_counts_and_none() {
        assert_eq!(search_limit("0"), Ok(Some(0)));
        assert_eq!(search_limit("42"), Ok(Some(42)));
        assert_eq!(search_limit("none"), Ok(None));
        for bad in ["", "-1", "1.5", "18446744073709551616", "auto"] {
            assert!(search_limit(bad).is_err(), "{bad}");
        }
    }
}

fn symmetry_liveness(value: &str) -> Option<dive_api::SymmetryLiveness> {
    match value {
        "unreduced" => Some(dive_api::SymmetryLiveness::Unreduced),
        "refuse" => Some(dive_api::SymmetryLiveness::Refuse),
        "tlc" => Some(dive_api::SymmetryLiveness::Tlc),
        _ => None,
    }
}

#[cfg(test)]
mod symmetry_liveness_tests {
    #![allow(clippy::expect_used, reason = "finite argument and report controls")]
    use super::*;
    fn arguments(args: &[&str]) -> Vec<String> {
        args.iter().map(|arg| (*arg).into()).collect()
    }
    #[test]
    fn unknown_modes_are_usage_errors_before_any_input_access() {
        for args in [
            arguments(&["Missing.tla", "--symmetry-liveness=unknown"]),
            arguments(&["--symmetry-liveness", "bad", "Missing.tla"]),
        ] {
            let mut out = Vec::new();
            let mut err = Vec::new();
            assert_eq!(
                check_command(&args, &mut out, &mut err),
                ExitCode::from(EXIT_USAGE)
            );
            assert!(String::from_utf8_lossy(&err).contains("--symmetry-liveness expects"));
            assert_eq!(out, [] as [u8; 0]);
            assert_eq!(
                validate_trace_command(&args, &mut out, &mut err),
                ExitCode::from(EXIT_USAGE)
            );
        }
    }
    #[test]
    fn explicit_mode_survives_native_profile_flag_order_and_adapter_transport() {
        let file = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../conformance/corpus/probes/specifications/P4SymLive/P4SymLive.tla");
        let file = file.to_str().expect("fixture path");
        for native in [true, false] {
            for reverse in [false, true] {
                let mut args = if native {
                    arguments(&[
                        file,
                        "--output=json",
                        "--workers=1",
                        "--seed=0",
                        "--fp=0",
                        "--max-memory=none",
                        "--time-limit=none",
                    ])
                } else {
                    arguments(&[
                        file,
                        "--output=json",
                        "--workers=1",
                        "--seed=0",
                        "--fp=0",
                        "--max-memory=none",
                    ])
                };
                let selection = if reverse {
                    ["--symmetry-liveness=unreduced", "--compat=tlc"]
                } else {
                    ["--compat=tlc", "--symmetry-liveness=unreduced"]
                };
                if native {
                    args.extend(arguments(&selection));
                } else {
                    args.push("--symmetry-liveness=unreduced".into());
                }
                let mut out = Vec::new();
                let mut err = Vec::new();
                let status = if native {
                    check_command(&args, &mut out, &mut err)
                } else {
                    tlc::command(&args, &mut out, &mut err)
                };
                assert_eq!(
                    status,
                    ExitCode::SUCCESS,
                    "{}",
                    String::from_utf8_lossy(&err)
                );
                let report: serde_json::Value = serde_json::from_slice(&out).expect("actual JSON");
                assert_eq!(report["options"]["profile"], "tlc+overrides");
                assert_eq!(report["options"]["symmetry_liveness"], "unreduced");
                assert_eq!(report["symmetry_liveness"]["scope"], "whole-run");
                assert_eq!(report["statistics"]["distinct"], 2);
            }
        }
    }
}

#[cfg(test)]
mod validation_exception_tests {
    #[test]
    fn aborted_validation_json_is_an_exception_without_a_result()
    -> Result<(), Box<dyn std::error::Error>> {
        let mut out = Vec::new();
        let mut err = Vec::new();
        let error = dive_api::trace::ValidationRunError::ThreadFailure(
            "test isolated thread did not return".into(),
        );
        let status = super::validation_exception(&mut out, &mut err, &error, true);
        assert_eq!(status, std::process::ExitCode::from(4));
        let value: serde_json::Value = serde_json::from_slice(&out)?;
        assert_eq!(value["schema_version"], 3);
        assert_eq!(value["command"], "validate-trace");
        assert_eq!(value["validation_completed"], false);
        assert_eq!(value["error"]["kind"], "execution-error");
        assert!(value.get("result").is_none());
        assert!(value.get("verdict").is_none());
        assert_eq!(err, [] as [u8; 0]);
        Ok(())
    }
}