cyberbrain 0.7.0

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

mod app;
mod audit_bridge;
mod cli;
mod daemon;
mod hook;
mod hostload;
mod hub;
mod identity;
mod import;
mod install;
mod mcp;
mod render;
mod serve;
mod terminal;
mod usage;
mod writers;

use app::{
    App, AuditView, InvalidateRequest, RecallRequest, ScanOptions, WriteOutcome, WriteRequest,
};
use clap::Parser;
use cli::{Cli, Command, ExportFormat, PolicyCommand};
use cyberbrain_core::{Error, Result, Ring};
use cyberbrain_policy::{Actor, AuditFilter};
use serde::Serialize;
use std::io::{Read, Write};

/// How the command wants its output.
#[derive(Clone, Copy)]
struct Out {
    json: bool,
    quiet: bool,
}

impl Out {
    fn emit<T: Serialize>(self, value: &T, human: impl FnOnce(&T) -> String) -> Result<()> {
        if self.quiet {
            return Ok(());
        }
        let text = if self.json {
            serde_json::to_string_pretty(value)
                .map_err(|e| Error::Index(format!("report does not serialise: {e}")))?
        } else {
            human(value)
        };
        self.print(&text);
        Ok(())
    }

    /// Text that is already what `emit` would have made of a value (the daemon's answer).
    fn print(self, text: &str) {
        let mut stdout = std::io::stdout().lock();
        let _ = stdout.write_all(text.as_bytes());
        if !text.ends_with('\n') {
            let _ = stdout.write_all(b"\n");
        }
    }
}

/// SPEC §8.1: one failure taxonomy, three front ends. Delegates to the core, where the
/// names live beside the exit codes; kept as a crate-local alias so `serve` and `mcp` do
/// not each reach for a different spelling of the same thing.
fn error_code(e: &Error) -> &'static str {
    e.code()
}

fn report_error(e: &Error, json: bool) {
    eprintln!("{}", error_text(e, json));
}

/// The line `report_error` prints, so the daemon can hand back the same one.
fn error_text(e: &Error, json: bool) -> String {
    let code = e.exit_code();
    if json {
        serde_json::json!({
            "error": { "code": error_code(e), "message": e.to_string(), "exit_code": code }
        })
        .to_string()
    } else {
        let prefix = if code == 3 { "refused" } else { "error" };
        format!("cyberbrain: {prefix}: {e}")
    }
}

/// How the CLI shows a write's outcome; shared with the daemon.
fn render_write(o: &WriteOutcome) -> String {
    match o {
        WriteOutcome::Written(w) => render::written(w),
        WriteOutcome::Held { rendered, .. } => format!(
            "{rendered}Nothing was written. Re-run with --force to write it flagged, \
             or edit the body.\n"
        ),
        WriteOutcome::Conflict {
            name,
            current_updated,
        } => {
            format!("{name} changed at {current_updated} since it was read; nothing was written\n")
        }
    }
}

/// The exit a write's outcome means: 0, 3 for a hold, an error for a conflict.
fn write_exit(o: &WriteOutcome) -> Result<i32> {
    match o {
        WriteOutcome::Written(_) => Ok(0),
        WriteOutcome::Held { .. } => Ok(3),
        WriteOutcome::Conflict { .. } => Err(Error::StoreIntegrity(
            "the note changed since it was read".into(),
        )),
    }
}

/// Who is at this command line: the operator, or an agent running it through its shell?
///
/// 2026-09-25: every CLI command opened the store as `Actor::Operator`. An agent that ran
/// `cyberbrain write --ring 0` through Bash therefore passed the ring-owner check that 0.6.1
/// put into `App::write`, and the audit log recorded it as the operator — 3,437 of 4,062 rows
/// in one store said "operator", most of them agents. Claude Code sets `CLAUDECODE=1` for the
/// commands it runs; `CYBERBRAIN_AGENT=<name>` lets any other harness say the same.
///
/// This is attribution and a guard against the ordinary course of work, not a boundary
/// against an agent that sets out to lie: it controls its own environment. Unsetting the
/// variable next to a `cyberbrain` call is what the pre-tool-use hook refuses for Bash.
fn cli_actor() -> Actor {
    agent_from_env(|k| std::env::var(k).ok()).unwrap_or(Actor::Operator)
}

fn agent_from_env(var: impl Fn(&str) -> Option<String>) -> Option<Actor> {
    let set = |k: &str| {
        var(k)
            .map(|v| v.trim().to_string())
            .filter(|v| !v.is_empty())
    };
    if set("CLAUDECODE").is_some() {
        // A prefix of the session id is enough to find the session again; the whole id
        // would put a resumable handle into every audit row.
        let session: String = set("CLAUDE_CODE_SESSION_ID")
            .unwrap_or_default()
            .chars()
            .filter(char::is_ascii_alphanumeric)
            .take(8)
            .collect();
        return Some(Actor::Agent(if session.is_empty() {
            "claude-code".to_string()
        } else {
            format!("claude-code:{session}")
        }));
    }
    set("CYBERBRAIN_AGENT").map(|n| {
        Actor::Agent(
            n.chars()
                .filter(|c| c.is_ascii_alphanumeric() || "-_.:".contains(*c))
                .take(64)
                .collect(),
        )
    })
}

fn runtime() -> Result<tokio::runtime::Runtime> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|e| Error::Index(format!("cannot start the async runtime: {e}")))
}

fn read_stdin() -> Result<String> {
    let mut s = String::new();
    std::io::stdin()
        .read_to_string(&mut s)
        .map_err(|e| Error::Io {
            path: "<stdin>".into(),
            source: e,
        })?;
    Ok(s)
}

/// The stack this program runs on, chosen rather than inherited.
///
/// The main thread's stack size is fixed by the linker and differs by platform: 8 MB on the
/// Linux this is developed on, 1 MB on Windows. Building the command tree is recursive, and
/// in a debug build — no inlining, every frame its full size — it is deep enough that 1 MB
/// is not enough. `cyberbrain --version` aborted with "thread 'main' has overflowed its
/// stack" before it had parsed anything.
///
/// The release build fits, which is the worst shape this bug could have: the build that
/// overflows is the one the tests run, so the Windows half of the test suite stopped running
/// while the shipped binary was fine. Sixteen megabytes is not a measurement of what is
/// needed; it is far enough above it that the next few subcommands do not bring this back.
const STACK_BYTES: usize = 16 * 1024 * 1024;

fn main() {
    // Named, because a stack overflow names the thread and "cyberbrain" is a better thing to
    // read in that message than "unnamed".
    let worker = std::thread::Builder::new()
        .name("cyberbrain".to_string())
        .stack_size(STACK_BYTES)
        .spawn(real_main);
    let code = match worker {
        Ok(h) => h.join().unwrap_or(2),
        // A machine that cannot spawn a thread has worse problems, and refusing to run at
        // all over it would be a worse answer than running on the stack we were given.
        Err(_) => real_main(),
    };
    std::process::exit(code);
}

fn real_main() -> i32 {
    let cli = Cli::parse();
    let out = Out {
        json: cli.json,
        quiet: cli.quiet,
    };
    match run(cli, out) {
        Ok(code) => code,
        Err(e) => {
            report_error(&e, out.json);
            e.exit_code()
        }
    }
}

/// Returns the exit code. `Ok(3)` is a policy decision that is not an error: the write was
/// held and printed, and the caller must answer.
fn run(cli: Cli, out: Out) -> Result<i32> {
    match cli.command {
        Command::Init { path } => {
            let root = match path.or(cli.store) {
                Some(p) => p,
                None => std::env::current_dir()
                    .map_err(|e| Error::Io {
                        path: ".".into(),
                        source: e,
                    })?
                    .join(cyberbrain_core::config::DEFAULT_STORE_DIR),
            };
            let r = App::init(&root, &cli_actor())?;
            out.emit(&r, render::init)?;
            return Ok(0);
        }
        // SPEC §9.1: a hook never fails the harness. Until it is wired, it stands down
        // audibly on stderr and exits 0 with empty output, which is also what the Windows
        // CI job invoking it through cmd.exe requires.
        Command::Hook { event } => {
            hook::install_never_fail_guard();
            // Not `read_stdin()`: that returns an error on invalid UTF-8, and a hook that
            // errors on a malformed payload is a hook that failed the harness (SPEC §9.1).
            let mut raw = Vec::new();
            let _ = std::io::Read::read_to_end(&mut std::io::stdin(), &mut raw);
            let stdin = String::from_utf8_lossy(&raw);
            // The session says which project it is in; that beats the directory this
            // process happens to have been started in. They agree today, and relying on
            // that would mean reading another project's memory the day they do not.
            let session_cwd = serde_json::from_str::<serde_json::Value>(&stdin)
                .ok()
                .and_then(|v| Some(std::path::PathBuf::from(v.get("cwd")?.as_str()?)));
            let opened = App::open_from(
                cli.store.as_deref(),
                session_cwd.as_deref(),
                Actor::Hook(hook::event_name(event).into()),
            );
            let out = hook::run_with(opened.as_ref().ok(), opened.as_ref().err(), event, &stdin);
            out.emit();
            // Always 0. An unreachable store, a malformed payload and an internal error are
            // all reported through stdout, never through the exit code.
            return Ok(out.exit_code);
        }

        Command::Serve {
            port,
            no_open,
            terminal,
        } => {
            let app = std::sync::Arc::new(App::open(cli.store.as_deref(), Actor::Operator)?);
            runtime()?.block_on(serve::serve(app, port, !no_open, terminal))?;
            return Ok(0);
        }
        Command::Daemon { idle_secs } => {
            let app = App::open(cli.store.as_deref(), Actor::System("daemon".into()))?;
            return daemon::serve(app, idle_secs);
        }
        Command::Mcp => {
            let app = std::sync::Arc::new(App::open(cli.store.as_deref(), Actor::Mcp)?);
            runtime()?.block_on(mcp::serve_stdio(app))?;
            return Ok(0);
        }

        // A store is needed for its path, not its contents: the entry this writes names
        // the store so that a desktop client, which starts the process wherever it likes,
        // talks to this project and not to whichever one it lands in.
        Command::Install {
            ref client,
            ref project,
            ref name,
            undo,
            dry_run,
        } => {
            let project = match project {
                Some(p) => p.clone(),
                None => std::env::current_dir().map_err(|e| Error::Io {
                    path: ".".into(),
                    source: e,
                })?,
            };
            let store = match cli.store.as_deref() {
                Some(_) => app::discover_store(cli.store.as_deref())?,
                None => app::discover_store_from(Some(&project))?,
            };
            let opts = install::Options {
                clients: client.iter().copied().map(Into::into).collect(),
                project,
                store,
                name: name.clone(),
                undo,
                dry_run,
                env: install::Env::current(),
            };
            let r = install::run(&opts)?;
            out.emit(&r, render::install)?;
            return Ok(0);
        }

        // No store either: the hub keeps its own record of other machines' rows, and the
        // notes on this machine are none of its business.
        Command::Hub { ref command } => return run_hub(command, cli.store.as_deref(), out),

        // No store: the point of this one is that a person who was handed a file can check
        // it with nothing but the binary. Opening a store first would make it useless
        // exactly where it is needed.
        Command::VerifyExport { ref path } => {
            let text = std::fs::read_to_string(path).map_err(|e| Error::Io {
                path: path.clone(),
                source: e,
            })?;
            let report = cyberbrain_policy::bundle::verify(&text)?;
            out.emit(&report, render::verify_export)?;
            return Ok(0);
        }

        _ => {}
    }

    let app = App::open(cli.store.as_deref(), cli_actor())?;
    match cli.command {
        Command::Scan { full, dry_run } => {
            // A scan with something to embed loads the model, which the daemon already has
            // (`daemon.rs`); one with nothing to do is answered here in milliseconds. Like a
            // write, a scan that reached the daemon is never repeated here.
            if app.scan_has_work(full)? {
                match daemon::scan(app.root(), &cli_actor(), full, dry_run, out.json)? {
                    daemon::Answer::Done {
                        stdout,
                        stderr,
                        code,
                    } => {
                        if let Some(text) = stdout.filter(|_| !out.quiet) {
                            out.print(&text);
                        }
                        if let Some(line) = stderr {
                            eprintln!("{line}");
                        }
                        return Ok(code);
                    }
                    daemon::Answer::Local => {}
                }
            }
            let r = app.scan(ScanOptions { full, dry_run })?;
            out.emit(&r, render::scan)?;
        }
        Command::Recall {
            query,
            id,
            n,
            ring,
            bereich,
            stand,
        } => {
            if let Some(id) = id {
                let r = app.recall_id(&id)?;
                out.emit(&r, render::expanded)?;
            } else {
                let query = query.ok_or_else(|| {
                    Error::Config("recall needs a query, or --id <citation>".into())
                })?;
                let ring = ring.map(Ring::try_from).transpose()?;
                let req = RecallRequest {
                    n: Some(n),
                    ring,
                    bereich,
                    at: stand,
                };
                // The resident daemon answers in milliseconds what takes this process over a
                // second to load for (`daemon.rs`); anything short of a clean answer lands here.
                if !out.quiet
                    && let Some(text) =
                        daemon::recall(app.root(), &cli_actor(), &query, &req, out.json)
                {
                    out.print(&text);
                    return Ok(0);
                }
                let r = runtime()?.block_on(app.recall(&query, &req))?;
                out.emit(&r, render::recall)?;
            }
        }
        Command::Find { symbol, limit } => {
            let r = app.find(&symbol, limit)?;
            out.emit(&r, render::find)?;
        }
        Command::Write {
            ring,
            kind,
            name,
            body,
            tags,
            bereich,
            retention,
            supersedes,
            valid_from,
            invalid_at,
            force,
            dry_run,
        } => {
            let body = match body {
                Some(b) => b,
                None => read_stdin()?,
            };
            let req = WriteRequest {
                ring: Ring::try_from(ring)?,
                kind: kind.into(),
                name,
                body,
                tags,
                bereich: bereich.clone().map(Some),
                retention: retention.clone().map(Some),
                force,
                choice: None,
                expected_updated: None,
                supersedes: (!supersedes.is_empty()).then_some(supersedes),
                valid_from: valid_from.map(Some),
                invalid_at: invalid_at.map(Some),
                arriving: None,
                dry_run,
            };
            // A write embeds its note, which costs the same model load a recall does; the
            // daemon has it loaded (`daemon.rs`). Unlike a recall, a write that reached the
            // daemon is never repeated here: `daemon::write` says whether it did.
            match daemon::write(app.root(), &cli_actor(), &req, out.json)? {
                daemon::Answer::Done {
                    stdout,
                    stderr,
                    code,
                } => {
                    if let Some(text) = stdout.filter(|_| !out.quiet) {
                        out.print(&text);
                    }
                    if let Some(line) = stderr {
                        eprintln!("{line}");
                    }
                    return Ok(code);
                }
                daemon::Answer::Local => {}
            }
            let outcome = app.write(req)?;
            out.emit(&outcome, render_write)?;
            let code = write_exit(&outcome)?;
            if code != 0 {
                return Ok(code);
            }
        }
        Command::Propose {
            ring,
            kind,
            name,
            body,
            tags,
            bereich,
            retention,
            force,
            dry_run,
        } => {
            let who = identity::who(app.root())?;
            let body = match body {
                Some(b) => b,
                None => read_stdin()?,
            };
            let req = WriteRequest {
                ring: Ring::try_from(ring)?,
                kind: kind.into(),
                name,
                body,
                tags,
                bereich: bereich.clone().map(Some),
                retention: retention.clone().map(Some),
                force,
                choice: None,
                expected_updated: None,
                supersedes: None,
                valid_from: None,
                invalid_at: None,
                arriving: None,
                dry_run,
            };
            let outcome = app.propose(req, &who)?;
            out.emit(&outcome, |o| match o {
                app::Proposed::Written(r) => render::proposed(r),
                app::Proposed::Held { rendered, .. } => format!(
                    "{rendered}Nothing was proposed. Re-run with --force to propose it \
                     flagged, or edit the body.\n"
                ),
            })?;
            if matches!(outcome, app::Proposed::Held { .. }) {
                return Ok(3);
            }
        }

        Command::Review {
            target,
            accept,
            reject,
            reason,
            force,
            dry_run,
        } => {
            let Some(name) = target else {
                let waiting = app.proposals()?;
                out.emit(&waiting, |w| render::proposals(w))?;
                return Ok(0);
            };
            if accept == reject {
                return Err(Error::Config(
                    "say which: --accept or --reject. Listing what is waiting is \
                     `cyberbrain review` with no name"
                        .into(),
                ));
            }
            let req = app::ReviewRequest {
                name,
                accept,
                reason: reason.unwrap_or_default(),
                by: identity::who(app.root())?,
                force,
                dry_run,
            };
            let r = app.review(req)?;
            out.emit(&r, render::reviewed)?;
        }

        Command::Invalidate {
            name,
            at,
            by,
            clear,
            dry_run,
        } => {
            let r = app.invalidate(InvalidateRequest {
                name,
                at,
                clear,
                by,
                dry_run,
            })?;
            out.emit(&r, render::invalidated)?;
        }
        Command::Forget { target, dry_run } => {
            // Read before the erasure, because afterwards there is nothing left to ask.
            let shared = app.shared_copy_sentence(&target);
            let r = app.forget(&target, dry_run)?;
            out.emit(&r, cyberbrain_policy::erasure::render)?;
            // Art. 17 does not stop at this disk. Erasing locally and saying nothing about
            // the copy on the hub would make `forget` a promise that only half holds.
            if let Some(sentence) = shared {
                eprintln!("\n{sentence}\n");
            }
        }
        Command::Import {
            suggest,
            plan,
            accept_pii,
            dry_run,
        } => {
            if let Some(folder) = suggest {
                let s = import::suggest::survey(&folder)?;
                // The plan goes to stdout and the summary to stderr, so `> plan.toml` gives
                // a file that runs and the person still reads what was guessed.
                eprintln!("{}", import::suggest::summary(&s));
                print!("{}", import::suggest::to_plan(&s));
                return Ok(0);
            }
            let plan_path = plan.ok_or_else(|| {
                Error::Config("import needs --plan <file>, or --suggest <folder>".into())
            })?;
            let mut plan = import::load_plan(&plan_path)?;
            if accept_pii {
                plan.accept_pii = true;
            }
            let r = import::import(&app, &plan, dry_run)?;
            out.emit(&r, import::render)?;
            // 0 clean, 1 something did not make it, 2 the ledger does not close,
            // 3 only PII holds remain. The ledger failing is an internal error on purpose:
            // it means the importer cannot account for the corpus it just read.
            return Ok(import::exit_code(&r));
        }
        Command::Manifest { path } => {
            let dir = path.unwrap_or_else(|| app.config().model_dir());
            let r = app.write_manifest(&dir)?;
            out.emit(&r, render::manifest)?;
        }
        Command::Doctor => {
            let r = app.doctor()?;
            out.emit(&r, render::doctor)?;
        }
        Command::Status => {
            let r = runtime()?.block_on(app.status())?;
            out.emit(&r, render::status)?;
        }
        Command::Export { target, format } => {
            let r = app.export(&target)?;
            match format {
                ExportFormat::Md => out.emit(&r, |n| {
                    cyberbrain_core::frontmatter::render(&n.front, &n.body)
                        .unwrap_or_else(|e| format!("cannot render: {e}"))
                })?,
                ExportFormat::Json => Out { json: true, ..out }.emit(&r, render::note)?,
            }
        }
        Command::Policy { command } => return run_policy(&app, command, out),
        Command::Init { .. }
        | Command::Hook { .. }
        | Command::Serve { .. }
        | Command::Mcp
        | Command::Daemon { .. }
        | Command::Install { .. }
        | Command::Hub { .. }
        | Command::VerifyExport { .. } => {
            unreachable!("handled before the store was opened")
        }
    }
    Ok(0)
}

/// Licence handling. `keygen` and `issue` are the issuer's side; the rest is a customer's.
fn run_licence(command: &cli::LicenceCommand, out: Out) -> Result<i32> {
    use cli::LicenceCommand;

    match command {
        LicenceCommand::Install { path, data } => {
            let text = std::fs::read_to_string(path).map_err(|e| Error::Io {
                path: path.clone(),
                source: e,
            })?;
            // Checked before it is stored: an unreadable licence in the record would turn
            // every later command into the same complaint about a file nobody can fix.
            let signed = hub::licence::parse(&text)?;
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            store.set_licence(&text)?;
            let state = hub::LicenceState::read(&store, jiff::Timestamp::now());
            out.emit(
                &serde_json::json!({
                    "licence": signed.licence(),
                    "state": state.line(),
                    "collecting": state.may_collect(),
                }),
                |v| {
                    format!(
                        "installed: {} — {} seat(s), until {}\n{}\n",
                        v["licence"]["customer"].as_str().unwrap_or_default(),
                        v["licence"]["seats"].as_u64().unwrap_or_default(),
                        v["licence"]["valid_until"].as_str().unwrap_or_default(),
                        v["state"].as_str().unwrap_or_default()
                    )
                },
            )?;
            Ok(0)
        }

        LicenceCommand::Show { data } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let state = hub::LicenceState::read(&store, jiff::Timestamp::now());
            let devices = store.active_device_count()?;
            let seats_used = store.seats_in_use()?;
            out.emit(
                &serde_json::json!({
                    "state": state.line(),
                    "collecting": state.may_collect(),
                    "seats": state.seats(),
                    "seats_in_use": seats_used,
                    "devices_in_use": devices,
                }),
                |v| {
                    let mut s = format!("{}\n", v["state"].as_str().unwrap_or_default());
                    if let Some(seats) = v["seats"].as_u64() {
                        s.push_str(&format!(
                            "seats: {} of {} in use ({} device(s))\n",
                            v["seats_in_use"].as_u64().unwrap_or_default(),
                            seats,
                            v["devices_in_use"].as_u64().unwrap_or_default(),
                        ));
                    }
                    s
                },
            )?;
            // Non-zero when the hub is not collecting, so a monitoring check is one line.
            Ok(if state.may_collect() { 0 } else { 1 })
        }

        LicenceCommand::Keygen => {
            let (private, public) = hub::licence::generate_key()?;
            out.emit(
                &serde_json::json!({ "private_key": private, "public_key": public }),
                |v| {
                    format!(
                        "private key (keep it, never commit it, back it up):\n  {}\n\n\
                         public key (belongs in ISSUER_PUBLIC_KEY, needs a rebuild):\n  {}\n\n\
                         Whoever holds the private key can issue licences for this product.\n\
                         Losing it means no new licences; leaking it means anyone can make them.\n",
                        v["private_key"].as_str().unwrap_or_default(),
                        v["public_key"].as_str().unwrap_or_default()
                    )
                },
            )?;
            Ok(0)
        }

        LicenceCommand::Issue {
            key_file,
            customer,
            seats,
            from,
            until,
            out: out_path,
        } => {
            let key = std::fs::read_to_string(key_file)
                .map_err(|e| Error::Io {
                    path: key_file.clone(),
                    source: e,
                })?
                .trim()
                .to_string();
            let now = jiff::Timestamp::now();
            let valid_from = from.clone().unwrap_or_else(|| now.to_string());
            // Parsed here so a typo is caught while issuing, not by the customer's hub.
            for (what, value) in [("--from", &valid_from), ("--until", until)] {
                value.parse::<jiff::Timestamp>().map_err(|e| {
                    Error::Config(format!(
                        "{what}: {value:?} is not an RFC 3339 timestamp: {e}"
                    ))
                })?;
            }
            let licence = hub::licence::Licence {
                version: 1,
                id: format!("lic_{}", cyberbrain_core::NoteId::generate()),
                customer: customer.clone(),
                seats: *seats,
                valid_from,
                valid_until: until.clone(),
                issued_at: now.to_string(),
            };
            let signed = hub::licence::issue(&licence, &key)?;
            let text = signed.render();
            match out_path {
                Some(p) => {
                    std::fs::write(p, &text).map_err(|e| Error::Io {
                        path: p.clone(),
                        source: e,
                    })?;
                    out.emit(&serde_json::json!({ "licence": licence, "path": p }), |v| {
                        format!(
                            "issued {} for {} ({} seats, until {}) -> {}\n",
                            v["licence"]["id"].as_str().unwrap_or_default(),
                            v["licence"]["customer"].as_str().unwrap_or_default(),
                            v["licence"]["seats"].as_u64().unwrap_or_default(),
                            v["licence"]["valid_until"].as_str().unwrap_or_default(),
                            v["path"].as_str().unwrap_or_default()
                        )
                    })?;
                }
                None => print!("{text}"),
            }
            Ok(0)
        }
    }
}

/// The hub's commands. Most run a hub and open no store; `enrol` and `push` are the
/// client's side of the same feature and do open one, which is why the store path comes in
/// here rather than being reached for globally.
/// Register the hub as a Windows service, or control the one that is registered.
///
/// The certificate a hub serves with, for the two questions that come up about it: which one
/// is this, and how do I stop the browser complaining.
///
/// Only ever the hub's own, the pair beside the record. A certificate the operator supplied
/// is a file they already have, in a place they chose, and copying it around from here would
/// be this program being helpful about something it does not own.
fn run_hub_cert(command: &cli::CertCommand, out: Out) -> Result<i32> {
    use cli::CertCommand;
    let (data, to) = match command {
        CertCommand::Show { data } => (data, None),
        CertCommand::Export { to, data } => (data, Some(to)),
    };
    let record = hub::data_path(data.clone());
    let dir = record.parent().unwrap_or(std::path::Path::new("."));
    let cert = dir.join(hub::tls::OWN_CERT);
    if !cert.exists() {
        return Err(Error::Config(format!(
            "this hub has no certificate of its own: {} is not there. Either it serves one \
             you supplied, in which case that file is where you put it, or it is not \
             encrypted at all — start it with --tls-generate.",
            cert.display()
        )));
    }
    let fingerprint = hub::tls::fingerprint_of(&cert)?;
    if let Some(to) = to {
        // Copied rather than moved or linked: the hub goes on serving the original, and what
        // is handed out is a certificate, which is public by construction — it is what the
        // hub shows every machine that connects to it.
        std::fs::copy(&cert, to).map_err(|e| Error::Io {
            path: to.clone(),
            source: e,
        })?;
    }
    out.emit(
        &serde_json::json!({
            "certificate": cert,
            "sha256": fingerprint,
            "exported_to": to,
        }),
        |v| {
            let mut s = format!(
                "certificate: {}\nSHA-256:     {}\n",
                v["certificate"].as_str().unwrap_or_default(),
                v["sha256"].as_str().unwrap_or_default()
            );
            if let Some(to) = v["exported_to"].as_str() {
                s.push_str(&format!("copied to:   {to}\n"));
            }
            // The path, not the file name: the two lines below are meant to be copied, and
            // a hub's certificate is never in the directory somebody is standing in.
            let here = v["exported_to"]
                .as_str()
                .or_else(|| v["certificate"].as_str())
                .unwrap_or_default();
            s.push_str(
                "\nThis is what invitations pin, and enrolled machines need nothing else. A \
                 browser is the exception: it has never heard of this certificate and warns \
                 until the machine itself trusts it.\n\n",
            );
            // The platform this is running on, and only that one. Printing both put a
            // Windows path into a `cp` line on Windows, which is not an instruction, and an
            // instruction that cannot be right is a reason to distrust the ones that are.
            #[cfg(windows)]
            s.push_str(&format!(
                "In an elevated prompt:\n  certutil -addstore -f Root {here}\n"
            ));
            #[cfg(not(windows))]
            s.push_str(&format!(
                "As root:\n  cp {here} /usr/local/share/ca-certificates/cyberbrain-hub.crt \
                 && update-ca-certificates\n\
                 (the .crt ending is not decoration; the file is ignored without it)\n"
            ));
            s
        },
    )?;
    Ok(0)
}

/// The installer calls `install` with the same defaults, so a customer who ticks the box and
/// an administrator who types the command end up with exactly the same registration.
fn run_hub_service(command: &cli::ServiceCommand, out: Out) -> Result<i32> {
    use cli::ServiceCommand;
    use hub::service;

    match command {
        ServiceCommand::Install {
            data,
            addr,
            tls_cert,
            tls_key,
            insecure_http,
        } => {
            // Checked before anything is registered: a service that will not start because
            // of a typo in an address is diagnosed from services.msc, which is a bad place
            // to find out.
            let parsed = hub::parse_addr(addr)?;
            let path = data
                .clone()
                .unwrap_or_else(|| service::default_data_dir().join("hub.db"));
            if let Some(dir) = path.parent() {
                std::fs::create_dir_all(dir).map_err(|e| Error::Io {
                    path: dir.to_path_buf(),
                    source: e,
                })?;
            }
            // Generated where nothing was given, because this is the one moment a person is
            // standing there and because the customer this is for has no certificate to give.
            // A hub that listens to the network in the clear is now something somebody asked
            // for in writing, not what happens when they answer no questions.
            let own;
            let tls = match (tls_cert, tls_key) {
                (Some(c), Some(k)) => {
                    // Loaded here as well as at startup, because "the service was registered"
                    // and "the service will start" have to be the same sentence. The cost is
                    // reading two files twice.
                    hub::tls::load(c, k)?;
                    Some((c.as_path(), k.as_path()))
                }
                _ if *insecure_http || parsed.ip().is_loopback() => None,
                _ => {
                    let dir = path.parent().unwrap_or(std::path::Path::new("."));
                    own = hub::tls::ensure_self_signed(dir, &hub::tls::names_for(&parsed))?;
                    hub::tls::load(&own.0, &own.1)?;
                    Some((own.0.as_path(), own.1.as_path()))
                }
            };
            let exe = std::env::current_exe()
                .map_err(|e| Error::Config(format!("cannot find this program on disk: {e}")))?;
            service::install(&exe, &path, addr, tls)?;
            let drop =
                service::licence_drop_path(path.parent().unwrap_or(std::path::Path::new(".")));
            out.emit(
                &serde_json::json!({
                    "service": service::SERVICE_NAME,
                    "data": path,
                    "addr": parsed.to_string(),
                    "encrypted": tls.is_some(),
                    "certificate": tls.map(|(c, _)| c.display().to_string()),
                    "licence_drop": drop,
                    "state": "running",
                }),
                |v| {
                    format!(
                        "{} registered and started.\nrecord:  {}\nlistens: {} ({})\n\nPut a \
                         licence file at {} and restart the service; without one nothing is \
                         collected.\n",
                        service::DISPLAY_NAME,
                        v["data"].as_str().unwrap_or_default(),
                        v["addr"].as_str().unwrap_or_default(),
                        if v["encrypted"].as_bool().unwrap_or_default() {
                            "https"
                        } else {
                            "plain text"
                        },
                        v["licence_drop"].as_str().unwrap_or_default(),
                    )
                },
            )?;
            Ok(0)
        }
        ServiceCommand::Uninstall => {
            service::uninstall()?;
            // Said out loud because the opposite would be the surprise: removing the
            // software must not remove the evidence it was collecting.
            out.emit(
                &serde_json::json!({ "service": service::SERVICE_NAME, "state": "removed" }),
                |_| {
                    format!(
                        "{} removed. The record and the log are untouched.\n",
                        service::DISPLAY_NAME
                    )
                },
            )?;
            Ok(0)
        }
        ServiceCommand::Start | ServiceCommand::Stop => {
            let start = matches!(command, ServiceCommand::Start);
            service::set_state(start)?;
            out.emit(
                &serde_json::json!({
                    "service": service::SERVICE_NAME,
                    "state": if start { "starting" } else { "stopping" },
                }),
                |v| {
                    format!(
                        "{} {}\n",
                        service::DISPLAY_NAME,
                        v["state"].as_str().unwrap_or("")
                    )
                },
            )?;
            Ok(0)
        }
        ServiceCommand::Status => {
            let state = service::status()?;
            let running = state == "running";
            out.emit(
                &serde_json::json!({ "service": service::SERVICE_NAME, "state": state }),
                |v| {
                    format!(
                        "{} is {}\n",
                        service::DISPLAY_NAME,
                        v["state"].as_str().unwrap_or("")
                    )
                },
            )?;
            // Non-zero when it is not running, so a monitoring check is one line.
            Ok(if running { 0 } else { 1 })
        }
    }
}

fn run_hub(command: &cli::HubCommand, store: Option<&std::path::Path>, out: Out) -> Result<i32> {
    use cli::HubCommand;
    let now = || jiff::Timestamp::now().to_string();

    match command {
        HubCommand::Enrol { invitation } => {
            let text = std::fs::read_to_string(invitation).map_err(|e| Error::Io {
                path: invitation.clone(),
                source: e,
            })?;
            let app = App::open(store, cli_actor())?;
            // Two kinds. A personal invitation already carries a device and its token; a fleet
            // invitation carries a code, and the hub makes the device when it is asked.
            let (hub_url, device, token, pin, inference_url, fleet_name) =
                match hub::client::parse_any_invitation(&text)? {
                    hub::client::AnyInvitation::Device(inv) => (
                        inv.hub_url.clone().expect("checked while parsing"),
                        inv.device,
                        inv.token,
                        inv.hub_cert_sha256,
                        inv.inference_url,
                        None,
                    ),
                    hub::client::AnyInvitation::Fleet(inv) => {
                        let machine = hub::client::machine_name().ok_or_else(|| {
                            Error::Config(
                                "this machine reports no name, so the hub could not count its \
                                 seat; ask for a personal invitation (`hub add --invite`)"
                                    .into(),
                            )
                        })?;
                        let enrolled =
                            runtime()?.block_on(app.enrol_with_fleet_invitation(&inv, &machine))?;
                        (
                            inv.hub_url.clone(),
                            enrolled.device,
                            enrolled.token,
                            inv.hub_cert_sha256.clone(),
                            inv.inference_url.clone(),
                            Some(enrolled.name),
                        )
                    }
                };

            let token_at = hub::client::save_token(&hub_url, &device, &token)?;
            // Taken from the invitation and written down, or taken away again: enrolling
            // afresh with a hub that has since moved behind an ordinary certificate must not
            // leave this machine expecting the old key for ever.
            match &pin {
                Some(p) => {
                    hub::client::save_pin(&hub_url, p)?;
                }
                None => hub::client::forget_pin(&hub_url)?,
            }
            let inference = app.enrol_with_hub(&hub_url, &device, inference_url.as_deref())?;

            out.emit(
                &serde_json::json!({
                    "hub": hub_url,
                    "device": device,
                    "name": fleet_name,
                    "token_stored_at": token_at,
                    "pinned_certificate": pin,
                    "inference_endpoint": inference,
                }),
                |v| {
                    let mut s = format!(
                        "enrolled with {} as {}{}\ntoken stored at {}\n",
                        v["hub"].as_str().unwrap_or_default(),
                        v["device"].as_str().unwrap_or_default(),
                        v["name"]
                            .as_str()
                            .map(|n| format!(" ({n})"))
                            .unwrap_or_default(),
                        v["token_stored_at"].as_str().unwrap_or_default()
                    );
                    if let Some(p) = v["pinned_certificate"].as_str() {
                        s.push_str(&format!(
                            "this hub is pinned to the certificate {p}\n\
                             deliveries go nowhere else, whatever certificate is presented\n"
                        ));
                    }
                    if let Some(e) = v["inference_endpoint"].as_str() {
                        s.push_str(&format!("inference endpoint set to {e}\n"));
                    }
                    s.push_str(if v["name"].is_string() {
                        "\nThe invitation enrols further projects until it runs out or expires.\n\
                         Deliver with `cyberbrain hub push`, on a timer.\n"
                    } else {
                        "\nDelete the invitation file: it carries the token.\n\
                         Deliver with `cyberbrain hub push`, on a timer.\n"
                    });
                    s
                },
            )?;
            Ok(0)
        }

        HubCommand::Invite { command } => {
            use cli::InviteCommand;
            match command {
                InviteCommand::Create {
                    uses,
                    expires,
                    label,
                    hub_url,
                    inference_url,
                    out: path,
                    data,
                } => {
                    if path.exists() {
                        return Err(Error::Config(format!(
                            "{} exists already; an invitation is never written over a file",
                            path.display()
                        )));
                    }
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let (row, code) =
                        store.create_enrolment_code(label, *uses, expires, "cli", &now())?;
                    let invitation = serde_json::json!({
                        "kind": hub::client::FLEET_INVITATION_KIND,
                        "version": 1,
                        "code": code,
                        "label": row.label,
                        "hub_url": hub_url,
                        "inference_url": inference_url,
                        "hub_cert_sha256": hub::pin_to_offer(&store),
                        "expires_at": row.expires_at,
                    });
                    let text = serde_json::to_string_pretty(&invitation).map_err(|e| {
                        Error::Config(format!("invitation does not serialise: {e}"))
                    })?;
                    std::fs::write(path, format!("{text}\n")).map_err(|e| Error::Io {
                        path: path.clone(),
                        source: e,
                    })?;
                    out.emit(
                        &serde_json::json!({
                            "id": row.id, "label": row.label, "uses": row.max_uses,
                            "expires_at": row.expires_at, "file": path.display().to_string(),
                        }),
                        |v| {
                            format!(
                                "invitation {id} written to {}\n  label: {}\n  enrols up to {} \
                                 project(s) until {}\n\nThe file is a credential for every one of \
                                 them. Hand it out the way you would a password, for example from \
                                 a share only the rollout can read, and withdraw it once the \
                                 rollout is done:\n  cyberbrain hub invite revoke {id}\n",
                                v["file"].as_str().unwrap_or_default(),
                                v["label"].as_str().unwrap_or_default(),
                                v["uses"],
                                v["expires_at"].as_str().unwrap_or_default(),
                                id = v["id"].as_str().unwrap_or_default(),
                            )
                        },
                    )?;
                    Ok(0)
                }
                InviteCommand::List { data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let stamp = now();
                    let all = store.enrolment_codes()?;
                    out.emit(&serde_json::json!(all), |v| {
                        let rows = v.as_array().cloned().unwrap_or_default();
                        if rows.is_empty() {
                            return "No fleet invitations.\n".to_string();
                        }
                        let mut s = String::new();
                        for c in rows {
                            let state = if c["revoked_at"].is_string() {
                                "withdrawn".to_string()
                            } else if c["expires_at"].as_str().unwrap_or_default() <= stamp.as_str()
                            {
                                "expired".to_string()
                            } else if c["uses"].as_i64() >= c["max_uses"].as_i64() {
                                "used up".to_string()
                            } else {
                                format!(
                                    "works until {}",
                                    c["expires_at"].as_str().unwrap_or_default()
                                )
                            };
                            s.push_str(&format!(
                                "  {}  {}  {}/{} used  {state}\n",
                                c["id"].as_str().unwrap_or_default(),
                                c["label"].as_str().unwrap_or_default(),
                                c["uses"],
                                c["max_uses"],
                            ));
                        }
                        s
                    })?;
                    Ok(0)
                }
                InviteCommand::Revoke { id, data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let done = store.revoke_enrolment_code(id, "cli", &now())?;
                    out.emit(&serde_json::json!({ "id": id, "revoked": done }), |v| {
                        if v["revoked"].as_bool().unwrap_or(false) {
                            format!(
                                "{id} withdrawn. The projects it enrolled stay; nobody further \
                                 gets in with it.\n"
                            )
                        } else {
                            format!("{id}: no such invitation, or it was already withdrawn.\n")
                        }
                    })?;
                    Ok(if done { 0 } else { 1 })
                }
            }
        }

        HubCommand::Push {
            since,
            notes,
            bereich,
            dry_run,
        } => {
            let app = App::open(store, cli_actor())?;
            if *notes {
                let (report, code) =
                    runtime()?.block_on(app.push_notes_to_hub(bereich.as_deref(), *dry_run))?;
                out.emit(&report, |v| {
                    format!("{}\n", v["message"].as_str().unwrap_or_default())
                })?;
                return Ok(code);
            }
            if bereich.is_some() {
                return Err(Error::Config(
                    "--bereich selects notes; it needs --notes".into(),
                ));
            }
            let since = since
                .as_ref()
                .map(|s| {
                    s.parse::<jiff::Timestamp>().map_err(|e| {
                        Error::Config(format!("--since {s:?} is not an RFC 3339 timestamp: {e}"))
                    })
                })
                .transpose()?;
            let (report, code) = runtime()?.block_on(app.push_to_hub(since))?;
            out.emit(&report, |v| {
                format!("{}\n", v["message"].as_str().unwrap_or_default())
            })?;
            Ok(code)
        }

        HubCommand::Serve {
            addr,
            data,
            tls_cert,
            tls_key,
            tls_generate,
        } => {
            let path = hub::data_path(data.clone());
            let addr = hub::parse_addr(addr)?;
            // Read before the listener is opened. A certificate that cannot be loaded is the
            // operator's mistake to see at once, not a hub that comes up in plain text
            // because the file it was told to use had the wrong permissions.
            let dir = path
                .parent()
                .unwrap_or(std::path::Path::new("."))
                .to_path_buf();
            let tls = match (tls_cert, tls_key) {
                // Named paths, which is how the Windows service is registered even when the
                // installer made the pair itself — so the question of whose certificate this
                // is gets asked here rather than assumed from how it arrived.
                (Some(c), Some(k)) => Some(hub::tls::named(&dir, c, k)?),
                _ if *tls_generate => Some(hub::tls::own(&dir, &hub::tls::names_for(&addr))?),
                // clap's `requires` makes one-without-the-other unreachable from the command
                // line; the match still has to say what it means.
                _ => None,
            };
            // Set before anything can go wrong: started by the service control manager there
            // is no console, so a message that only reaches stdout reaches nobody — including
            // the one saying why the thing will not start.
            hub::service::set_log_path(&path);

            let serve: hub::service::Serve = {
                let path = path.clone();
                Box::new(move |stop| {
                    let store = hub::HubStore::open(&path)?;
                    // Written on every start and cleared when there is no pin, because an
                    // invitation is issued by a second process reading this record: a stale
                    // fingerprint here would send a machine off to expect a certificate this
                    // hub no longer serves.
                    hub::remember_pin(
                        &store,
                        tls.as_ref()
                            .filter(|c| c.pinnable)
                            .map(|c| c.fingerprint.as_str()),
                    )?;
                    // A licence dropped next to the record is taken on start, so licensing a
                    // hub is copying a file rather than typing a command with a path in it.
                    let dir = path.parent().unwrap_or(std::path::Path::new("."));
                    let note = hub::service::adopt_dropped_licence(&store, dir);
                    // Read once at startup, so whoever starts the hub sees the state without
                    // having to ask a second command.
                    let state = hub::LicenceState::read(&store, jiff::Timestamp::now());
                    let licence_line = state.line();
                    use hub::service::Dropped;
                    match note {
                        Dropped::Installed(m) | Dropped::Problem(m) => hub::service::log(&m),
                        // Silence is fine for a hub that was licensed months ago. For one
                        // that has no licence at all it is the opposite of fine: that is
                        // exactly the reader who needs to know where it looked.
                        Dropped::None if state == hub::LicenceState::Missing => {
                            hub::service::log(&hub::service::where_it_looked(dir));
                        }
                        Dropped::None | Dropped::Unchanged => {}
                    }
                    let path = path.clone();
                    let tls = tls.clone();
                    runtime()?.block_on(async move {
                        let listener = tokio::net::TcpListener::bind(addr)
                            .await
                            .map_err(|e| Error::Config(format!("cannot bind {addr}: {e}")))?;
                        let bound = listener.local_addr().map_err(|e| {
                            Error::Config(format!("cannot read the bound address: {e}"))
                        })?;
                        // Built after binding, so the address the page suggests for
                        // invitations is the one actually being listened on rather than the
                        // one that was asked for.
                        let state = std::sync::Arc::new(hub::api::HubState {
                            hub: std::sync::Mutex::new(store),
                            record: path.clone(),
                            port: bound.port(),
                            sessions: Default::default(),
                            flash: std::sync::Mutex::new(None),
                            encrypted: tls.is_some(),
                            enrol_attempts: Default::default(),
                            sign_in_refusals: Default::default(),
                        });
                        let scheme = if tls.is_some() { "https" } else { "http" };
                        let hello = format!(
                            "cyberbrain hub: {scheme}://{bound}/  (record: {}; devices \
                             authenticate with a bearer token)",
                            path.display()
                        );
                        println!("{hello}");
                        println!("{licence_line}");
                        hub::service::log(&hello);
                        hub::service::log(&licence_line);
                        match &tls {
                            // Printed every start, because the fingerprint is what somebody
                            // compares against the browser warning, and the moment they need
                            // it is the moment the hub was restarted onto a new certificate.
                            // Both are labelled with what they are for: they look alike and
                            // they are not interchangeable.
                            Some(cert) => {
                                let line = format!(
                                    "certificate SHA-256: {}{}",
                                    cert.fingerprint,
                                    if cert.pinnable {
                                        "  (invitations pin this)"
                                    } else {
                                        ""
                                    }
                                );
                                println!("{line}");
                                hub::service::log(&line);
                            }
                            // Not a warning on loopback: that hub is talking to itself.
                            None if !bound.ip().is_loopback() => {
                                let line = format!(
                                    "warning: {bound} is a network address and this hub is \
                                     not encrypted. Device tokens cross the network in the \
                                     clear and the password can only be typed at this \
                                     machine. Start it with --tls-cert and --tls-key."
                                );
                                eprintln!("{line}");
                                hub::service::log(&line);
                            }
                            None => {}
                        }
                        // With connect info, because who may set or type a password is
                        // decided by where the request came from.
                        let make = hub::api::router(state)
                            .into_make_service_with_connect_info::<std::net::SocketAddr>();
                        // The stop signal arrives on a plain channel from the service
                        // control handler, which is not async and must answer at once.
                        let stopped = async move {
                            let _ = tokio::task::spawn_blocking(move || stop.recv()).await;
                        };
                        match tls {
                            Some(cert) => hub::tls::serve(listener, make, cert, stopped).await,
                            None => axum::serve(listener, make)
                                .with_graceful_shutdown(async move {
                                    stopped.await;
                                    hub::service::log("stop requested; closing the listener");
                                })
                                .await
                                .map_err(|e| Error::Config(format!("hub: {e}"))),
                        }
                    })
                })
            };

            // Started by the service control manager this takes over and returns when the
            // service stops; started from a prompt it comes back false and we carry on as an
            // ordinary console server. One binary, no flag to remember.
            hub::service::set_serve(serve);
            if hub::service::try_dispatch()? {
                return Ok(0);
            }
            // No sender is ever used here, and `_never` holds the other end open so the
            // shutdown future waits rather than firing on a disconnected channel.
            let (_never, stop) = std::sync::mpsc::channel();
            hub::service::run_serve(stop)?;
            Ok(0)
        }

        HubCommand::Service { command } => run_hub_service(command, out),

        HubCommand::Admin { command } => {
            let cli::AdminCommand::Reset { data } = command;
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            store.set_setting("admin_password", "")?;
            out.emit(&serde_json::json!({ "admin": "reset" }), |_| {
                concat!(
                    "The administrator password is cleared. Open the hub's page on this ",
                    "machine to set a new one; from anywhere else it now says the hub has ",
                    "not been set up.\n"
                )
                .to_string()
            })?;
            Ok(0)
        }

        HubCommand::Add {
            name,
            data,
            invite,
            hub_url,
            machine,
            inference_url,
        } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let machine = machine
                .as_deref()
                .map(|m| {
                    hub::normalise_machine(m).ok_or_else(|| {
                        Error::Config(format!("--machine {m:?} is not a machine name"))
                    })
                })
                .transpose()?;
            // Seats are checked here rather than at delivery time. A device that was allowed
            // to enrol and is then refused every night is the worst of both: it looks
            // registered and collects nothing.
            let state = hub::LicenceState::read(&store, jiff::Timestamp::now());
            match state.seats() {
                None => {
                    return Err(Error::Config(format!(
                        "{}\nNo device can be registered without one.",
                        state.line()
                    )));
                }
                Some(seats) => {
                    let active = store.seats_in_use()?;
                    if store.needs_seat(machine.as_deref())? && active >= seats {
                        return Err(Error::Config(format!(
                            "the licence covers {seats} seat(s) and {active} are in use. \
                             Revoke a device that is gone, or extend the licence — its rows \
                             are kept either way."
                        )));
                    }
                }
            }
            let (device, token) = store.add_device(name, &now())?;
            if let Some(m) = &machine {
                store.set_machine(&device.id, m)?;
            }

            if let Some(path) = invite {
                // Taken from the record, which the running hub wrote when it started. A pin
                // is only issued when there is a hub currently serving with a key it could
                // name — an invitation that promises a certificate nobody serves is worse
                // than one that promises none.
                let pin = hub::pin_to_offer(&store);
                let invitation = serde_json::json!({
                    "kind": "cyberbrain.hub.invitation",
                    // 2 adds the pin. A client of either version reads either file: the
                    // field is absent on hubs that have no certificate of their own, and a
                    // missing pin means "verify the ordinary way", not "verify nothing".
                    "version": 2,
                    "device": device.id,
                    "name": device.name,
                    "token": token,
                    "hub_url": hub_url,
                    "inference_url": inference_url,
                    "hub_cert_sha256": pin,
                });
                let text = serde_json::to_string_pretty(&invitation)
                    .map_err(|e| Error::Config(format!("invitation does not serialise: {e}")))?;
                std::fs::write(path, format!("{text}\n")).map_err(|e| Error::Io {
                    path: path.clone(),
                    source: e,
                })?;
                out.emit(&invitation, |v| {
                    format!(
                        "device {} registered as {:?}\ninvitation written to {}\n\n\
                         It carries the token. Hand it over the way you would a password, \
                         and delete it once the machine has been set up.\n{}",
                        v["device"].as_str().unwrap_or_default(),
                        v["name"].as_str().unwrap_or_default(),
                        path.display(),
                        if v["hub_url"].is_null() {
                            "\nNo --hub-url was given, so the device still has to be told \
                             where to deliver.\n"
                        } else {
                            ""
                        }
                    )
                })?;
                return Ok(0);
            }

            out.emit(
                &serde_json::json!({ "device": device, "token": token }),
                |v| {
                    format!(
                        "device {} registered as {:?}\ntoken: {}\n\nThis is the only time the \
                         token is shown. The record keeps a hash of it.\n",
                        v["device"]["id"].as_str().unwrap_or_default(),
                        v["device"]["name"].as_str().unwrap_or_default(),
                        v["token"].as_str().unwrap_or_default()
                    )
                },
            )?;
            Ok(0)
        }

        HubCommand::Licence { command } => run_licence(command, out),

        HubCommand::Cert { command } => run_hub_cert(command, out),

        HubCommand::Fleet { data } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let version = env!("CARGO_PKG_VERSION");
            let rows = hub::report::fleet(&store, jiff::Timestamp::now(), version)?;
            let total = store.total_entries()?;
            let licence = hub::LicenceState::read(&store, jiff::Timestamp::now());
            let troubled = rows.iter().filter(|r| !r.concerns.is_empty()).count();

            out.emit(
                &serde_json::json!({
                    "devices": rows,
                    "total_rows": total,
                    "needs_attention": troubled,
                    "licence": licence.line(),
                    "collecting": licence.may_collect(),
                }),
                |v| {
                    let list = v["devices"].as_array().cloned().unwrap_or_default();
                    if list.is_empty() {
                        return "no devices registered yet; `cyberbrain hub add <name>`\n"
                            .to_string();
                    }
                    let mut s = String::new();
                    for d in list {
                        let concerns: Vec<String> = d["concerns"]
                            .as_array()
                            .map(|c| {
                                c.iter()
                                    .filter_map(|x| {
                                        serde_json::from_value::<hub::report::Concern>(x.clone())
                                            .ok()
                                    })
                                    .map(|c| c.line())
                                    .collect()
                            })
                            .unwrap_or_default();
                        // The marker is the first thing on the line, so a screen of devices
                        // can be scanned down one column.
                        let marker = if d["revoked_at"].is_string() {
                            "-"
                        } else if concerns.is_empty() {
                            "ok"
                        } else {
                            "!!"
                        };
                        s.push_str(&format!(
                            "{:<3} {:<22} {:>8} rows  {}\n",
                            marker,
                            match d["machine"].as_str() {
                                Some(m) =>
                                    format!("{} @{m}", d["name"].as_str().unwrap_or_default()),
                                None => d["name"].as_str().unwrap_or_default().to_string(),
                            },
                            d["rows"].as_i64().unwrap_or_default(),
                            if d["revoked_at"].is_string() {
                                "revoked".to_string()
                            } else if concerns.is_empty() {
                                format!("last seen {}", d["last_seen"].as_str().unwrap_or("never"))
                            } else {
                                concerns.join("; ")
                            }
                        ));
                    }
                    s.push_str(&format!(
                        "\n{} row(s) in the record, {} device(s) need attention\n{}\n",
                        v["total_rows"].as_i64().unwrap_or_default(),
                        v["needs_attention"].as_i64().unwrap_or_default(),
                        v["licence"].as_str().unwrap_or_default()
                    ));
                    s
                },
            )?;
            Ok(0)
        }

        HubCommand::Pull {
            apply_erasures,
            dry_run,
        } => {
            let app = App::open(store, cli_actor())?;
            let (report, code) =
                runtime()?.block_on(app.pull_notes_from_hub(*apply_erasures, *dry_run))?;
            out.emit(&report, |v| {
                let mut s = format!("{}\n", v["message"].as_str().unwrap_or_default());
                for k in v["kept_local"].as_array().cloned().unwrap_or_default() {
                    s.push_str(&format!(
                        "  kept local: {} (here {}, offered {})\n",
                        k["name"].as_str().unwrap_or_default(),
                        k["local"].as_str().unwrap_or_default(),
                        k["offered"].as_str().unwrap_or_default(),
                    ));
                }
                for e in v["erasures"].as_array().cloned().unwrap_or_default() {
                    if e["held_here"].as_bool().unwrap_or(false)
                        && !e["removed"].as_bool().unwrap_or(false)
                    {
                        s.push_str(&format!(
                            "  erased at the hub but still here: {} — `cyberbrain forget {}` \
                             or pull again with --apply-erasures\n",
                            e["name"].as_str().unwrap_or_default(),
                            e["name"].as_str().unwrap_or_default(),
                        ));
                    }
                }
                s
            })?;
            Ok(code)
        }
        HubCommand::Erase { name, bereich } => {
            let app = App::open(store, cli_actor())?;
            let (report, code) = runtime()?.block_on(app.erase_at_hub(bereich, name))?;
            out.emit(&report, |v| {
                format!("{}\n", v["message"].as_str().unwrap_or_default())
            })?;
            Ok(code)
        }
        HubCommand::Conflicts {
            bereich,
            resolve,
            take_offered,
            as_,
            data,
        } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            // The same check the web page has made all along, for the same reason, and it
            // was missing here: the command printed every open conflict of every bereich
            // with `offered_body` in it — the whole turned-away note text — to anybody who
            // could open the file. Two doors, one lock.
            let who = store
                .principal_for(as_.as_deref(), hub::access::Role::Editor)
                .map_err(|d| Error::Config(d.to_string()))?;
            if let Some(id) = resolve {
                // Against this person's bereiche, not against the id alone. Otherwise a
                // guessed id settles a conflict in a department they have nothing to do
                // with, which the web route says in the same words.
                if store.conflict_for_principal(&who.id, id)?.is_none() {
                    return Err(Error::Config(format!(
                        "{id}: no open conflict of yours has that id"
                    )));
                }
                let stamp = now();
                let done = store.resolve_conflict(id, *take_offered, &stamp)?;
                if done {
                    let _ = store.record(
                        &who.id,
                        "conflict.resolved",
                        serde_json::json!({
                            "id": id,
                            "by": who.name,
                            "took": if *take_offered { "offered" } else { "held" },
                        }),
                        &stamp,
                    );
                }
                out.emit(
                    &serde_json::json!({
                        "id": id, "resolved": done,
                        "took": if *take_offered { "offered" } else { "held" }
                    }),
                    |v| {
                        if v["resolved"].as_bool().unwrap_or(false) {
                            format!(
                                "{} settled: the {} version stands.\n",
                                v["id"].as_str().unwrap_or_default(),
                                v["took"].as_str().unwrap_or_default()
                            )
                        } else {
                            format!(
                                "{}: no open conflict with that id.\n",
                                v["id"].as_str().unwrap_or_default()
                            )
                        }
                    },
                )?;
                return Ok(0);
            }
            // Always through the principal: `open_conflicts(bereich)` answers for a
            // bereich, not for a person, and taking the bereich from an argument would let
            // an editor name somebody else's.
            let mine = store.conflicts_for_principal(&who.id)?;
            let list: Vec<_> = mine
                .into_iter()
                .map(|(c, _held)| c)
                .filter(|c| bereich.as_deref().is_none_or(|b| c.bereich == *b))
                .collect();
            out.emit(&serde_json::json!(list), |v| {
                let rows = v.as_array().cloned().unwrap_or_default();
                if rows.is_empty() {
                    return "No open conflicts.\n".to_string();
                }
                let mut s = format!(
                    "{} note(s) two machines changed without seeing each other.\n\
                     Nothing was overwritten and nothing was dropped.\n\n",
                    rows.len()
                );
                for c in rows {
                    s.push_str(&format!(
                        "  {} in {}\n    held:    {} from {}\n    offered: {} from {}\n    \
                         {}\n    settle: cyberbrain hub conflicts --resolve {} \
                         [--take-offered]\n\n",
                        c["name"].as_str().unwrap_or_default(),
                        c["bereich"].as_str().unwrap_or_default(),
                        c["held_updated"].as_str().unwrap_or_default(),
                        c["held_from_device"].as_str().unwrap_or_default(),
                        c["offered_updated"].as_str().unwrap_or_default(),
                        c["offered_from_device"].as_str().unwrap_or_default(),
                        match c["based_on"].as_str() {
                            Some(b) => format!("the sender started from {b}"),
                            None => "the sender did not say what it started from".to_string(),
                        },
                        c["id"].as_str().unwrap_or_default(),
                    ));
                }
                s
            })?;
            Ok(0)
        }
        HubCommand::Grant { command } => {
            use cli::GrantCommand;
            match command {
                GrantCommand::Add {
                    device,
                    bereich,
                    direction,
                    reason,
                    data,
                } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let dir = hub::sync_access::Direction::parse(direction)?;
                    cyberbrain_core::frontmatter::validate_bereich(bereich)
                        .map_err(|r| Error::Config(format!("bereich `{bereich}`: {r}")))?;
                    if reason.trim().is_empty() {
                        return Err(Error::Config(
                            "a grant needs a reason: it is what an auditor reads later".into(),
                        ));
                    }
                    let id = format!("bg_{}", cyberbrain_core::NoteId::generate());
                    let stamp = now();
                    store.grant_bereich(&id, device, bereich, dir, reason, "cli", &stamp)?;
                    let _ = store.record(
                        "cli",
                        "grant.added",
                        serde_json::json!({
                            "id": id, "device": device, "bereich": bereich,
                            "direction": dir.as_str(), "reason": reason,
                        }),
                        &stamp,
                    );
                    out.emit(
                        &serde_json::json!({
                            "id": id, "device": device, "bereich": bereich,
                            "direction": dir.as_str(), "reason": reason
                        }),
                        |v| {
                            format!(
                                concat!(
                                    "grant {3} written: device {0} may {1} bereich {2}\n",
                                    "  reason: {4}\n\n",
                                    "It does nothing yet. A bereich takes two people, so ",
                                    "somebody holding a countersigner credential has to ",
                                    "run:\n  cyberbrain hub grant approve {3} --as ",
                                    "<credential>\n\n",
                                    "Rings 0 and 1 stay on the machine regardless.\n"
                                ),
                                v["device"].as_str().unwrap_or_default(),
                                v["direction"].as_str().unwrap_or_default(),
                                v["bereich"].as_str().unwrap_or_default(),
                                v["id"].as_str().unwrap_or_default(),
                                v["reason"].as_str().unwrap_or_default(),
                            )
                        },
                    )?;
                    Ok(0)
                }
                GrantCommand::Approve { id, as_, data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let who = store
                        .principal_for(as_.as_deref(), hub::access::Role::Countersigner)
                        .map_err(|d| Error::Config(d.to_string()))?;
                    use hub::store::CountersignOutcome as O;
                    let outcome = store.countersign_grant(id, &who, &now())?;
                    let (state, line) = match &outcome {
                        O::Signed => (
                            "signed",
                            format!("{id} takes effect now, countersigned by {}.", who.name),
                        ),
                        O::Unknown => ("unknown", format!("{id}: no grant with that id.")),
                        O::Withdrawn => (
                            "withdrawn",
                            format!(
                                "{id} was withdrawn. Reviving it is a new decision: write a \
                                 new grant, with its reason."
                            ),
                        ),
                        O::AlreadySigned { by } => (
                            "already-signed",
                            format!("{id} was already countersigned by {by}."),
                        ),
                        O::SamePerson => (
                            "same-person",
                            format!(
                                "{id} was written by you. Two signatures from one hand are \
                                 one signature; somebody else has to countersign it."
                            ),
                        ),
                    };
                    out.emit(
                        &serde_json::json!({ "id": id, "state": state, "message": line }),
                        |v| format!("{}\n", v["message"].as_str().unwrap_or_default()),
                    )?;
                    Ok(if matches!(outcome, O::Signed) { 0 } else { 1 })
                }
                GrantCommand::List { device, data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let devices = match device {
                        Some(d) => vec![d.clone()],
                        None => store.devices()?.into_iter().map(|d| d.id).collect(),
                    };
                    let mut all = Vec::new();
                    for d in devices {
                        all.extend(store.grants_for_device(&d)?);
                    }
                    out.emit(&serde_json::json!(all), |v| {
                        let rows = v.as_array().cloned().unwrap_or_default();
                        if rows.is_empty() {
                            return "No grants. Without one a device delivers audit rows and \
                                    nothing else.\n"
                                .to_string();
                        }
                        let mut s = format!("{} grant(s)\n\n", rows.len());
                        for g in rows {
                            let live = g["revoked_at"].is_null();
                            s.push_str(&format!(
                                "  {:9} {:14} {:7} {}\n      {}\n",
                                g["device"].as_str().unwrap_or_default(),
                                g["bereich"].as_str().unwrap_or_default(),
                                g["direction"].as_str().unwrap_or_default(),
                                if live { "" } else { "(withdrawn)" },
                                g["reason"].as_str().unwrap_or_default(),
                            ));
                        }
                        s
                    })?;
                    Ok(0)
                }
                GrantCommand::Revoke { id, data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let stamp = now();
                    let gone = store.revoke_grant(id, &stamp)?;
                    if gone {
                        let _ = store.record(
                            "cli",
                            "grant.revoked",
                            serde_json::json!({ "id": id }),
                            &stamp,
                        );
                    }
                    out.emit(&serde_json::json!({ "id": id, "revoked": gone }), |v| {
                        if v["revoked"].as_bool().unwrap_or(false) {
                            format!(
                                "{} withdrawn. What was delivered stays; what stops is \
                                 delivery from now on.\n",
                                v["id"].as_str().unwrap_or_default()
                            )
                        } else {
                            format!(
                                "{}: no such grant, or it was already withdrawn.\n",
                                v["id"].as_str().unwrap_or_default()
                            )
                        }
                    })?;
                    Ok(0)
                }
            }
        }
        HubCommand::Principal { command } => {
            use cli::PrincipalCommand;
            match command {
                PrincipalCommand::Assign {
                    principal,
                    bereich,
                    data,
                } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    cyberbrain_core::frontmatter::validate_bereich(bereich)
                        .map_err(|r| Error::Config(format!("bereich `{bereich}`: {r}")))?;
                    let who = store.principals()?.into_iter().find(|p| &p.id == principal);
                    match who {
                        None => return Err(Error::Config(format!("no principal {principal}"))),
                        Some(p) if p.role != hub::access::Role::Editor => {
                            return Err(Error::Config(format!(
                                "{} is {}, not an editor. Only an editor is given bereiche, \
                                 because reading note text is not part of the other roles.",
                                p.name,
                                p.role.as_str()
                            )));
                        }
                        Some(_) => {}
                    }
                    let stamp = now();
                    store.assign_bereich(principal, bereich, &stamp)?;
                    let _ = store.record(
                        "cli",
                        "principal.assigned",
                        serde_json::json!({ "principal": principal, "bereich": bereich }),
                        &stamp,
                    );
                    out.emit(
                        &serde_json::json!({ "principal": principal, "bereich": bereich }),
                        |v| {
                            format!(
                                "{} now sees conflicts in {}\n",
                                v["principal"].as_str().unwrap_or_default(),
                                v["bereich"].as_str().unwrap_or_default()
                            )
                        },
                    )?;
                    Ok(0)
                }
                PrincipalCommand::Add { name, role, data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let role = hub::access::Role::parse(role)?;
                    let (who, token) = store.add_principal(name, role, &now())?;
                    out.emit(
                        &serde_json::json!({ "principal": who, "token": token }),
                        |v| {
                            format!(
                                "{} registered as {} ({})\ncredential: {}\n\n\
                                 Shown once; the record keeps a hash. Granting a role is \
                                 itself an entry in the hub's log.\n",
                                v["principal"]["name"].as_str().unwrap_or_default(),
                                v["principal"]["role"].as_str().unwrap_or_default(),
                                v["principal"]["id"].as_str().unwrap_or_default(),
                                v["token"].as_str().unwrap_or_default()
                            )
                        },
                    )?;
                    Ok(0)
                }
                PrincipalCommand::List { data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let people = store.principals()?;
                    out.emit(&serde_json::json!({ "principals": people }), |v| {
                        let list = v["principals"].as_array().cloned().unwrap_or_default();
                        if list.is_empty() {
                            return "nobody registered yet\n".to_string();
                        }
                        let mut s = String::new();
                        for p in list {
                            s.push_str(&format!(
                                "{:<16} {:<24} {}\n",
                                p["role"].as_str().unwrap_or_default(),
                                p["name"].as_str().unwrap_or_default(),
                                if p["revoked_at"].is_string() {
                                    "revoked"
                                } else {
                                    p["id"].as_str().unwrap_or_default()
                                }
                            ));
                        }
                        s
                    })?;
                    Ok(0)
                }
                PrincipalCommand::Revoke { id, data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let done = store.revoke_principal(id, &now())?;
                    out.emit(
                        &serde_json::json!({ "revoked": done, "principal": id }),
                        |v| {
                            if v["revoked"].as_bool().unwrap_or(false) {
                                format!("{id} may no longer act\n")
                            } else {
                                format!("{id} is unknown or was already revoked\n")
                            }
                        },
                    )?;
                    Ok(0)
                }
            }
        }

        HubCommand::Request {
            reason,
            device,
            from,
            to,
            as_,
            data,
        } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let who = store
                .principal_for(as_.as_deref(), hub::access::Role::Auditor)
                .map_err(|d| Error::Config(d.to_string()))?;
            let req = store.create_request(
                &who,
                device.as_deref(),
                from.as_deref(),
                to.as_deref(),
                reason,
                &now(),
            )?;
            let id = req.id.clone();
            out.emit(&req, move |r| {
                format!(
                    "request {} recorded\n\nIt gives access to nothing until somebody else \
                     countersigns it:\n  cyberbrain hub approve {} --as <countersigner>\n",
                    r.id, id
                )
            })?;
            Ok(0)
        }

        HubCommand::Approve {
            request,
            hours,
            as_,
            data,
        } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let who = store
                .principal_for(as_.as_deref(), hub::access::Role::Countersigner)
                .map_err(|d| Error::Config(d.to_string()))?;
            let expires = (jiff::Timestamp::now()
                + std::time::Duration::from_secs((*hours).max(1) as u64 * 3600))
            .to_string();
            let req = store
                .approve_request(request, &who, &expires, &now())
                .map_err(|d| Error::Config(d.to_string()))?;
            let name = who.name.clone();
            out.emit(&req, move |r| {
                format!(
                    "request {} countersigned by {}\nopen until {}\n",
                    r.id,
                    name,
                    r.expires_at.as_deref().unwrap_or("unknown")
                )
            })?;
            Ok(0)
        }

        HubCommand::Requests { data } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let reqs = store.requests()?;
            let now_ts = jiff::Timestamp::now();
            let text: String = reqs.iter().map(|r| r.line(now_ts)).collect();
            out.emit(&serde_json::json!({ "requests": reqs }), move |_| {
                if text.is_empty() {
                    "no requests have been made\n".to_string()
                } else {
                    text.clone()
                }
            })?;
            Ok(0)
        }

        HubCommand::Disclose {
            request,
            out_dir,
            as_,
            data,
        } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let tool = concat!("cyberbrain hub ", env!("CARGO_PKG_VERSION"));
            let result = hub::report::disclose(
                &store,
                as_.as_deref(),
                request,
                out_dir,
                jiff::Timestamp::now(),
                tool,
            )
            .map_err(|d| Error::Config(d.to_string()))?;
            out.emit(&result, |v| {
                format!(
                    "{} row(s) from {} device(s) written to {}\n\n\
                     This disclosure is in the hub's log: request {}, read by {}, approved \
                     by {}.\n",
                    v["rows"].as_i64().unwrap_or_default(),
                    v["devices"].as_i64().unwrap_or_default(),
                    v["directory"].as_str().unwrap_or_default(),
                    v["request"].as_str().unwrap_or_default(),
                    v["auditor"].as_str().unwrap_or_default(),
                    v["approved_by"].as_str().unwrap_or("nobody")
                )
            })?;
            Ok(0)
        }

        HubCommand::AccessLog { limit, data } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let events = store.hub_events(*limit)?;
            // Names in the text, ids in the JSON: a person reads this, a script matches on it.
            let names = store.principal_names()?;
            let chain = store.verify_hub_chain().map_err(|e| e.to_string());
            out.emit(
                &serde_json::json!({
                    "events": events,
                    "chain": match &chain {
                        Ok(n) => serde_json::json!({ "rows": n }),
                        Err(e) => serde_json::json!({ "broken": e }),
                    },
                }),
                |v| {
                    let mut s = String::new();
                    for e in v["events"].as_array().cloned().unwrap_or_default() {
                        s.push_str(&format!(
                            "{}  {:<18} {}  {}\n",
                            e["ts"].as_str().unwrap_or_default(),
                            e["action"].as_str().unwrap_or_default(),
                            names.of(e["actor"].as_str().unwrap_or_default()),
                            e["detail"]
                        ));
                    }
                    match v["chain"]["rows"].as_i64() {
                        Some(n) => s.push_str(&format!("\nchain holds over {n} entr(ies)\n")),
                        None => s.push_str(&format!(
                            "\nCHAIN BROKEN: {}\n",
                            v["chain"]["broken"].as_str().unwrap_or_default()
                        )),
                    }
                    s
                },
            )?;
            Ok(if chain.is_ok() { 0 } else { 1 })
        }

        HubCommand::Verify { data } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let report = hub::report::verify(&store)?;
            let ok = report.ok;
            // Rendered from the JSON shape rather than the struct so the text and `--json`
            // cannot describe two different things.
            let as_json = serde_json::to_value(&report)
                .map_err(|e| Error::Index(format!("verify report does not serialise: {e}")))?;
            out.emit(&as_json, |v| {
                let mut s = String::new();
                for d in v["devices"].as_array().cloned().unwrap_or_default() {
                    let verdict = match d["chain"].get("Ok") {
                        Some(n) => match d["floor_seq"].as_i64() {
                            Some(f) => format!(
                                "chain holds over {n} row(s), from row {} (rows before it were purged)",
                                f + 1
                            ),
                            None => format!("chain holds over {} row(s)", n),
                        },
                        None => format!(
                            "BROKEN: {}",
                            d["chain"]["Err"].as_str().unwrap_or("unknown")
                        ),
                    };
                    s.push_str(&format!(
                        "{:<24} {}\n",
                        d["name"].as_str().unwrap_or_default(),
                        verdict
                    ));
                }
                s.push_str(&format!(
                    "\n{} row(s) checked; {}\n",
                    v["rows"].as_i64().unwrap_or_default(),
                    if v["ok"].as_bool().unwrap_or(false) {
                        "everything the hub holds is as it arrived"
                    } else {
                        "AT LEAST ONE CHAIN DOES NOT HOLD"
                    }
                ));
                s
            })?;
            Ok(if ok { 0 } else { 1 })
        }

        HubCommand::Backup { to, data } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let report = hub::report::backup(&store, to, &now())?;
            let ok = report.ok;
            let as_json = serde_json::to_value(&report)
                .map_err(|e| Error::Index(format!("backup report does not serialise: {e}")))?;
            out.emit(&as_json, |v| {
                let hub_log = match v["hub_chain"].get("Ok") {
                    Some(n) => format!("the hub's own log holds over {n} row(s)"),
                    None => format!(
                        "the hub's own log is BROKEN: {}",
                        v["hub_chain"]["Err"].as_str().unwrap_or("unknown")
                    ),
                };
                format!(
                    "written to {} ({} bytes)\n{} activity row(s) re-checked in the copy; {}\n{}\n",
                    v["path"].as_str().unwrap_or_default(),
                    v["bytes"],
                    v["verify"]["rows"],
                    hub_log,
                    if v["ok"].as_bool().unwrap_or(false) {
                        "the copy verifies on its own; to restore, stop the hub and put it in place of hub.db"
                    } else {
                        "THE COPY DOES NOT VERIFY: do not rely on it"
                    }
                )
            })?;
            Ok(if ok { 0 } else { 1 })
        }

        HubCommand::Retention { command } => {
            use cli::RetentionCommand;
            match command {
                RetentionCommand::Set { period, data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    store.set_retention(period, "cli", &now())?;
                    out.emit(&serde_json::json!({ "retention": period }), |v| {
                        format!(
                            "activity rows are kept for {}\n\nNothing was removed. A purge is its own \
                             step: `cyberbrain hub retention propose --reason <why>`, and then a \
                             countersigner.\n",
                            v["retention"].as_str().unwrap_or_default()
                        )
                    })?;
                    Ok(0)
                }
                RetentionCommand::Show { data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let stamp = now();
                    let period = store.retention()?;
                    let (cutoff, would) = match &period {
                        Some(p) => {
                            let c = hub::store::cutoff_for(p, &stamp)?;
                            let n: i64 = store.purge_plan(&c)?.iter().map(|(_, n, _)| n).sum();
                            (Some(c), n)
                        }
                        None => (None, 0),
                    };
                    let pending: Vec<_> = store
                        .purges()?
                        .into_iter()
                        .filter(|p| p.is_pending())
                        .collect();
                    out.emit(
                        &serde_json::json!({
                            "retention": period, "cutoff": cutoff,
                            "would_remove": would, "pending": pending,
                        }),
                        |v| match v["retention"].as_str() {
                            None => "No retention period is set. The hub keeps every activity row \
                                     until one is, and no purge can be proposed.\n"
                                .to_string(),
                            Some(p) => format!(
                                "activity rows are kept for {p}\n\
                                 a purge today would remove {} row(s) older than {}\n\
                                 {} purge(s) waiting for a countersignature\n",
                                v["would_remove"],
                                v["cutoff"].as_str().unwrap_or_default(),
                                v["pending"].as_array().map(|a| a.len()).unwrap_or(0)
                            ),
                        },
                    )?;
                    Ok(0)
                }
                RetentionCommand::Propose { reason, data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let (p, would) = store.propose_purge(reason, "cli", &now())?;
                    out.emit(
                        &serde_json::json!({
                            "id": p.id, "cutoff": p.cutoff, "retention": p.retention,
                            "reason": p.reason, "would_remove": would,
                        }),
                        |v| {
                            let id = v["id"].as_str().unwrap_or_default();
                            format!(
                                "purge {id} written: rows older than {} ({}), {} row(s) today\n\
                                 \x20 reason: {}\n\n\
                                 Nothing is removed yet. Somebody holding a countersigner \
                                 credential has to sign it:\n\
                                 \x20 cyberbrain hub retention approve {id} --as <credential>\n\
                                 or on the hub's page, under /requests.\n",
                                v["cutoff"].as_str().unwrap_or_default(),
                                v["retention"].as_str().unwrap_or_default(),
                                v["would_remove"],
                                v["reason"].as_str().unwrap_or_default(),
                            )
                        },
                    )?;
                    Ok(0)
                }
                RetentionCommand::Approve { id, as_, data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let who = store
                        .principal_for(as_.as_deref(), hub::access::Role::Countersigner)
                        .map_err(|d| Error::Config(d.to_string()))?;
                    use hub::store::PurgeOutcome as O;
                    let outcome = store.countersign_purge(id, &who, &now())?;
                    let (state, line) = match &outcome {
                        O::CarriedOut { rows, devices } => (
                            "carried-out",
                            format!(
                                "{id} carried out, countersigned by {}: {rows} row(s) removed from \
                                 {} device(s). Each remaining chain is checked from where the \
                                 purge stopped.",
                                who.name,
                                devices.len()
                            ),
                        ),
                        O::Unknown => ("unknown", format!("{id}: no purge with that id.")),
                        O::AlreadyDone { by } => (
                            "already-done",
                            format!("{id} was already carried out, countersigned by {by}."),
                        ),
                        O::SamePerson => (
                            "same-person",
                            format!(
                                "{id} was proposed by you. Two signatures from one hand are one \
                                 signature; somebody else has to countersign it."
                            ),
                        ),
                    };
                    out.emit(
                        &serde_json::json!({ "id": id, "state": state, "message": line, "outcome": outcome }),
                        |v| format!("{}\n", v["message"].as_str().unwrap_or_default()),
                    )?;
                    Ok(if matches!(outcome, O::CarriedOut { .. }) {
                        0
                    } else {
                        1
                    })
                }
                RetentionCommand::List { data } => {
                    let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
                    let all = store.purges()?;
                    let names = store.principal_names()?;
                    out.emit(&serde_json::json!(all), |v| {
                        let rows = v.as_array().cloned().unwrap_or_default();
                        if rows.is_empty() {
                            return "No purges. Every activity row the hub received is still \
                                    there.\n"
                                .to_string();
                        }
                        let mut s = format!("{} purge(s)\n\n", rows.len());
                        for p in rows {
                            let state = match p["approved_by"].as_str() {
                                Some(by) => format!(
                                    "carried out {} by {}, {} row(s) removed",
                                    p["approved_at"].as_str().unwrap_or_default(),
                                    names.of(by),
                                    p["rows_removed"]
                                ),
                                None => "waiting for a countersignature".to_string(),
                            };
                            s.push_str(&format!(
                                "  {}  rows before {} ({})\n      reason: {}\n      {state}\n",
                                p["id"].as_str().unwrap_or_default(),
                                p["cutoff"].as_str().unwrap_or_default(),
                                p["retention"].as_str().unwrap_or_default(),
                                p["reason"].as_str().unwrap_or_default(),
                            ));
                        }
                        s
                    })?;
                    Ok(0)
                }
            }
        }

        HubCommand::Report {
            out_dir,
            from,
            to,
            data,
        } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let tool = concat!("cyberbrain hub ", env!("CARGO_PKG_VERSION"));
            let report =
                hub::report::write_report(&store, out_dir, from.as_deref(), to.as_deref(), tool)?;
            out.emit(&report, |v| {
                format!(
                    "{}\nwritten to {}/summary.txt\n",
                    v["summary"].as_str().unwrap_or_default(),
                    v["directory"].as_str().unwrap_or_default()
                )
            })?;
            Ok(0)
        }

        HubCommand::Revoke { id, data } => {
            let store = hub::HubStore::open(&hub::data_path(data.clone()))?;
            let done = store.revoke(id, &now())?;
            out.emit(&serde_json::json!({ "revoked": done, "device": id }), |v| {
                if v["revoked"].as_bool().unwrap_or(false) {
                    format!("{id} may no longer send; its rows are kept\n")
                } else {
                    format!("{id} is unknown or was already revoked\n")
                }
            })?;
            Ok(0)
        }
    }
}

fn run_policy(app: &App, command: PolicyCommand, out: Out) -> Result<i32> {
    match command {
        PolicyCommand::Egress => {
            let r = app.policy_egress();
            out.emit(&r, |e| render::egress(e))?;
        }
        PolicyCommand::Obligations => {
            let r = app.policy_obligations();
            out.emit(&r, render::obligations)?;
        }
        PolicyCommand::Audit {
            limit,
            action,
            subject,
            verify,
            since,
            until,
            export,
        } => {
            let stamp = |s: Option<String>, what: &str| -> Result<Option<jiff::Timestamp>> {
                s.map(|v| {
                    v.parse::<jiff::Timestamp>().map_err(|e| {
                        Error::Config(format!("--{what}: {v:?} is not an RFC 3339 timestamp: {e}"))
                    })
                })
                .transpose()
            };
            let filter = AuditFilter {
                action,
                subject,
                since: stamp(since, "since")?,
                until: stamp(until, "until")?,
                // An export answers "what happened in this period", and a limit silently
                // cutting that short is the one failure an auditor cannot see. The listing
                // keeps its default; the file does not get one unless it was asked for.
                limit: if export.is_some() {
                    limit
                } else {
                    Some(limit.unwrap_or(50))
                },
                ..Default::default()
            };
            if let Some(path) = export {
                let text = app.export_audit_bundle(&filter)?;
                std::fs::write(&path, &text).map_err(|e| Error::Io {
                    path: path.clone(),
                    source: e,
                })?;
                let report = cyberbrain_policy::bundle::verify(&text)?;
                out.emit(&report, |r| {
                    format!(
                        "wrote {} row(s) to {}\nchecked as written: chain holds from anchor {}\n",
                        r.rows,
                        path.display(),
                        &r.anchor[..r.anchor.len().min(12)]
                    )
                })?;
                return Ok(0);
            }
            let format = if out.json {
                cyberbrain_policy::ExportFormat::Json
            } else {
                cyberbrain_policy::ExportFormat::Text
            };
            let r = app.policy_audit(&filter, verify, format)?;
            let code = audit_exit_code(&r);
            out.emit(&r, |v| {
                let mut s = String::new();
                if let Some(ver) = &v.verified {
                    s.push_str(&match ver {
                        Ok(n) => format!("chain verified over {n} rows\n"),
                        Err(e) => format!("CHAIN BROKEN: {e}\n"),
                    });
                }
                s.push_str(&format!(
                    "{} rows shown (ts\tactor\taction\tsubject\tdetail)\n",
                    v.rows
                ));
                s.push_str(&v.rendered);
                s
            })?;
            return Ok(code);
        }
        PolicyCommand::Subject { identifier } => {
            let r = app.policy_subject(&identifier)?;
            out.emit(&r, |r| r.render_markdown())?;
        }
        PolicyCommand::Retention { apply, dry_run } => {
            let r = app.policy_retention(apply, dry_run)?;
            out.emit(&r, render::retention)?;
        }
        PolicyCommand::ModelCard => {
            let r = app.policy_model_card();
            out.emit(&r, |r| render::model_cards(&r.cards, &r.absent))?;
        }
        PolicyCommand::Consent { withdraw } => {
            let r = app.policy_consent(!withdraw)?;
            out.emit(&r, render::consent)?;
        }
    }
    Ok(0)
}

/// The exit code of `policy audit --verify`.
///
/// A broken chain must not exit 0. This is the one command whose whole purpose is to fail
/// when the log was tampered with, and a check that cannot fail a script is decoration:
/// a nightly `cyberbrain policy audit --verify` would have reported success over an edited
/// log. The rows are printed either way, so the evidence is on screen before the process
/// leaves. Reporting commands (`doctor`, plain `audit`) keep exiting 0; findings there are
/// advisory, a broken hash chain is not.
fn audit_exit_code(view: &AuditView) -> i32 {
    match &view.verified {
        Some(Err(_)) => 1,
        // Not asked to verify, or verified and intact.
        _ => 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn env<'a>(vars: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
        move |k| {
            vars.iter()
                .find(|(n, _)| *n == k)
                .map(|(_, v)| v.to_string())
        }
    }

    /// Calibrated against the broken state first: before 2026-09-25 every one of these was
    /// the operator.
    #[test]
    fn an_agent_at_the_cli_is_not_the_operator() {
        let a = agent_from_env(env(&[
            ("CLAUDECODE", "1"),
            ("CLAUDE_CODE_SESSION_ID", "8c734a31-ccbc-489d"),
        ]));
        assert_eq!(
            a.map(|a| a.to_string()),
            Some("agent:claude-code:8c734a31".into())
        );
        let a = agent_from_env(env(&[("CLAUDECODE", "1")]));
        assert_eq!(a.map(|a| a.to_string()), Some("agent:claude-code".into()));
        let a = agent_from_env(env(&[("CYBERBRAIN_AGENT", "codex; rm -rf /")]));
        assert_eq!(a.map(|a| a.to_string()), Some("agent:codexrm-rf".into()));
        assert!(agent_from_env(env(&[])).is_none());
        assert!(agent_from_env(env(&[("CLAUDECODE", " "), ("CYBERBRAIN_AGENT", "")])).is_none());
    }

    fn view(verified: Option<std::result::Result<usize, String>>) -> AuditView {
        AuditView {
            rows: 3,
            verified,
            rendered: String::new(),
        }
    }

    /// Calibrated against the broken state first: this is the case the exit code exists for.
    #[test]
    fn a_broken_chain_exits_non_zero() {
        let broken = view(Some(Err(
            "audit chain broken at row 2: content does not match its hash".into(),
        )));
        assert_eq!(audit_exit_code(&broken), 1);
    }

    #[test]
    fn an_intact_chain_and_an_unverified_listing_both_exit_zero() {
        assert_eq!(audit_exit_code(&view(Some(Ok(3)))), 0);
        assert_eq!(audit_exit_code(&view(None)), 0);
    }
}