blue-lang-cli 0.0.158

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

mod arika;
mod census;

/// `blue migrate`'s program: blue, over builtins only.
const MIGRATE: &str = include_str!("../blue/migrate.b");

const VERBS: &str = include_str!("../blue/verbs.b");
const REUSE: &str = include_str!("../blue/reuse.b");
mod config;
mod crash;
mod deploy;
mod diagnostics;
mod doc;
mod facts;
mod inputs;
mod memo;
mod observe;
mod prefetch;
mod query;
mod receipt;
mod reference;
mod registry;
mod repl;
mod replay;
mod scaffold;
mod script;
mod sigint;
mod source_lines;
mod test_cache;
mod watch;
mod witness;

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

use blue_lang_pkg::lock::{Freshness, LOCK_FILE};
use clap::{CommandFactory, Parser, Subcommand};

use config::BlueConfig;

/// Counts allocations per thread so `blue profile` can say what each
/// definition allocated; two thread-local additions per allocation.
#[global_allocator]
static ALLOC: blue_lang_runtime::alloc::Counting = blue_lang_runtime::alloc::Counting;

#[derive(Parser)]
#[command(
    name = "blue",
    version,
    about = "The blue language: a Ruby/Elixir surface on tatara-lisp and Rust."
)]
struct Cli {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// Parse, type-check, erase, and execute a program.
    Run {
        file: PathBuf,
        /// Supply a build input: `--input name=path`.
        ///
        /// The program must also `definput(name, "b3:…")`; the bytes are
        /// verified against that hash before any macro can read them. A
        /// mismatch is refused — see `blue_lang_runtime::inputs`.
        #[arg(long = "input", value_name = "NAME=PATH")]
        inputs: Vec<String>,
        /// Hold the run to these host capabilities: `none`, `host`, or one of
        /// `process`, `filesystem`, `environment`, `clock`, `network`,
        /// `entropy`. Repeatable. A host name the file writes outside them
        /// refuses the program before it runs; one reached through a bidama
        /// or a process is refused where it is called. Without the flag the
        /// run has every capability. A script states it in its shebang:
        /// `#!/usr/bin/env -S blue --allow filesystem`.
        #[arg(long = "allow", value_name = "CAPABILITY")]
        allow: Vec<String>,
        /// Write an execution receipt into DIR for the run and for each
        /// process when an incarnation ends: the definition's `def_hash`, the
        /// frame (granted, provided, withheld), the exit, and the host calls
        /// made through granted names. Each is canonical JSON named by the
        /// BLAKE3 hash of its bytes; `blue receipt verify` checks one.
        #[arg(long, value_name = "DIR")]
        receipts: Option<PathBuf>,
        /// With `--receipts`, each receipt also counts the steps its run or
        /// incarnation spent: `blue-receipt` version 3. Off by default, since
        /// a count moves with the code blue emits and so renames the receipt;
        /// the call memo is off under it, so the count is the evaluation's.
        #[arg(long, requires = "receipts")]
        receipt_steps: bool,
        /// Do not print the program's final value. An installed command's
        /// output is what it writes (`write_stdout`), not the value its last
        /// expression happens to leave; `mkBlueApp` passes this, so a blue
        /// executable on PATH never ends its output with a stray `nil`.
        #[arg(long, short = 'q')]
        quiet: bool,
        /// `json` prints a runtime error as one JSON object on stdout, with
        /// its position and blue call stack.
        #[arg(long, value_enum, default_value_t = Format::Text)]
        format: Format,
        /// Print the wall time of each pipeline stage to stderr after the run.
        #[arg(long)]
        timings: bool,
        /// Run every call, answering none from the memo `BLUE_MEMO` turns on.
        #[arg(long)]
        no_memo: bool,
        /// The program's own arguments, after the file (use `--` before any
        /// that start with a dash): what `argv()` returns. Before 2026-09-27
        /// `run` refused any, so no blue program could take arguments.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Format a program. There is one formatting; this produces it.
    ///
    /// Several files may be named with `--check` or `--write`: each is
    /// reported, and the exit is non-zero if any drifted or was refused. That
    /// is what lets a gate hold a whole tree canonical in ONE command
    /// (`mkFmtCheck`, and `mkBidama`'s own build) rather than in a loop.
    Fmt {
        #[arg(required = true)]
        file: Vec<PathBuf>,
        /// Report drift and exit non-zero instead of rewriting.
        #[arg(long)]
        check: bool,
        /// Rewrite the file in place.
        #[arg(long)]
        write: bool,
    },
    /// Print the tatara-lisp form, annotations intact.
    ///
    /// `--resolved` prints the RESOLVED tree instead: every definition renamed
    /// to its runtime key (`retsu/first`, `%root/f` for a script) and every
    /// reference to what per-bidama namespaces bind it to (a builtin stays
    /// bare). `--json` adds, per reference, what today's flat rule and the
    /// namespace rule each bind it to — the data a migration is proven on.
    /// `--lines` wraps each statement of the resolved tree as `(%line LINE COLUMN
    /// form)`, what a compiler that names source lines reads.
    Ast {
        file: PathBuf,
        #[arg(long)]
        resolved: bool,
        #[arg(long, requires = "resolved")]
        json: bool,
        #[arg(long, requires = "resolved")]
        lines: bool,
    },
    /// Print the tatara-lisp form after type erasure — what actually runs.
    Erase { file: PathBuf },
    /// Check a program against every rule in the registry — unbound names,
    /// unused bindings, types, waivers — and report the typing analysis.
    ///
    /// Like `run` and `test`, this compiles only canonical source and writes
    /// nothing: a file that is not canonically formatted is refused, naming
    /// `blue fmt --write`. Only `--fix` writes. A loaded dependency's form is
    /// its producer's (`BLUE_FORM`, docs/COMPOUNDING.md).
    ///
    /// Exits non-zero when any error-severity diagnostic remains. Test blocks
    /// are checked too. `blue explain CODE` says what a code means.
    Check {
        #[arg(required_unless_present = "hook")]
        file: Option<PathBuf>,
        #[arg(
            long,
            conflicts_with_all = ["fix", "only"],
            help = "Print only each B0070 in FILE, with the word to use and its import line, one per line, and exit 0"
        )]
        reuse: bool,
        #[arg(
            long,
            requires = "reuse",
            help = "With --reuse: read Claude Code's PostToolUse JSON from stdin instead of FILE, take tool_input.file_path, stay silent unless it ends in .b and exists, and always exit 0"
        )]
        hook: bool,
        /// `text` for people; `json` prints one JSON object per diagnostic
        /// per line on stdout (JSON Lines). The fields are documented in
        /// docs/DIAGNOSTICS.md and are stable.
        #[arg(long, value_enum, default_value_t = Format::Text)]
        format: Format,
        /// Apply every machine-applicable fix to the file, re-format it, and
        /// check again. Suggestions marked maybe-incorrect are never applied.
        #[arg(long)]
        fix: bool,
        /// With `--fix`: apply only these codes' machine fixes, to the file
        /// as written, with no re-format and no Bluefile edit. A project
        /// pinned to an older blue takes one rule's fix from this blue and
        /// formats with its own (`blue check --fix --only B0062 FILE`).
        #[arg(long, requires = "fix", value_name = "CODE")]
        only: Vec<String>,
    },
    /// Every definition under PATH (files, or directories of `.b` files; `.`
    /// when none) that satisfies QUERY, one line per hit:
    /// `file:line:col: definition  name = value…`.
    ///
    /// QUERY is tatara-lisp data, or the name of a `query(name, …)` in the
    /// Bluefile of this directory or above. Several clauses are their
    /// conjunction: (match PATTERN) (reaches CAP) (annotated) (unannotated)
    /// (calls NAME) (package NAME) (longer-than N) (kind function|macro|value)
    /// (and …) (or …) (not C). CAP is process, filesystem, environment, clock,
    /// network or host. A PATTERN is tatara's `match` pattern over the
    /// resolved tree `blue ast` prints, every reference written as what it
    /// resolved to: `(match `(retsu/first ,xs))` is every call to retsu's
    /// first, with its argument bound to xs. A file that cannot be resolved is
    /// named on stderr and the exit is 1.
    Query {
        query: String,
        paths: Vec<PathBuf>,
        /// One JSON object per hit per line: file, line, column, definition,
        /// key, kind, bindings, reach.
        #[arg(long)]
        json: bool,
    },
    /// Make every reference each FILE makes to another bidama's definition
    /// explicit (`use("retsu", [:first])`, and the bidama's `needs`), keeping
    /// a file only when its resolved tree is proven unchanged. The tool is
    /// the blue program `crates/blue-lang-cli/blue/migrate.b`, compiled into
    /// this binary.
    Migrate {
        /// FILE... to make explicit, or `--strip PREFIX BIDAMA CALLER...` to
        /// strip a bidama's hand-made prefix and rewrite its callers.
        #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
        files: Vec<String>,
    },
    /// What NAME is: its signature, doc line, namespace, tier and an example,
    /// for a builtin, `pkg::name`, or a bare name across the builtins and
    /// every bidama on BLUE_PATH; a bidama's name lists the package. The
    /// tool is the blue program `crates/blue-lang-cli/blue/doc.b`, compiled
    /// into this binary.
    Doc {
        #[arg(required_unless_present = "rows")]
        name: Option<String>,
        /// Look NAME up as this file reaches it: its own definitions first,
        /// and each answer's tier is how the file reaches it.
        #[arg(long)]
        file: Option<PathBuf>,
        /// One JSON object per answer.
        #[arg(long)]
        json: bool,
        /// The conformance rows compiled into this binary, as JSON; what
        /// `doc.b` reads a builtin's example from.
        #[arg(long, hide = true)]
        rows: bool,
        /// What blue derives about NAME, defined in FILE, as one JSON object:
        /// mondou's view (signature, rung, contract row, space, callers,
        /// refusals), which `doc.b` renders beside the `@doc`.
        #[arg(long, hide = true, requires = "file")]
        derived: bool,
    },
    /// The verb graph (`bidamas/mokuroku/graph`): `import` region or merged
    /// TSVs into its row files, `export` them back to TSV (the only writer of
    /// TSV), `check` its gates against the recorded baseline, `findings` of a
    /// TSV directory. The tool is the blue program
    /// `crates/blue-lang-cli/blue/verbs.b`, compiled into this binary.
    Verbs {
        #[arg(required = true, trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// How a bare NAME resolves at FILE:LINE: every tier of the resolution
    /// order, what each holds, and which wins.
    ExplainName {
        name: String,
        /// `path/to/file.b:LINE`.
        at: String,
    },
    /// Count, over every `.b` file under ROOT, each finding of every rule
    /// still being ratcheted in, and fail unless each count equals its
    /// registry row's `ratchet`. `--findings` lists them.
    Census {
        #[arg(default_value = ".")]
        root: PathBuf,
        #[arg(long)]
        findings: bool,
        #[arg(
            long,
            help = "Judge definition copies instead: every definition of 12 or more nodes whose shape_hash is another scope's, per package, against the hadome baseline. A grown or new row exits 1; a shrink passes; a gone row is advisory; an absent baseline enforces nothing. docs/DIAGNOSTICS.md, \"The reuse ratchet\""
        )]
        reuse: bool,
        #[arg(
            long,
            requires = "reuse",
            help = "With --reuse: the baseline file (default ROOT/reuse.baseline)"
        )]
        baseline: Option<PathBuf>,
        #[arg(
            long,
            requires = "reuse",
            help = "With --reuse: write the measured rows to the baseline. A raised or new row needs --receipt"
        )]
        record: bool,
        #[arg(
            long,
            requires = "record",
            help = "With --record: why a row rises or is new, kept as a # line in the baseline"
        )]
        receipt: Option<String>,
        #[arg(
            long,
            requires = "reuse",
            help = "With --reuse: one JSON document: rows that broke, every copy with its home, the denominators"
        )]
        json: bool,
        #[arg(
            long,
            requires = "reuse",
            help = "With --reuse: one JSON object per definition of 12 or more nodes, with its shape_hash, and exit 0"
        )]
        facts: bool,
    },
    /// Explain a diagnostic code (`blue explain B0001`), or list them all.
    #[command(group(clap::ArgGroup::new("which").required(true).args(["code", "list"])))]
    Explain {
        code: Option<String>,
        /// List every code with its severity and one-line law.
        #[arg(long)]
        list: bool,
    },
    /// Check the file (as `blue check` does), then run its `test` blocks. A
    /// directory runs every `.b` file under it holding a `test` block, in
    /// parallel, and ends with one summary line.
    Test {
        file: PathBuf,
        /// Run only the tests whose name contains PATTERN.
        #[arg(long, value_name = "PATTERN")]
        filter: Option<String>,
        /// Count each definition's calls across the tests and list the
        /// definitions no test reached.
        #[arg(long)]
        coverage: bool,
        /// Print coverage as one JSON object per file.
        #[arg(long, requires = "coverage")]
        json: bool,
        /// Run every call, answering none from the memo `BLUE_MEMO` turns
        /// on. Coverage always does.
        #[arg(long)]
        no_memo: bool,
        /// Run every test, reporting none as cached from the test cache
        /// `BLUE_TEST_CACHE` turns on. Coverage and facts always do.
        #[arg(long)]
        no_cache: bool,
        /// Hold the tests to these host capabilities, as `blue run --allow`
        /// holds a program: `none`, `host`, or one label. Repeatable. A host
        /// name a test reaches outside them is a capability breach, which
        /// fails that test; no `rescue` sees it. Without the flag the tests
        /// have every capability.
        #[arg(long = "allow", value_name = "CAPABILITY")]
        allow: Vec<String>,
        /// Write the run's facts for tameshi to FILE: the assertion tally,
        /// the steps and the frame. `blue-test-evidence.json` beside it
        /// names each test's controls, its target's `def_hash` and its own.
        /// `TAMESHI_FACTS` names FILE when the flag is not given.
        #[arg(long, value_name = "FILE")]
        facts: Option<PathBuf>,
    },
    /// Run a program and report every function it called: calls, inclusive
    /// and exclusive time, and what it allocated, most exclusive time first.
    Profile {
        file: PathBuf,
        /// How many functions to list.
        #[arg(long, default_value_t = 20)]
        top: usize,
        #[arg(long)]
        json: bool,
        /// Profile with every call run, none answered from the memo
        /// `BLUE_MEMO` turns on.
        #[arg(long)]
        no_memo: bool,
        /// The program's own arguments, after the file.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Run a program and print each call of DEF with its arguments, and each
    /// exit with its value, to stderr.
    Trace {
        /// The definition, as the program writes it: `f` or `retsu::first`.
        def: String,
        file: PathBuf,
        /// Stop printing after this many lines (the count still runs).
        #[arg(long, default_value_t = 200)]
        limit: usize,
        /// The program's own arguments, after the file.
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },
    /// Resolve a Bluefile's dependencies. Does not fetch.
    Deps { file: PathBuf },
    /// Report the posture a Bluefile's declared floor requires.
    Posture { file: PathBuf },
    /// Print a Bluefile's evaluated manifest, or confirm its lock is fresh.
    #[command(group(clap::ArgGroup::new("mode").required(true).args(["json", "confirm"])))]
    Bluefile {
        /// Print the evaluated manifest as JSON — what `Bluefile.lock` records
        /// under `manifest`.
        #[arg(long)]
        json: bool,
        /// Exit non-zero unless the `Bluefile.lock` beside every named
        /// Bluefile is blue's evaluation of it. Offline.
        #[arg(long)]
        confirm: bool,
        #[arg(required = true)]
        files: Vec<PathBuf>,
    },
    /// Evaluate each directory's Bluefile, pin every `source(...)` with
    /// `nix flake prefetch`, and write `Bluefile.lock` beside it.
    Lock {
        /// Directories holding a Bluefile. The current one when none is named.
        dirs: Vec<PathBuf>,
    },
    /// Seal FILE into an appliance payload: the program compiled (every `use`
    /// resolved, checked, erased) with the capability record its project's
    /// fresh `Bluefile.lock` verified, closed with its BLAKE3 digest. With
    /// `--runner`, OUT is the executable: the runner's bytes, then the payload.
    /// The appliance runs held to the record and takes no flags; a program
    /// outside a project, or a project that declares no `allow` or
    /// `virtualize`, runs pure.
    Bundle {
        file: PathBuf,
        /// The sealed payload, or the executable with `--runner`.
        #[arg(long, short = 'o', value_name = "OUT")]
        output: PathBuf,
        /// The `blue-appliance` runner to seal the payload onto.
        #[arg(long, value_name = "RUNNER")]
        runner: Option<PathBuf>,
    },
    /// Run the language server, speaking LSP over stdin/stdout.
    Lsp,
    /// Serve one evaluation session as JSON lines on stdin/stdout
    /// (`theory/BLUE-TOOLING.md` §4): the door an editor drives.
    Serve(repl::SessionArgs),
    /// An evaluation session at the terminal.
    Repl(repl::SessionArgs),
    /// Evaluate EXPR, or the top-level form at FILE:LINE:COL in that file's
    /// context, and print its value.
    Eval {
        target: String,
        #[command(flatten)]
        session: repl::SessionArgs,
    },
    /// Print blue's wordmark.
    Banner,
    /// Report the blueshift: how far this program is shifted, and what is
    /// shifting it.
    Shift {
        file: PathBuf,
        /// One JSON object: `rung` (or null with no declarations), `typed`,
        /// `total`, `analysed_nodes`, and `holding_back` with each factor's
        /// `kind`, `subject`, 1-based `line` and `detail`.
        #[arg(long)]
        json: bool,
    },
    /// The morphology: what each posture grants, what it forfeits, which pairs
    /// are genuinely exclusive, and which language each shape corresponds to.
    Morph,
    /// Print the language reference as JSON: operators, keywords, surface
    /// forms, Bluefile words, every bound name and every command, each read
    /// from the table the implementation runs on. `docs/REFERENCE.md` is
    /// rendered from it, and the README's commands and numbers.
    Reference,
    /// Run a crashed process again from the trace its crash wrote, and say
    /// whether it crashed the same way. `blue run` writes traces to
    /// `BLUE_TRACE_DIR` (default: `blue-traces` in the temporary directory),
    /// a fatal exit's as a `.bluecrash`, which replays under its recorded
    /// hold. TRACE is a file or a crash hash (`b3:<hex>`, 8 digits at least)
    /// resolved in that directory.
    Replay { trace: String },
    /// A crash trace, by its file or its crash hash: `dump` what it violated
    /// and where, `bisect` it to the fewest messages that still replay to
    /// it, `immunize` it into a test that locks the fix.
    Crash {
        #[command(subcommand)]
        cmd: crash::CrashCmd,
    },
    #[command(
        about = "arika, blue's word search: the word a draft already is (like), or a word by name (word)"
    )]
    Arika {
        #[command(subcommand)]
        cmd: arika::ArikaCmd,
    },
    /// Execution receipts `blue run --receipts DIR` writes.
    Receipt {
        #[command(subcommand)]
        cmd: receipt::ReceiptCmd,
    },
    /// Show the bounds `blue` is running with, at any tier.
    ///
    /// The fleet-uniform `config-show` surface, supplied by shikumi rather
    /// than hand-rolled here — see `config` for what may live in it and why
    /// the surface is two fields.
    Config(shikumi::cli::ConfigShowCommand),
    /// Start a program (a project with its own bidama), a `--bidama`, a
    /// `--script`, or a `--kernel` program, each passing `blue test` as written.
    New {
        /// The directory to create, or with `--script` the file.
        name: PathBuf,
        #[arg(long, conflicts_with_all = ["script", "kernel"])]
        bidama: bool,
        #[arg(long, conflicts_with = "kernel")]
        script: bool,
        /// A kernel program with its loader: `blue test` runs it on the pure
        /// machine with no kernel, and `--allow kernel_bpf` loads it.
        #[arg(long)]
        kernel: bool,
    },
    /// Rerun `check` (the default), `test` or `run` over each PATH whenever a
    /// watched file changes: `blue watch test lib.b`.
    Watch {
        #[arg(required = true, value_name = "[CMD] PATH")]
        targets: Vec<String>,
        /// The program's arguments, for `run`, after `--`.
        #[arg(last = true)]
        args: Vec<String>,
    },
    /// The Bluefile's `image(...)` entries, built through nix.
    Image {
        #[command(subcommand)]
        cmd: deploy::ImageCmd,
    },
    /// The Bluefile's `workload(...)` entries, rendered for GitOps.
    Workload {
        #[command(subcommand)]
        cmd: deploy::WorkloadCmd,
    },
    /// Compare the committed workload files with a cluster, read-only: exit 0
    /// when they agree, 1 when they differ, 2 when the comparison failed.
    /// There is no `blue apply`; a GitOps reconciler applies the commit.
    Diff(deploy::DiffArgs),
    #[command(
        about = "The Bluefile's `registry(...)` entries: each backend's publish workflow rendered from Bluefile.lock, and the sui state of every pin (docs/REGISTRY.md)"
    )]
    Registry {
        #[command(subcommand)]
        cmd: registry::RegistryCmd,
    },
}

fn main() -> ExitCode {
    // `blue FILE [ARGS]` is `blue run --quiet FILE -- ARGS` (`script`).
    let argv = script::route(std::env::args_os().collect(), &Cli::command());
    let code = match dispatch(Cli::parse_from(argv)) {
        Ok(code) => code,
        Err(e) => {
            eprintln!("blue: {e}");
            match &e {
                CliError::Blue(run) => failure_code(run),
                _ => ExitCode::FAILURE,
            }
        }
    };
    inputs::release(code != ExitCode::SUCCESS);
    code
}

fn failure_code(e: &blue_lang_runtime::RunError) -> ExitCode {
    ExitCode::from(e.exit_status())
}

/// `blue check`'s output shape.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
enum Format {
    Text,
    Json,
}

/// One error type for the CLI's own failures, so every exit path is typed.
#[derive(Debug, thiserror::Error)]
enum CliError {
    #[error("{path}: {source}")]
    Read {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("{path}: {source}")]
    Write {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("{0}")]
    Blue(#[from] blue_lang_runtime::RunError),
    #[error("{0}")]
    Fmt(String),
    #[error("{0}")]
    Pkg(String),
    #[error("{0}")]
    Usage(String),
    /// blue compiles only canonical source; `blue_lang_pkg::canonical`.
    #[error("{0}")]
    Refused(#[from] blue_lang_pkg::canonical::Refusal),
    #[error("{0}")]
    Config(#[from] shikumi::cli::ConfigShowError),
    #[error("{0}")]
    Bluefile(#[from] blue_lang_pkg::BluefileError),
    #[error("{0}")]
    Lock(#[from] blue_lang_pkg::lock::LockError),
    #[error("could not render JSON: {0}")]
    Json(#[from] serde_json::Error),
    #[error("{0}")]
    Deploy(#[from] deploy::DeployError),
    #[error("{0}")]
    Registry(#[from] registry::RegistryCliError),
    #[error("no diagnostic code `{0}`; `blue explain --list` lists them")]
    UnknownCode(String),
    /// `--json` prints ONE manifest; several would need a container shape, and
    /// inventing one here would be a second schema beside the lock's.
    #[error("`blue bluefile --json` prints one manifest, and {got} Bluefiles were named")]
    JsonTakesOne { got: usize },
}

/// One line of `blue bluefile --confirm` output: which Bluefile, and its
/// verdict (`{"status": "fresh"}` or `{"status": "stale", "reason": …}`).
#[derive(serde::Serialize)]
struct Confirmation<'a> {
    bluefile: String,
    #[serde(flatten)]
    verdict: &'a Freshness,
}

/// The source of a file blue is about to COMPILE without writing it:
/// canonical, or refused naming `blue fmt --write` (`blue_lang_pkg::canonical`).
/// `test` reads it here; a door that only looks (`fmt`, `ast`, `erase`,
/// `explain-name`) reads it with [`read`], as written.
fn read_compiled(path: &Path) -> Result<String, CliError> {
    Ok(blue_lang_pkg::canonical::read_source(
        path,
        blue_lang_pkg::canonical::Policy::from_env(),
    )?)
}

/// The source of a file blue is about to RUN: canonical, or formatted in
/// place first (`BLUE_LAYOUT=judge` refuses instead). `run`, `profile` and
/// `trace` read it here.
pub(crate) fn read_run(path: &Path) -> Result<String, CliError> {
    Ok(blue_lang_pkg::canonical::read_source(
        path,
        blue_lang_pkg::canonical::Policy::run(),
    )?)
}

fn dir_of(file: &Path) -> PathBuf {
    file.parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or(Path::new("."))
        .to_path_buf()
}

/// The directory of the Bluefile a file answers to: a level has none of its
/// own, so its root's.
fn manifest_dir_of(file: &Path) -> PathBuf {
    let dir = dir_of(file);
    std::fs::canonicalize(&dir)
        .unwrap_or_else(|_| dir.clone())
        .ancestors()
        .find(|d| d.join(blue_lang_pkg::MANIFEST_FILE).is_file())
        .map_or(dir, Path::to_path_buf)
}

fn read_bytes(path: &Path) -> Result<Vec<u8>, CliError> {
    std::fs::read(path).map_err(|source| CliError::Read {
        path: path.display().to_string(),
        source,
    })
}

fn read(path: &Path) -> Result<String, CliError> {
    std::fs::read_to_string(path).map_err(|source| CliError::Read {
        path: path.display().to_string(),
        source,
    })
}

/// Parse under the CONFIGURED nesting bound.
///
/// Every direct parse the CLI performs goes through here rather than through
/// `blue_lang_runtime::parse`, for the same reason the pipeline owns stage
/// order: a second door that quietly uses the compiled-in default would make
/// `max_expr_depth` true of some subcommands and not others, and nothing would
/// say which.
fn parse(src: &str, cfg: &BlueConfig) -> Result<Vec<blue_lang_syntax::Sexp>, CliError> {
    Ok(blue_lang_runtime::parse_with_depth(
        src,
        cfg.max_expr_depth,
    )?)
}

/// [`parse`] keeping every node's source span, under the same configured bound.
fn parse_tree(src: &str, cfg: &BlueConfig) -> Result<Vec<blue_lang_syntax::Spanned>, CliError> {
    Ok(blue_lang_runtime::parse_tree_with_depth(
        src,
        cfg.max_expr_depth,
    )?)
}

/// A `file:line:col` prefix.
///
/// A typed `Display` rather than a `format!` at the call site, per ★★ TYPED
/// EMISSION: a consumer that needed the text was a missing `Display`, not a
/// licence to build the string by interpolation. Both `line` and `col` are
/// ONE-based here, because this string is read by humans and by editors, and
/// both count from 1 — `Span::line_col` already answers in those terms.
struct Located {
    file: String,
    line: usize,
    col: usize,
}

impl std::fmt::Display for Located {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}:{}:", self.file, self.line, self.col)
    }
}

/// The distribution on `BLUE_PATH`, if any root holds one.
///
/// Roots are searched in order and the FIRST non-empty one wins — the same
/// "first match wins" rule `LoadPath` itself documents, so `blue deps` and
/// `use(...)` cannot disagree about which distribution is in effect.
fn scan_registry() -> Result<Option<blue_lang_pkg::git_registry::GitRegistry>, CliError> {
    use blue_lang_pkg::git_registry::{GitRegistry, GitRegistryError};
    for root in blue_lang_pkg::load_path::Environment::from_env().installed_roots() {
        let registry = match GitRegistry::scan(&root) {
            Ok(r) => r,
            // A stale entry in a `PATH`-shaped list is normal, so an unreadable
            // root is skipped. A Bluefile that EXISTS and does not parse is a
            // broken package and is reported — the scanner draws that line
            // deliberately, and swallowing it here would undo it.
            Err(GitRegistryError::Unreadable { .. }) => continue,
            Err(e @ GitRegistryError::BadManifest { .. }) => {
                return Err(CliError::Pkg(e.to_string()))
            }
        };
        if !registry.is_empty() {
            return Ok(Some(registry));
        }
    }
    Ok(None)
}

fn dispatch(cli: Cli) -> Result<ExitCode, CliError> {
    // Resolved ONCE, at the top, and threaded down — never re-read per
    // subcommand. Two reads of a config are two chances to disagree about it,
    // and the pipeline's own lesson (one place owns the order) applies to the
    // bounds the pipeline runs under just as much.
    let cfg = config::resolve();
    blue_lang_check::evolution::FormJudge::from_env().map_err(CliError::Pkg)?;
    blue_lang_check::evolution::Layout::from_env().map_err(CliError::Pkg)?;
    // Before any interpreter is built, so every evaluating door — run, test,
    // the LSP, a Bluefile — runs under the configured bounds.
    blue_lang_runtime::set_execution_bounds(cfg.execution_bounds());
    blue_lang_runtime::wire::set_flash_rate(cfg.flash_bytes_per_second);
    blue_lang_proc::node::set_trace_dir(replay::trace_dir());
    blue_lang_proc::node::set_journal_bound(replay::journal_bound());
    // `self_exe` answers with THIS binary only because it is the blue CLI;
    // any other embedder leaves it nil (blue_lang_runtime::sys::set_blue_exe).
    if let Ok(me) = std::env::current_exe() {
        blue_lang_runtime::sys::set_blue_exe(me.to_string_lossy().into_owned());
    }
    match cli.cmd {
        Cmd::Replay { trace } => crash::resolve(&trace)
            .and_then(|path| replay::run(&path))
            .map_err(CliError::Fmt),
        Cmd::Crash { cmd } => crash::run(cmd).map_err(CliError::Fmt),
        Cmd::Arika { cmd } => arika::run(cmd).map_err(CliError::Fmt),
        Cmd::Receipt { cmd } => Ok(receipt::run(cmd)),
        Cmd::Run {
            file,
            inputs,
            allow,
            receipts,
            receipt_steps,
            quiet,
            format,
            timings,
            no_memo,
            args,
        } => {
            if timings {
                blue_lang_runtime::timings::enable();
            }
            sigint::stop();
            inputs::hold(&file, inputs::Word::Generate)?;
            let project = blue_lang_pkg::capabilities::hold_for(&file).map_err(CliError::Pkg)?;
            let hold = if allow.is_empty() {
                project
            } else {
                let asked = blue_lang_runtime::session::frame_granting(
                    &repl::granted(&allow).map_err(CliError::Fmt)?,
                );
                Some(match project {
                    Some(p) => blue_lang_runtime::Hold {
                        frame: asked.narrow(&p.frame),
                        provisions: p.provisions,
                        bounds: p.bounds,
                    },
                    None => blue_lang_runtime::Hold::from(asked),
                })
            };
            let hold = receipt::hold_for(hold, receipts.as_deref());
            let mut account = receipt::account(receipts.clone());
            if receipt_steps {
                account.steps = Some(std::sync::Arc::default());
            }
            blue_lang_runtime::sys::set_program_args(args);
            // The SURFACE the program is written in: BLUE_LANG wins, else the
            // host locale. An explicit choice must beat a detected one.
            let surface = resolve_surface().map_err(CliError::Pkg)?;
            // blue compiles only canonical source. The formatter speaks the
            // English surface, so a program that USES a `yakugo` surface's
            // words is compiled as written rather than translated by its
            // formatting. One that parses to the same tree either way is
            // English — the common case under a pt or de locale — and is held
            // to the rule like any other.
            let src = match &surface {
                None => blue_lang_runtime::timings::stage(
                    blue_lang_runtime::timings::Stage::Read,
                    || read_run(&file),
                )?,
                Some(pack) => {
                    let text = read(&file)?;
                    let english = blue_lang_syntax::parse_program(&text).ok();
                    let spoken = blue_lang_syntax::parse_program_in(&text, pack).ok();
                    if english.is_some() && english == spoken {
                        blue_lang_pkg::canonical::admit(&file, text)?
                    } else {
                        text
                    }
                }
            };
            // Always bind, even with no `--input` flags: a program that
            // DECLARES an input and gets no material must hear "you forgot the
            // flag", not the macro-level "no input named …" from deep inside
            // expansion. Short-circuiting on an empty flag list is what made it
            // report the wrong one.
            // Imports resolve through BLUE_PATH.
            //
            // The CLI is the one place a *user's* environment can supply the
            // loader, and without this wire `use("kazu")` fails from the
            // command line no matter what nix built — the derivations, the
            // BLUE_PATH root and the resolver would all be correct and none of
            // them reachable from `blue run`.
            //
            // Reading the environment rather than taking a flag because that is
            // what makes the nix wrapper work: `mkBlueWithBidamas` suffixes
            // BLUE_PATH, so a wrapped `blue` resolves the distribution with no
            // argument, and an unwrapped one still honours a checkout. After
            // BLUE_PATH come the project around the file and the distribution
            // compiled in (`LoadPath::for_entry` states the order).
            let loader = blue_lang_pkg::load_path::LoadPath::for_entry(&file);
            // The entry file travels WITH its source. Without the path, every
            // type error in the file the user named would report against
            // `<anonymous>` while an imported package's reported its real path
            // — the entry file being the one file the CLI always knows.
            let entry = blue_lang_runtime::uses::Entry {
                path: Some(&file),
                text: &src,
            };
            let inputs = bind_inputs(&src, &inputs, &cfg)?;
            let memo = if receipt_steps {
                memo::Mode::Off
            } else {
                memo::unless_bounded(
                    memo::mode(no_memo, &cfg),
                    hold.as_ref().and_then(|h| h.bounds),
                )
            };
            let ran = match memo {
                memo::Mode::Off => blue_lang_runtime::pipeline::run_framed_accounted(
                    entry,
                    inputs,
                    &loader,
                    surface.as_ref(),
                    hold.as_ref(),
                    &account,
                ),
                mode => {
                    let mut held = None;
                    let observed = blue_lang_runtime::pipeline::run_observed_accounted(
                        entry,
                        inputs,
                        &loader,
                        surface.as_ref(),
                        hold.as_ref(),
                        &account,
                        |w| {
                            let m = memo::over(
                                mode.persist(),
                                w.definitions,
                                w.lowered,
                                w.erased,
                                None,
                            );
                            held = Some(std::sync::Arc::clone(&m));
                            m
                        },
                    );
                    if let Some(m) = &held {
                        memo::finish(m);
                    }
                    observed.and_then(|o| o.outcome)
                }
            };
            if let Some(dir) = &receipts {
                receipt::write_run(dir, hold.as_ref(), &account, &ran);
            }
            let out = match ran {
                Err(e) if format == Format::Json => {
                    println!("{}", serde_json::to_string(&observe::error_json(&e))?);
                    return Ok(failure_code(&e));
                }
                out => out?,
            };
            if !quiet {
                println!("{}", render(&out.value));
            }
            if timings {
                eprint!("{}", blue_lang_runtime::timings::report());
            }
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Fmt { file, check, write } => {
            if !check && !write && file.len() != 1 {
                return Err(CliError::Fmt(
                    "`blue fmt` prints ONE file; name several with --check or --write".into(),
                ));
            }
            let mut failed = false;
            for file in &file {
                let src = read(file)?;
                // The LOSSLESS rendering is the canonical form of a file that
                // has comments, so `--check` must compare against it. Comparing
                // against the comment-stripped rendering made every commented
                // file report "not formatted" forever — a --check that can
                // never be satisfied.
                let formatted = match blue_lang_pkg::canonical::format_resolved(file, &src) {
                    Ok(f) => f,
                    Err(e) if check || write => {
                        eprintln!("blue: {}: {e}", file.display());
                        failed = true;
                        continue;
                    }
                    Err(e) => return Err(CliError::Fmt(e.to_string())),
                };
                if check {
                    // Compare trimmed: a trailing newline is not drift.
                    if formatted.trim_end() != src.trim_end() {
                        eprintln!(
                            "{}: not formatted{}; run blue fmt --write {}",
                            file.display(),
                            blue_lang_pkg::canonical::rules_named(&src),
                            file.display()
                        );
                        failed = true;
                    }
                } else if write {
                    // The LOSSLESS path, because this overwrites the file.
                    // `--write` used to delete every comment silently; a
                    // comment the formatter cannot place is refused above.
                    std::fs::write(file, &formatted).map_err(|source| CliError::Write {
                        path: file.display().to_string(),
                        source,
                    })?;
                } else {
                    print!("{formatted}");
                }
            }
            Ok(if failed {
                ExitCode::FAILURE
            } else {
                ExitCode::SUCCESS
            })
        }

        Cmd::Ast {
            file,
            resolved: false,
            ..
        } => {
            for form in parse(&read(&file)?, &cfg)? {
                println!("{form}");
            }
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Ast {
            file, json, lines, ..
        } => {
            use blue_lang_runtime::pipeline::{check_entry, Checking};
            let loader = blue_lang_pkg::load_path::LoadPath::for_entry(&file);
            let src = read(&file)?;
            let checked = check_entry(
                blue_lang_runtime::uses::Entry {
                    path: Some(&file),
                    text: &src,
                },
                &loader,
                None,
                Checking::WithTests,
            )?;
            let resolved = checked.resolve();
            if json {
                println!("{}", diagnostics::resolved_json(&checked, &resolved)?);
            } else {
                let tree = resolved.resolved_tree(
                    checked.program.forms(),
                    blue_lang_check::names::Rule::Namespaced,
                );
                if lines {
                    let path = file.display().to_string();
                    println!("{}", source_lines::source_form(&path, &src));
                }
                for (i, form) in tree.iter().enumerate() {
                    if checked.program.owner_of(i)
                        == Some(blue_lang_runtime::uses::ResolvedProgram::ENTRY)
                    {
                        if lines {
                            let marked = source_lines::with_source_lines(form.clone(), &src);
                            println!("{}", marked.to_sexp());
                        } else {
                            println!("{}", form.to_sexp());
                        }
                    }
                }
            }
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Erase { file } => {
            // The SPANNED door — erasure runs on spans, so this is the tree it
            // takes. Printed through `to_sexp`, which is the projection that
            // throws the positions away: they are what the erased tree is FOR
            // downstream, and `Spanned` has no `Display` precisely so a caller
            // has to say out loud that it is dropping them.
            let forms = parse_tree(&read(&file)?, &cfg)?;
            for form in blue_lang_runtime::to_sexps(&blue_lang_runtime::erase_types(&forms)) {
                println!("{form}");
            }
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Check { hook: true, .. } => {
            census::reuse_hook();
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Check {
            file: Some(file),
            reuse: true,
            ..
        } => {
            for line in census::word_copy_lines(&file) {
                println!("{line}");
            }
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Check {
            file,
            format,
            fix,
            only,
            ..
        } => check(
            &file.expect("clap requires a file unless --hook"),
            format,
            fix,
            &only,
        ),

        Cmd::Query { query, paths, json } => query::run(&query, &paths, json),

        Cmd::Migrate { files } => {
            blue_lang_runtime::sys::set_program_args(files);
            blue_lang_runtime::pipeline::run_in_surface(
                blue_lang_runtime::uses::Entry {
                    path: Some(Path::new("crates/blue-lang-cli/blue/migrate.b")),
                    text: MIGRATE,
                },
                blue_lang_runtime::inputs::Inputs::new(),
                &blue_lang_runtime::uses::NoLoader,
                None,
            )?;
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Doc {
            name,
            file,
            json,
            rows,
            derived,
        } => {
            if rows {
                println!("{}", doc::rows_json()?);
                return Ok(ExitCode::SUCCESS);
            }
            if derived {
                let (Some(name), Some(file)) = (name, file) else {
                    return Ok(ExitCode::FAILURE);
                };
                let text = read(&file)?;
                let bidama = blue_lang_runtime::uses::Loader::entry_package(
                    &blue_lang_pkg::load_path::LoadPath::for_entry(&file),
                    &file,
                );
                let mut engine = blue_lang_mondou::Engine::with_scopes(Box::new(
                    blue_lang_pkg::load_path::Environment::from_env(),
                ));
                let id = file.display().to_string();
                engine.set_document(&id, Some(file.clone()), &text);
                return Ok(match engine.doc_view_in(&id, bidama.as_deref(), &name) {
                    Some(v) => {
                        println!("{}", doc::derived_json(&v)?);
                        ExitCode::SUCCESS
                    }
                    None => ExitCode::FAILURE,
                });
            }
            let mut args: Vec<String> = name.into_iter().collect();
            if let Some(f) = file {
                args.push("--file".into());
                args.push(f.display().to_string());
            }
            if json {
                args.push("--json".into());
            }
            blue_lang_runtime::sys::set_program_args(args);
            let out = blue_lang_runtime::pipeline::run_in_surface(
                blue_lang_runtime::uses::Entry {
                    path: Some(Path::new("crates/blue-lang-cli/blue/doc.b")),
                    text: doc::PROGRAM,
                },
                blue_lang_runtime::inputs::Inputs::new(),
                &blue_lang_pkg::load_path::Environment::from_env().load_path(None),
                None,
            )?;
            Ok(
                if matches!(out.value, tatara_lisp_eval::Value::Bool(false)) {
                    ExitCode::FAILURE
                } else {
                    ExitCode::SUCCESS
                },
            )
        }

        Cmd::Verbs { args } => {
            blue_lang_runtime::sys::set_program_args(args);
            let out = blue_lang_runtime::pipeline::run_in_surface(
                blue_lang_runtime::uses::Entry {
                    path: Some(Path::new("crates/blue-lang-cli/blue/verbs.b")),
                    text: VERBS,
                },
                blue_lang_runtime::inputs::Inputs::new(),
                &blue_lang_pkg::load_path::Environment::from_env().load_path(None),
                None,
            )?;
            Ok(
                if matches!(out.value, tatara_lisp_eval::Value::Bool(false)) {
                    ExitCode::FAILURE
                } else {
                    ExitCode::SUCCESS
                },
            )
        }

        Cmd::ExplainName { name, at } => {
            let (path, line) = at
                .rsplit_once(':')
                .and_then(|(p, l)| l.parse::<usize>().ok().map(|l| (PathBuf::from(p), l)))
                .ok_or_else(|| CliError::Pkg(format!("expected FILE:LINE, got `{at}`")))?;
            let src = read(&path)?;
            let checked = blue_lang_runtime::pipeline::check_entry(
                blue_lang_runtime::uses::Entry {
                    path: Some(&path),
                    text: &src,
                },
                &blue_lang_pkg::load_path::LoadPath::for_entry(&path),
                None,
                blue_lang_runtime::pipeline::Checking::WithTests,
            )?;
            let program = &checked.program;
            let entry = |i: usize| {
                program.owner_of(i) == Some(blue_lang_runtime::uses::ResolvedProgram::ENTRY)
            };
            let form = (0..program.forms().len())
                .filter(|i| entry(*i))
                .filter(|i| {
                    blue_lang_syntax::Span::line_col(&src, program.forms()[*i].span.start).0 <= line
                })
                .last()
                .ok_or_else(|| {
                    CliError::Pkg(format!("no top-level form at or before line {line}"))
                })?;
            let own = blue_lang_runtime::pipeline::namespace_of(program, form);
            println!("`{name}` at {}:{line}, in {own}:", path.display());
            println!("  local     a parameter or local of that name in scope at the line wins over everything below");
            let mut won = false;
            for (tier, nss) in checked.names.tiers_of(&name, &own, form) {
                let word = format!("{tier:?}").to_lowercase();
                let held = if nss.is_empty() {
                    "-".to_string()
                } else {
                    nss.iter()
                        .map(ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(", ")
                };
                let verdict = match (nss.len(), won) {
                    (0, _) => "",
                    (1, false) => "  <- wins",
                    (_, false) => "  <- ambiguous (B0009)",
                    (_, true) => "  (shadowed)",
                };
                if !nss.is_empty() {
                    won = true;
                }
                println!("  {word:<9} {held}{verdict}");
            }
            if !won {
                println!("  unbound (B0001, or B0012 when a used bidama defines it)");
            }
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Census {
            root,
            findings,
            reuse: true,
            baseline,
            record,
            receipt,
            json,
            facts,
        } => {
            let scan = census::reuse_scan(&root);
            if facts {
                for f in &scan.facts {
                    println!("{}", f.to_json());
                }
                return Ok(ExitCode::SUCCESS);
            }
            let path = baseline.unwrap_or_else(|| root.join("reuse.baseline"));
            let mut args = vec![
                "--report".to_string(),
                scan.to_json().to_string(),
                root.display().to_string(),
                path.display().to_string(),
            ];
            for (on, flag) in [
                (record, "--record"),
                (json, "--json"),
                (findings, "--findings"),
            ] {
                if on {
                    args.push(flag.to_string());
                }
            }
            if let Some(why) = receipt {
                args.push("--receipt".to_string());
                args.push(why);
            }
            blue_lang_runtime::sys::set_program_args(args);
            let out = blue_lang_runtime::pipeline::run_in_surface(
                blue_lang_runtime::uses::Entry {
                    path: Some(Path::new("crates/blue-lang-cli/blue/reuse.b")),
                    text: REUSE,
                },
                blue_lang_runtime::inputs::Inputs::new(),
                &blue_lang_pkg::load_path::Environment::from_env().load_path(None),
                None,
            )?;
            Ok(
                if matches!(out.value, tatara_lisp_eval::Value::Bool(false)) {
                    ExitCode::FAILURE
                } else {
                    ExitCode::SUCCESS
                },
            )
        }

        Cmd::Census { root, findings, .. } => {
            let c = census::take(&root).map_err(CliError::Pkg)?;
            println!("{} file(s)", c.files);
            for r in blue_lang_check::RULES
                .iter()
                .filter(|r| r.ratchet.is_some())
            {
                let measured = c
                    .findings
                    .get(&r.code)
                    .map_or(0, std::collections::BTreeSet::len);
                println!(
                    "{} {:<24} measured {measured:>5}  ratchet {:>5}",
                    r.code,
                    r.slug,
                    r.ratchet.unwrap_or(0)
                );
                if findings {
                    for f in c.findings.get(&r.code).into_iter().flatten() {
                        println!("    {}", f.lines().next().unwrap_or(""));
                    }
                }
            }
            let bad = c.mismatches();
            for (code, measured, ratchet) in &bad {
                eprintln!(
                    "blue census: {code} measured {measured}, ratchet {ratchet}: edit the row's ratchet to {measured} if the change is the intended one"
                );
            }
            Ok(if bad.is_empty() {
                ExitCode::SUCCESS
            } else {
                ExitCode::FAILURE
            })
        }

        Cmd::Explain { code, list } => {
            if list {
                for r in blue_lang_check::RULES {
                    println!(
                        "{} {:<8} {:<22} {}",
                        r.code,
                        r.severity.label(),
                        r.slug,
                        r.law
                    );
                }
                return Ok(ExitCode::SUCCESS);
            }
            let code = code.unwrap_or_default();
            let c = blue_lang_check::Code::parse(&code).ok_or(CliError::UnknownCode(code))?;
            print!("{}", blue_lang_check::Explain(c.rule()));
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Test {
            file,
            filter,
            coverage,
            json,
            no_memo,
            no_cache,
            allow,
            facts,
        } => {
            let facts = facts::path(facts);
            let cache = test_cache::TestCache::open(no_cache, coverage || facts.is_some())
                .map_err(CliError::Usage)?;
            if file.is_file() {
                inputs::hold(&file, inputs::Word::Check)?;
            }
            let asked = if allow.is_empty() {
                None
            } else {
                Some(blue_lang_runtime::Hold::from(
                    blue_lang_runtime::session::frame_granting(
                        &repl::granted(&allow).map_err(CliError::Fmt)?,
                    ),
                ))
            };
            observe::test(
                &file,
                &observe::Watch {
                    filter: filter.as_deref(),
                    coverage,
                    json,
                    memo: memo::mode(no_memo, &cfg),
                    cache: cache.as_ref(),
                },
                receipt::hold_for(asked, facts.as_deref()),
                facts.as_deref(),
            )
        }
        Cmd::Profile {
            file,
            top,
            json,
            no_memo,
            args,
        } => observe::profile(&file, top, json, memo::mode(no_memo, &cfg), args, &cfg),
        Cmd::Trace {
            def,
            file,
            limit,
            args,
        } => observe::trace(&def, &file, limit, args, &cfg),

        Cmd::Deps { file } => {
            let mut manifest = blue_lang_pkg::read_bluefile(&read(&file)?)
                .map_err(|e| CliError::Pkg(e.to_string()))?;
            if let Some(needs) = blue_lang_pkg::lock::locked_needs(&dir_of(&file)) {
                manifest.manifest.needs = needs;
            }
            println!("{} {}", manifest.name, manifest.version);
            if manifest.manifest.needs.is_empty() {
                println!("  (no dependencies)");
                return Ok(ExitCode::SUCCESS);
            }
            for (dep, range) in &manifest.manifest.needs {
                println!("  needs {dep} {range}");
            }

            // Resolve against the distribution on BLUE_PATH, if there is one.
            //
            // There is still no registry CLIENT — nothing fetches — but
            // `GitRegistry` reads a checkout that is already on disk, and that
            // is a real registry for resolution purposes. Printing "none is
            // configured" while a scannable distribution sat on BLUE_PATH was
            // the CLI declining to use the thing it had.
            let Some(registry) = scan_registry()? else {
                println!("\nno distribution on BLUE_PATH; nothing to resolve against");
                return Ok(ExitCode::SUCCESS);
            };
            // The configured bound, not the constructor's default. This is the
            // only production caller of the solver, so it is the only place
            // `solver_max_steps` can be read — and if it is not read here the
            // knob is decoration.
            let mut solver =
                blue_lang_pkg::Solver::new(&registry).with_max_steps(cfg.solver_max_steps);
            let resolution = solver
                .solve(&manifest.manifest)
                .map_err(|e| CliError::Pkg(e.to_string()))?;
            println!("\nresolved against {} package(s):", registry.len());
            for (name, version) in &resolution.picks {
                println!("  {name} {version}");
            }
            println!(
                "  ({} step(s), {} skipped by learning)",
                solver.steps_taken(),
                solver.skipped_by_learning()
            );
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Posture { file } => {
            let manifest = blue_lang_pkg::read_bluefile(&read(&file)?)
                .map_err(|e| CliError::Pkg(e.to_string()))?;
            let floor = &manifest.floor;
            println!("{} {}", manifest.name, manifest.version);
            println!("  when:  {:?}", floor.when);
            println!("  where: {:?}", floor.place);
            println!("  reach: {}", describe_reach(&floor.reach));

            // What the declaration actually BUYS, from the same derivation
            // `blue morph` prints. A coordinate is not self-explanatory —
            // `when: Preceding` says nothing to a reader about what they just
            // gave up, and the whole point of the morphology is that the answer
            // is computed rather than remembered.
            let grants = blue_lang_bidama::qualities_at(floor);
            let lost = blue_lang_bidama::forfeits_at(floor);
            let names = |qs: &std::collections::BTreeSet<blue_lang_bidama::Quality>| {
                qs.iter().map(|q| q.label()).collect::<Vec<_>>().join(", ")
            };
            println!("\n  grants:   {}", names(&grants));
            println!("  forfeits: {}", names(&lost));
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Bluefile {
            json,
            confirm: _,
            files,
        } => {
            if json {
                let [file] = files.as_slice() else {
                    return Err(CliError::JsonTakesOne { got: files.len() });
                };
                let manifest = blue_lang_pkg::lock::manifest_at(&dir_of(file))?;
                print!("{}", blue_lang_pkg::lock::render(&manifest)?);
                return Ok(ExitCode::SUCCESS);
            }
            // `--confirm`, the group's only other member. Every file is
            // checked and reported before the exit code is decided, so one
            // stale package does not hide the next.
            let mut all_fresh = true;
            for file in &files {
                let verdict = blue_lang_pkg::lock::confirm_dir(&dir_of(file))?;
                println!(
                    "{}",
                    serde_json::to_string(&Confirmation {
                        bluefile: file.display().to_string(),
                        verdict: &verdict,
                    })?
                );
                if let Freshness::Stale { reason } = &verdict {
                    let dir = file.parent().filter(|p| !p.as_os_str().is_empty());
                    eprintln!(
                        "blue: {}: {reason}; run `blue lock {}`",
                        file.display(),
                        dir.unwrap_or(Path::new(".")).display()
                    );
                    all_fresh = false;
                }
            }
            Ok(if all_fresh {
                ExitCode::SUCCESS
            } else {
                ExitCode::FAILURE
            })
        }

        Cmd::Lock { dirs } => {
            let dirs = if dirs.is_empty() {
                vec![PathBuf::from(".")]
            } else {
                dirs
            };
            // Every lock is computed before any is written: a source that fails
            // to pin must not leave half a directory tree relocked.
            let mut locks = Vec::with_capacity(dirs.len());
            for dir in &dirs {
                let (lock, notes) = blue_lang_pkg::lock::lock_dir_with(
                    dir,
                    &prefetch::NixPrefetch,
                    Some(&registry::CurlFlakeHub::from_env()),
                )?;
                for note in notes {
                    eprintln!("➖ {}: {note}", dir.display());
                }
                locks.push((dir.join(LOCK_FILE), lock));
            }
            for (path, lock) in &locks {
                std::fs::write(path, blue_lang_pkg::lock::render(lock)?).map_err(|source| {
                    CliError::Write {
                        path: path.display().to_string(),
                        source,
                    }
                })?;
                println!(
                    "{}: {} source(s) pinned",
                    path.display(),
                    lock.sources.len()
                );
            }
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Shift { file, json } => {
            let reading = blue_lang_lsp::shift_of(&read(&file)?);
            if json {
                let holding: Vec<serde_json::Value> = reading
                    .holding_back()
                    .iter()
                    .map(|f| {
                        serde_json::json!({
                            "kind": f.kind.label(),
                            "subject": f.subject,
                            "line": f.range.start.line + 1,
                            "detail": f.detail,
                        })
                    })
                    .collect();
                println!(
                    "{}",
                    serde_json::json!({
                        "rung": reading.rung.map(blue_lang_lsp::Rung::label),
                        "typed": reading.typed_declarations,
                        "total": reading.total_declarations,
                        "analysed_nodes": reading.analysed_nodes,
                        "holding_back": holding,
                    })
                );
                return Ok(ExitCode::SUCCESS);
            }
            println!("{}", reading.summary());
            if let Some(rung) = reading.rung {
                println!("{}", rung.meaning());
            }
            if reading.factors.is_empty() {
                return Ok(ExitCode::SUCCESS);
            }
            println!();
            for f in &reading.factors {
                // The arrow says which direction each factor pushes, so a
                // reader can tell "this shifted me" from "this is holding me".
                let arrow = if f.kind.shifts_forward() { "→" } else { "·" };
                println!("  {arrow} {:<24} {}", f.kind.label(), f.detail);
            }
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Image { cmd } => Ok(deploy::image(cmd)?),
        Cmd::Workload { cmd } => Ok(deploy::workload(cmd)?),
        Cmd::Registry { cmd } => Ok(registry::run(cmd)?),
        Cmd::Diff(args) => Ok(deploy::diff(args)),
        Cmd::Reference => {
            println!("{}", serde_json::to_string_pretty(&reference::reference())?);
            Ok(ExitCode::SUCCESS)
        }
        Cmd::Morph => {
            use blue_lang_bidama::{
                enforcement, exclusive_pairs, minimal_exclusive_groups, qualities_at, shapes,
                Quality,
            };

            println!("QUALITIES — where each is enforced\n");
            for q in Quality::ALL {
                let (layer, why) = enforcement(q);
                let mark = if layer.is_enforced() { "✓" } else { "·" };
                println!("  {mark} {:<30} {}", q.label(), layer.label());
                println!("      {why}");
            }

            println!("\nMUTUALLY EXCLUSIVE — derived by enumerating the lattice\n");
            for (a, b) in exclusive_pairs() {
                println!(
                    "  {:<30} ⊥ {:<30} (both on the {:?} axis)",
                    a.label(),
                    b.label(),
                    a.axis()
                );
            }
            println!(
                "\n  Every exclusive pair shares an axis. Two qualities on DIFFERENT\n                   coordinates always have a posture granting both — which is what a\n                   per-package posture buys over one global choice."
            );

            // Past two. A trilemma contains no exclusive pair — every pair has
            // a witness and only the whole set does not — so the section above
            // reports it as nothing at all, which looks like a checked absence.
            let groups: Vec<Vec<Quality>> = minimal_exclusive_groups()
                .into_iter()
                .filter(|g| g.len() > 2)
                .collect();
            if !groups.is_empty() {
                println!("\nPICK ANY TWO — minimal exclusive groups past a pair\n");
                for g in &groups {
                    let names: Vec<&str> = g.iter().map(|q| q.label()).collect();
                    println!(
                        "  {}  (all on the {:?} axis)",
                        names.join("  +  "),
                        g[0].axis()
                    );
                }
                println!(
                    "\n  No pair inside a group is exclusive — only the whole group is.\n  \
                     Dropping any one member names a posture that grants the rest."
                );
            }

            println!("\nSHAPES — a language is a point; blue is the space\n");
            for s in shapes() {
                let q = qualities_at(&s.posture);
                println!("  {:<22} {}", s.name, s.because);
                let names: Vec<&str> = q.iter().map(|x| x.label()).collect();
                println!("      grants: {}", names.join(", "));
            }
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Banner => {
            // The version comes from the crate, never a literal — mado shipped a
            // 0.1.0 wordmark against a 0.1.98 binary from exactly that mistake.
            for line in blue_lang_art::wordmark(env!("CARGO_PKG_VERSION")) {
                println!("{}", line.render());
            }
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Config(cmd) => {
            cmd.run::<BlueConfig>(config::TIER_ENV)?;
            Ok(ExitCode::SUCCESS)
        }

        Cmd::New {
            name,
            bidama,
            script,
            kernel,
        } => {
            let shape = match (bidama, script, kernel) {
                (true, _, _) => scaffold::Shape::Bidama,
                (_, true, _) => scaffold::Shape::Script,
                (_, _, true) => scaffold::Shape::Kernel,
                _ => scaffold::Shape::Program,
            };
            println!("{}", scaffold::new(&name, shape).map_err(CliError::Pkg)?);
            Ok(ExitCode::SUCCESS)
        }

        Cmd::Watch { targets, args } => {
            let (verb, paths) = watch::parse(&targets).map_err(CliError::Pkg)?;
            watch::watch(verb, &paths, &args).map_err(CliError::Pkg)
        }

        Cmd::Serve(session) => repl::serve(&session).map_err(CliError::Pkg),
        Cmd::Repl(session) => repl::repl(&session).map_err(CliError::Pkg),
        Cmd::Eval { target, session } => repl::eval(&target, &session).map_err(CliError::Pkg),
        Cmd::Bundle {
            file,
            output,
            runner,
        } => {
            let surface = resolve_surface().map_err(CliError::Pkg)?;
            let payload = blue_lang_pkg::appliance::bundle(&file, surface.as_ref())
                .map_err(|e| CliError::Pkg(e.to_string()))?;
            let bytes = match &runner {
                Some(r) => blue_lang_pkg::appliance::appended(read_bytes(r)?, &payload)?,
                None => blue_lang_pkg::appliance::seal(&payload)?,
            };
            let written = |source| CliError::Write {
                path: output.display().to_string(),
                source,
            };
            std::fs::write(&output, &bytes).map_err(written)?;
            #[cfg(unix)]
            if runner.is_some() {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(&output, std::fs::Permissions::from_mode(0o755))
                    .map_err(written)?;
            }
            let held = match payload.policy.as_ref().map(|p| &p.ceiling) {
                None => "pure".to_string(),
                Some(None) => "every capability".to_string(),
                Some(Some(c)) => format!("[{}]", c.join(", ")),
            };
            println!(
                "{}: {} ({} forms, held to {held})",
                output.display(),
                payload.name,
                payload.forms.len()
            );
            Ok(ExitCode::SUCCESS)
        }
        Cmd::Lsp => {
            let stdout = std::io::stdout();
            blue_lang_lsp::Server::with_scopes(Box::new(
                blue_lang_pkg::load_path::Environment::from_env(),
            ))
            .serve(std::io::BufReader::new(std::io::stdin()), stdout.lock())
            .map_err(|source| CliError::Write {
                path: "<stdio>".to_string(),
                source,
            })?;
            Ok(ExitCode::SUCCESS)
        }
    }
}

/// `blue check`: the pipeline's check stage over the file and its imports.
fn check(file: &Path, format: Format, fix: bool, only: &[String]) -> Result<ExitCode, CliError> {
    use blue_lang_runtime::pipeline::{check_entry, render, syntax_diagnostic, Checking};
    let only: Vec<blue_lang_check::Code> = only
        .iter()
        .map(|o| {
            blue_lang_check::Code::ALL
                .iter()
                .copied()
                .find(|c| c.as_str() == o)
                .ok_or_else(|| CliError::Pkg(format!("--only {o}: no rule has that code")))
        })
        .collect::<Result<_, _>>()?;
    // A file that does not parse has no tree to check, and the compile door
    // below would refuse it with the formatter's message. Report it here as
    // B0006 instead, so a syntax error arrives in the same shape — code,
    // line:col, JSON — as every other finding.
    let raw = read(file)?;
    if let Some(d) = syntax_diagnostic(&raw) {
        match format {
            Format::Json => print!("{}", diagnostics::syntax_json(file, &raw, &d)?),
            Format::Text => {
                let (line, col) = blue_lang_syntax::Span::line_col(&raw, d.span.start);
                eprintln!(
                    "{} {d}",
                    Located {
                        file: file.display().to_string(),
                        line,
                        col,
                    }
                );
            }
        }
        return Ok(ExitCode::FAILURE);
    }
    let loader = blue_lang_pkg::load_path::LoadPath::for_entry(file);
    let mut src = if fix && only.is_empty() {
        blue_lang_pkg::canonical::read_layout(file)?
    } else {
        std::fs::read_to_string(file).map_err(|source| CliError::Read {
            path: file.display().to_string(),
            source,
        })?
    };
    fn entry<'a>(file: &'a Path, text: &'a str) -> blue_lang_runtime::uses::Entry<'a> {
        blue_lang_runtime::uses::Entry {
            path: Some(file),
            text,
        }
    }
    // The project's own rules, written in blue and named by the Bluefiles
    // above the file (`blue_lang_pkg::project_rules`).
    let rules =
        blue_lang_pkg::project_rules::discover(file).map_err(|e| CliError::Pkg(e.to_string()))?;
    let project_pass = |checked: &blue_lang_runtime::pipeline::Checked| {
        blue_lang_pkg::project_rules::check(
            &checked.program,
            &checked.call_explicit_forms(),
            &rules,
            &loader,
            blue_lang_runtime::project_rules::RULE_STEPS,
        )
    };
    let mut checked = check_entry(entry(file, &src), &loader, None, Checking::WithTests)?;
    let mut project = project_pass(&checked);
    // A fix can expose the next one (a moved name's fix leaves the old
    // package's `use` unreached), so fix until nothing applies, bounded.
    for _ in 0..if fix { 4 } else { 0 } {
        let (fixed, applied) = diagnostics::apply_machine_fixes(
            &checked.program,
            &checked.outcome,
            &project,
            &src,
            &only,
        );
        if applied == 0 {
            break;
        }
        {
            std::fs::write(file, &fixed).map_err(|source| CliError::Write {
                path: file.display().to_string(),
                source,
            })?;
            eprintln!("blue: applied {applied} fix(es) to {}", file.display());
            // Re-format (`--fix` is an explicit write) and
            // re-check what is now on disk.
            src = if only.is_empty() {
                blue_lang_pkg::canonical::read_layout(file)?
            } else {
                fixed
            };
            checked = check_entry(entry(file, &src), &loader, None, Checking::WithTests)?;
            project = project_pass(&checked);
        }
    }
    if fix
        && (only.is_empty()
            || only.iter().any(|c| {
                matches!(
                    c,
                    blue_lang_check::Code::B0019 | blue_lang_check::Code::B0074
                )
            }))
        && blue_lang_runtime::uses::Loader::entry_package(&loader, file).is_some()
    {
        let dir = manifest_dir_of(file);
        let disagrees = checked.outcome.diagnostics.iter().any(|d| {
            matches!(
                d.code,
                blue_lang_check::Code::B0019 | blue_lang_check::Code::B0074
            )
        });
        let stale = matches!(
            blue_lang_pkg::lock::confirm_dir(&dir)?,
            Freshness::Stale { reason } if reason != blue_lang_pkg::lock::Staleness::Missing
        );
        if disagrees || stale {
            let bluefile = dir.join(blue_lang_pkg::MANIFEST_FILE);
            let (removed, renamed) = match blue_lang_pkg::needs::prune(&dir, &loader)
                .map_err(CliError::Pkg)?
            {
                Some(p) => {
                    std::fs::write(&bluefile, &p.bluefile).map_err(|source| CliError::Write {
                        path: bluefile.display().to_string(),
                        source,
                    })?;
                    (p.removed, p.renamed)
                }
                None => (Vec::new(), Vec::new()),
            };
            let lock = blue_lang_pkg::lock::lock_dir(&dir, &prefetch::NixPrefetch)?;
            let lock_path = dir.join(LOCK_FILE);
            std::fs::write(&lock_path, blue_lang_pkg::lock::render(&lock)?).map_err(|source| {
                CliError::Write {
                    path: lock_path.display().to_string(),
                    source,
                }
            })?;
            eprintln!(
                "blue: {}: unused needs rows removed {removed:?}, moved rows rewritten {renamed:?}; relocked {} (needs {:?})",
                bluefile.display(),
                lock_path.display(),
                lock.manifest.needs.keys().collect::<Vec<_>>()
            );
            checked = check_entry(entry(file, &src), &loader, None, Checking::WithTests)?;
            project = project_pass(&checked);
        }
    }
    if fix && only.is_empty() {
        if let Ok(canonical) = blue_lang_pkg::canonical::format_resolved(file, &src) {
            if canonical.trim_end() != src.trim_end() {
                std::fs::write(file, &canonical).map_err(|source| CliError::Write {
                    path: file.display().to_string(),
                    source,
                })?;
                eprintln!("blue: formatted {}", file.display());
                src = canonical;
                checked = check_entry(entry(file, &src), &loader, None, Checking::WithTests)?;
                project = project_pass(&checked);
            }
        }
    }
    let mut with_form = checked.outcome.clone();
    let entry_form = (0..checked.program.forms().len())
        .find(|i| {
            checked.program.owner_of(*i) == Some(blue_lang_runtime::uses::ResolvedProgram::ENTRY)
        })
        .unwrap_or(0);
    with_form.diagnostics.extend(
        blue_lang_runtime::pipeline::form_diagnostics(&src)
            .into_iter()
            .map(|d| d.at_top_level(entry_form)),
    );
    let outcome = &with_form;
    match format {
        Format::Json => {
            print!("{}", diagnostics::json_lines(&checked.program, outcome)?);
            print!(
                "{}",
                diagnostics::overrides_json(&checked, &checked.resolve())?
            );
            print!(
                "{}",
                diagnostics::project_json_lines(&checked.program, &project)?
            );
        }
        Format::Text => {
            // Report the analysis performed, not just pass/fail. §0's rule is
            // that an invisible cost is the one unacceptable outcome, and the
            // cost of typing is analysis — so it is printed.
            println!("typed declarations: {}", outcome.stats.typed_decls);
            println!("nodes analysed:     {}", outcome.stats.visited);
            println!("seams:              {}", outcome.seams.len());
            println!("names resolved:     {}", outcome.stats.names_resolved);
            println!(
                "waived:             {}",
                outcome.waived.len() + project.waived.len()
            );
            if !rules.is_empty() {
                println!("project rules:      {}", rules.len());
            }
            // `file:line:col`, the shape every editor and every `cc` already
            // knows how to jump to.
            for seam in &outcome.seams {
                let (line, col) = blue_lang_syntax::Span::line_col(&src, seam.span.start);
                println!(
                    "  {} seam at {} expects {:?}",
                    Located {
                        file: file.display().to_string(),
                        line,
                        col,
                    },
                    seam.at,
                    seam.expected
                );
            }
            for w in &outcome.waived {
                println!(
                    "  {}",
                    render(
                        &checked.program,
                        &blue_lang_check::Diagnostic::new(
                            w.diagnostic.code,
                            format!("waived: {} ({})", w.diagnostic.message, w.waiver.reason),
                            w.diagnostic.span,
                        )
                        .at_top_level(w.diagnostic.top_level)
                    )
                );
            }
            for w in &project.waived {
                let mut shown = w.finding.clone();
                shown.message = format!("waived: {} ({})", shown.message, w.waiver.reason);
                shown.help = None;
                println!(
                    "  {}",
                    diagnostics::render_finding(&checked.program, &shown)
                );
            }
            for d in outcome.diagnostics.iter().chain(&project.diagnostics) {
                eprintln!("{}", render(&checked.program, d));
            }
            for f in &project.findings {
                eprintln!("{}", diagnostics::render_finding(&checked.program, f));
            }
            for f in &project.failures {
                eprintln!("{}", diagnostics::render_failure(&checked.program, f));
            }
        }
    }
    Ok(if outcome.ok() && project.ok() {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    })
}

/// Bind `--input name=path` pairs against the program's own `definput`
/// declarations.
///
/// The declaration is the contract and the flag supplies the material. Both
/// halves are required, and each missing half is its own error: supplying bytes
/// for a name the program never declared is a different mistake from declaring
/// a name and forgetting the flag, and telling them apart is the difference
/// between a fixable message and a puzzle.
fn bind_inputs(
    src: &str,
    pairs: &[String],
    cfg: &BlueConfig,
) -> Result<blue_lang_runtime::Inputs, CliError> {
    let forms = parse(src, cfg)?;
    let declared = blue_lang_runtime::declarations(&forms);
    let mut inputs = blue_lang_runtime::Inputs::new();

    for pair in pairs {
        let (name, path) = pair.split_once('=').ok_or_else(|| {
            CliError::Pkg("--input expects NAME=PATH, e.g. --input schema=./schema.json".into())
        })?;
        let decl = declared.iter().find(|d| d.name == name).ok_or_else(|| {
            CliError::Pkg(
                "`".to_string()
                    + name
                    + "` was supplied but the program never declares it. Add                        definput(\"" + name + "\", \"b3:…\").",
            )
        })?;
        let bytes = std::fs::read(path).map_err(|source| CliError::Read {
            path: path.to_string(),
            source,
        })?;
        inputs
            .bind(decl, bytes)
            .map_err(|e| CliError::Pkg(e.to_string()))?;
    }

    // A declaration with no material is refused rather than left absent: the
    // macro would otherwise fail deep inside expansion with "no input named …",
    // which points at the macro instead of at the missing flag.
    if let Some(missing) = declared.iter().find(|d| inputs.get(&d.name).is_none()) {
        return Err(CliError::Pkg(
            "input `".to_string()
                + &missing.name
                + "` is declared but no bytes were supplied — pass --input "
                + &missing.name
                + "=<path>",
        ));
    }
    Ok(inputs)
}

fn describe_reach(r: &blue_lang_waku::Reach) -> String {
    match r {
        blue_lang_waku::Reach::Unrestricted => "unrestricted".to_string(),
        blue_lang_waku::Reach::Only(caps) => {
            // Capability LABELS, not the names they grant. A frame's `Reach` is
            // ten things at most; printing the ~66 identifiers behind them would
            // bury the one fact an operator is reading for — whether the frame
            // opens a host effect.
            let list = caps
                .iter()
                .map(|c| c.label())
                .collect::<Vec<_>>()
                .join(", ");
            let mut out = String::with_capacity(list.len() + 6);
            out.push_str("only ");
            out.push_str(&list);
            out
        }
    }
}

/// A value as the operator should read it.
///
/// A `Display` on `Value` would be tatara-lisp's call to make, not blue's, so
/// this is a small local projection rather than a `format!` of arbitrary
/// structure — it names each shape it prints.
fn render(v: &tatara_lisp_eval::Value) -> String {
    use tatara_lisp_eval::Value;
    match v {
        Value::Nil => "nil".to_string(),
        Value::Bool(b) => b.to_string(),
        Value::Int(n) => n.to_string(),
        Value::Float(x) => x.to_string(),
        Value::Str(s) => s.to_string(),
        Value::Symbol(s) => s.to_string(),
        Value::Keyword(k) => {
            let mut out = String::with_capacity(k.len() + 1);
            out.push(':');
            out.push_str(k);
            out
        }
        Value::List(items) => {
            let inner = items.iter().map(render).collect::<Vec<_>>().join(", ");
            let mut out = String::with_capacity(inner.len() + 2);
            out.push('[');
            out.push_str(&inner);
            out.push(']');
            out
        }
        other => format!("{other:?}"),
    }
}

/// Which `yakugo` surface to parse in: `BLUE_LANG`, else the host locale.
fn resolve_surface() -> Result<Option<blue_lang_syntax::yakugo::Yakugo>, String> {
    if let Ok(tag) = std::env::var("BLUE_LANG") {
        if tag.is_empty() {
            return Ok(None);
        }
        return match blue_lang_syntax::yakugo::pack_for_locale(&tag)? {
            Some(p) => Ok(Some(p)),
            None => Err(format!(
                "BLUE_LANG=\"{tag}\" names no surface. Available: {}",
                blue_lang_syntax::yakugo::BUILTIN_PACKS
                    .iter()
                    .map(|(t, _)| *t)
                    .collect::<Vec<_>>()
                    .join(", ")
            )),
        };
    }
    // The host locale is a HINT, so an unrecognised one is simply English —
    // unlike an explicit BLUE_LANG, nobody asked for it.
    for var in ["LC_ALL", "LC_MESSAGES", "LANG"] {
        if let Ok(loc) = std::env::var(var) {
            if let Some(p) = blue_lang_syntax::yakugo::pack_for_locale(&loc)? {
                return Ok(Some(p));
            }
        }
    }
    Ok(None)
}