cyberbrain 0.6.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
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
//! What the hub keeps: the devices it knows and the rows they sent.
//!
//! Its own SQLite file, not a store. A store is a project's memory; this is a record of what
//! other machines did, and conflating the two would put someone else's audit trail inside a
//! thing that has `forget` as a first-class operation.
//!
//! The same rule as the store's audit log applies here and for the same reason: `BEFORE
//! UPDATE` and `BEFORE DELETE` triggers abort. A hub whose rows can be edited is a hub whose
//! evidence is worth nothing, and "we would notice" is not a control.

use cyberbrain_core::{Error, Result};
use cyberbrain_policy::AuditEvent;
use rusqlite::{Connection, OptionalExtension, params};
use std::path::Path;

/// The chain state of a device that has never sent anything.
pub const GENESIS: &str = "genesis";

#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct Device {
    pub id: String,
    pub name: String,
    pub created_at: String,
    pub revoked_at: Option<String>,
    pub last_seen: Option<String>,
    /// Hash of the last row accepted from this device. The next bundle must anchor here.
    pub anchor: String,
    pub rows: i64,
    /// Version this device last reported. `None` until it has sent one.
    pub version: Option<String>,
    /// Why this device's last delivery was turned away, if one was.
    pub last_refusal: Option<String>,
    pub last_refusal_at: Option<String>,
    /// Where this device's chain starts on the hub after a purge: the hash of the last row
    /// removed, and its seq. `None` until something was purged, and then the chain starts at
    /// the genesis marker as it always did.
    pub floor_hash: Option<String>,
    pub floor_seq: Option<i64>,
    /// The machine this device is on, as its deliveries report it. Seats are counted by this:
    /// every project is its own device, and the licence promises a seat per machine.
    pub machine: Option<String>,
}

impl Device {
    pub fn is_active(&self) -> bool {
        self.revoked_at.is_none()
    }
}

/// What became of an offered note.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
#[serde(tag = "outcome", rename_all = "kebab-case")]
pub enum NoteOutcome {
    /// Taken: either the hub held nothing, or the sender built on what it holds.
    Stored,
    /// The sender re-sent what is already held. Not an error and not a change.
    Unchanged,
    /// Two machines changed it without seeing each other. Both versions are kept and
    /// somebody has to say which one stands.
    Conflict { id: String, held_updated: String },
}

/// What an erasure actually removed. Counted rather than assumed.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize)]
pub struct ErasureCount {
    pub notes: usize,
    pub conflicts: usize,
}

/// Two versions of one note that nobody has reconciled yet.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct NoteConflict {
    pub id: String,
    pub bereich: String,
    pub name: String,
    pub held_updated: String,
    pub held_from_device: String,
    pub offered_updated: String,
    pub offered_from_device: String,
    pub offered_frontmatter: String,
    pub offered_body: String,
    pub based_on: Option<String>,
    pub detected_at: String,
}

/// One note the hub holds for a bereich.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct SyncedNote {
    pub id: String,
    pub bereich: String,
    pub name: String,
    pub ring: u8,
    pub kind: String,
    pub updated: String,
    pub frontmatter: String,
    pub body: String,
    pub from_device: String,
}

pub struct HubStore {
    // Private, except to the tests in this module, which need to simulate the one attack
    // the triggers cannot stop: dropping them and rewriting a row. That is exactly the
    // shape the chain exists to catch, so it has to be reachable to prove it.
    #[cfg(not(test))]
    conn: Connection,
    #[cfg(test)]
    pub(super) conn: Connection,
}

fn ix<T>(r: rusqlite::Result<T>) -> Result<T> {
    r.map_err(|e| Error::Index(format!("hub store: {}", explain(e))))
}

/// SQLite's own words, plus what to do about them where we know.
///
/// "attempt to write a readonly database" is the message a person gets for running `hub add`
/// in an ordinary prompt: the record belongs to the service account, everybody else may read
/// it, and SQLite therefore opened it read-only. The sentence is accurate and tells the
/// reader nothing they can act on, which for a command they typed on purpose is the same as
/// telling them nothing.
pub(super) fn explain(e: rusqlite::Error) -> String {
    let text = e.to_string();
    let readonly = matches!(
        e,
        rusqlite::Error::SqliteFailure(
            rusqlite::ffi::Error {
                code: rusqlite::ErrorCode::ReadOnly,
                ..
            },
            _
        )
    );
    if !readonly {
        return text;
    }
    let hint = if cfg!(windows) {
        concat!(
            "the record belongs to the account the hub service runs as, and this prompt is ",
            "not elevated. Open one with Run as administrator and try again."
        )
    } else {
        concat!(
            "the record belongs to the account the hub runs as. Try again as that user, or ",
            "with sudo."
        )
    };
    format!("{text} — {hint}")
}

/// What came of a countersignature attempt. Each one is a different sentence to the person
/// holding the credential, so they are not collapsed into a bool.
#[derive(Debug, Clone, PartialEq)]
pub enum CountersignOutcome {
    Signed,
    Unknown,
    Withdrawn,
    AlreadySigned {
        by: String,
    },
    /// The person who wrote the grant is the person trying to sign it.
    SamePerson,
}

impl HubStore {
    pub fn open(path: &Path) -> Result<Self> {
        if let Some(parent) = path.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent).map_err(|e| Error::Io {
                path: parent.to_path_buf(),
                source: e,
            })?;
        }
        let conn = ix(Connection::open(path))?;
        let s = Self { conn };
        s.migrate()?;
        Ok(s)
    }

    /// Write a consistent copy of the whole record to `to`, for `hub backup`.
    ///
    /// `VACUUM INTO`, not a file copy. The record runs in WAL mode, so the newest rows may
    /// still live in `hub.db-wal`, and a copy of `hub.db` alone opens, verifies and misses
    /// them; the first version did exactly that. This reads one snapshot through SQLite, so
    /// deliveries keep arriving while it runs, and the copy is a single file with no WAL of
    /// its own to lose. Never over an existing file: replacing last night's backup with a
    /// broken one is how a backup disappears.
    pub fn backup_to(&self, to: &Path) -> Result<()> {
        if to.exists() {
            // A user error, not an I/O failure: the command was asked for something it will
            // not do, and exit 1 says so where exit 2 would read as a crash.
            return Err(Error::Config(format!(
                "{}: a backup is never written over an existing file; pick a new name",
                to.display()
            )));
        }
        if let Some(parent) = to.parent()
            && !parent.as_os_str().is_empty()
        {
            std::fs::create_dir_all(parent).map_err(|e| Error::Io {
                path: parent.to_path_buf(),
                source: e,
            })?;
        }
        let target = to.to_str().ok_or_else(|| {
            Error::Index(format!(
                "{} is not valid UTF-8, which SQLite needs for a file name",
                to.display()
            ))
        })?;
        ix(self.conn.execute("VACUUM INTO ?1", params![target]))?;
        Ok(())
    }

    #[cfg(test)]
    pub fn in_memory() -> Result<Self> {
        let conn = ix(Connection::open_in_memory())?;
        let s = Self { conn };
        s.migrate()?;
        Ok(s)
    }

    fn migrate(&self) -> Result<()> {
        ix(self.conn.execute_batch(
            "PRAGMA journal_mode = WAL;
             PRAGMA foreign_keys = ON;

             CREATE TABLE IF NOT EXISTS devices (
                 id          TEXT PRIMARY KEY,
                 name        TEXT NOT NULL,
                 token_hash  TEXT NOT NULL UNIQUE,
                 created_at  TEXT NOT NULL,
                 revoked_at  TEXT,
                 last_seen   TEXT,
                 anchor      TEXT NOT NULL,
                 rows        INTEGER NOT NULL DEFAULT 0,
                 version     TEXT,
                 -- The last delivery this device made that was turned away, and why.
                 -- Without it a gap is invisible: a delivery that does not continue the
                 -- chain is refused, so it leaves no rows — and the fleet view would show a
                 -- device that simply went quiet, which is a different problem with a
                 -- different fix.
                 last_refusal    TEXT,
                 last_refusal_at TEXT
             );

             CREATE TABLE IF NOT EXISTS entries (
                 device      TEXT NOT NULL REFERENCES devices(id),
                 seq         INTEGER NOT NULL,
                 ts          TEXT NOT NULL,
                 actor       TEXT NOT NULL,
                 action      TEXT NOT NULL,
                 subject     TEXT NOT NULL,
                 detail      TEXT NOT NULL,
                 hash        TEXT NOT NULL,
                 received_at TEXT NOT NULL,
                 PRIMARY KEY (device, seq)
             );

             -- Append-only, enforced by the database rather than by everyone remembering.
             CREATE TRIGGER IF NOT EXISTS entries_no_update
                 BEFORE UPDATE ON entries
                 BEGIN SELECT raise(ABORT, 'the hub record is append-only'); END;
             -- A fleet invitation: one code that enrols up to `max_uses` projects until
             -- `expires_at`. Only its hash is kept, like a device token, so a copy of the
             -- record is not a working invitation.
             CREATE TABLE IF NOT EXISTS enrolment_codes (
                 id         TEXT PRIMARY KEY,
                 code_hash  TEXT NOT NULL UNIQUE,
                 label      TEXT NOT NULL,
                 max_uses   INTEGER NOT NULL,
                 uses       INTEGER NOT NULL DEFAULT 0,
                 expires_at TEXT NOT NULL,
                 created_by TEXT NOT NULL,
                 created_at TEXT NOT NULL,
                 revoked_at TEXT
             );

             -- A purge of old activity rows under the hub's retention period: written down by
             -- one person, carried out when a second one signs (`countersign_purge`).
             CREATE TABLE IF NOT EXISTS purges (
                 id           TEXT PRIMARY KEY,
                 cutoff       TEXT NOT NULL,
                 retention    TEXT NOT NULL,
                 reason       TEXT NOT NULL,
                 proposed_by  TEXT NOT NULL,
                 created_at   TEXT NOT NULL,
                 approved_by  TEXT,
                 approved_at  TEXT,
                 rows_removed INTEGER
             );

             -- Holds a row only inside the transaction that carries out a purge. The delete
             -- trigger on `entries` (see `upgrade_delete_trigger`) lets a row go only while its
             -- device has a window here and the row lies below it.
             CREATE TABLE IF NOT EXISTS purge_window (
                 device    TEXT PRIMARY KEY,
                 below_seq INTEGER NOT NULL
             );

             CREATE INDEX IF NOT EXISTS entries_by_ts ON entries(ts);

             -- One row, holding the licence text. In the record rather than a file beside
             -- it so that moving the hub moves its licence with it.
             CREATE TABLE IF NOT EXISTS settings (
                 key   TEXT PRIMARY KEY,
                 value TEXT NOT NULL
             );

             -- People, as opposed to machines. Same token discipline as devices.
             CREATE TABLE IF NOT EXISTS principals (
                 id         TEXT PRIMARY KEY,
                 name       TEXT NOT NULL,
                 role       TEXT NOT NULL,
                 token_hash TEXT NOT NULL UNIQUE,
                 created_at TEXT NOT NULL,
                 revoked_at TEXT
             );

             -- Requests to read activity, and what became of them.
             CREATE TABLE IF NOT EXISTS access_requests (
                 id           TEXT PRIMARY KEY,
                 requester    TEXT NOT NULL REFERENCES principals(id),
                 device       TEXT,
                 from_ts      TEXT,
                 to_ts        TEXT,
                 reason       TEXT NOT NULL,
                 created_at   TEXT NOT NULL,
                 approved_by  TEXT REFERENCES principals(id),
                 approved_at  TEXT,
                 expires_at   TEXT,
                 disclosures  INTEGER NOT NULL DEFAULT 0
             );

             -- The hub own events: roles granted, requests made, approvals, disclosures.
             -- Its own chain, because these are the hub actions rather than any device
             -- rows, and asking who looked -- and whether anyone removed that afterwards --
             -- needs the same answer as every other row here.
             CREATE TABLE IF NOT EXISTS hub_audit (
                 seq    INTEGER PRIMARY KEY AUTOINCREMENT,
                 ts     TEXT NOT NULL,
                 actor  TEXT NOT NULL,
                 action TEXT NOT NULL,
                 detail TEXT NOT NULL,
                 prev   TEXT NOT NULL,
                 hash   TEXT NOT NULL
             );
             CREATE TRIGGER IF NOT EXISTS hub_audit_no_update
                 BEFORE UPDATE ON hub_audit
                 BEGIN SELECT raise(ABORT, 'the hub audit is append-only'); END;
             CREATE TRIGGER IF NOT EXISTS hub_audit_no_delete
                 BEFORE DELETE ON hub_audit
                 BEGIN SELECT raise(ABORT, 'the hub audit is append-only'); END;

             -- Which bereich a device may send or receive, and why. The reason is not
             -- decoration: a department boundary is a purpose limitation, and a purpose
             -- nobody wrote down cannot be shown to anybody later.
             CREATE TABLE IF NOT EXISTS bereich_grants (
                 id         TEXT PRIMARY KEY,
                 device     TEXT NOT NULL REFERENCES devices(id),
                 bereich    TEXT NOT NULL,
                 direction  TEXT NOT NULL CHECK (direction IN ('send','receive','both')),
                 reason     TEXT NOT NULL,
                 granted_by TEXT NOT NULL,
                 created_at TEXT NOT NULL,
                 -- Both NULL until a second person signs. A grant in that state is written
                 -- down and moves nothing; see `sync_access::BereichGrant::is_effective`.
                 approved_by TEXT,
                 approved_at TEXT,
                 revoked_at TEXT
             );
             CREATE INDEX IF NOT EXISTS bereich_grants_device
                 ON bereich_grants(device, bereich);

             -- Notes the hub holds on behalf of a bereich. The hub is a relay, not the
             -- authority: `name` is unique per bereich, and the newest `updated` wins, so a
             -- hub that loses this table costs a re-push and not a decision.
             CREATE TABLE IF NOT EXISTS synced_notes (
                 id          TEXT NOT NULL,
                 bereich     TEXT NOT NULL,
                 name        TEXT NOT NULL,
                 ring        INTEGER NOT NULL CHECK (ring BETWEEN 2 AND 4),
                 kind        TEXT NOT NULL,
                 updated     TEXT NOT NULL,
                 body        TEXT NOT NULL,
                 frontmatter TEXT NOT NULL,
                 from_device TEXT NOT NULL REFERENCES devices(id),
                 received_at TEXT NOT NULL,
                 PRIMARY KEY (bereich, name)
             );
             CREATE INDEX IF NOT EXISTS synced_notes_bereich ON synced_notes(bereich);

             -- Two machines changed the same note without seeing each other's change. The
             -- offered version is kept beside the held one rather than dropped: last-write-
             -- wins is not a resolution, it is a loss that nobody was told about.
             CREATE TABLE IF NOT EXISTS note_conflicts (
                 id                  TEXT PRIMARY KEY,
                 bereich             TEXT NOT NULL,
                 name                TEXT NOT NULL,
                 held_updated        TEXT NOT NULL,
                 held_from_device    TEXT NOT NULL,
                 offered_updated     TEXT NOT NULL,
                 offered_from_device TEXT NOT NULL,
                 offered_frontmatter TEXT NOT NULL,
                 offered_body        TEXT NOT NULL,
                 based_on            TEXT,
                 detected_at         TEXT NOT NULL,
                 resolved_at         TEXT,
                 resolution          TEXT
             );
             -- Which bereiche a person is responsible for. Only `editor` principals have
             -- these: an admin has none and gets none, because seeing note text is not part
             -- of running the machine.
             CREATE TABLE IF NOT EXISTS principal_bereiche (
                 principal  TEXT NOT NULL REFERENCES principals(id),
                 bereich    TEXT NOT NULL,
                 added_at   TEXT NOT NULL,
                 PRIMARY KEY (principal, bereich)
             );

             CREATE INDEX IF NOT EXISTS note_conflicts_open
                 ON note_conflicts(bereich, name) WHERE resolved_at IS NULL;

             -- A note that was erased. Deliberately carries no text: a record that an
             -- erasure happened must not be a copy of what was erased. It exists so a
             -- machine that delivers the note again learns it was withdrawn, rather than
             -- quietly recreating it (GDPR Art. 17).
             CREATE TABLE IF NOT EXISTS erasures (
                 bereich     TEXT NOT NULL,
                 name        TEXT NOT NULL,
                 erased_at   TEXT NOT NULL,
                 by_device   TEXT NOT NULL,
                 PRIMARY KEY (bereich, name)
             );",
        ))?;
        self.add_missing_columns()?;
        self.upgrade_delete_trigger()
    }

    /// The one delete trigger on `entries`, created here rather than in the schema batch.
    ///
    /// It refuses every delete except inside a purge, and there only below the window the
    /// purge opened for that device. A hub created before purges existed has the
    /// unconditional version, and `CREATE TRIGGER IF NOT EXISTS` would leave it that way
    /// forever, so it is replaced once, recognisably: the new one names `purge_window`.
    fn upgrade_delete_trigger(&self) -> Result<()> {
        let sql: Option<String> = ix(self
            .conn
            .query_row(
                "SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = 'entries_no_delete'",
                [],
                |r| r.get(0),
            )
            .optional())?;
        if sql.as_deref().is_some_and(|s| s.contains("purge_window")) {
            return Ok(());
        }
        ix(self.conn.execute_batch(
            "BEGIN IMMEDIATE;
             DROP TRIGGER IF EXISTS entries_no_delete;
             CREATE TRIGGER entries_no_delete
                 BEFORE DELETE ON entries
                 WHEN NOT EXISTS (SELECT 1 FROM purge_window w
                                  WHERE w.device = old.device AND old.seq < w.below_seq)
                 BEGIN SELECT raise(ABORT, 'the hub record is append-only'); END;
             COMMIT;",
        ))
    }

    /// Bring an existing record up to the current shape.
    ///
    /// `CREATE TABLE IF NOT EXISTS` does nothing to a table that already exists, so a hub
    /// upgraded in place would keep the columns it was created with and fail on the first
    /// query that names a new one. This record is meant to hold a decade of evidence;
    /// upgrading the program must not mean starting it over.
    fn add_missing_columns(&self) -> Result<()> {
        // Only ever additive, and only with a NULL default: a migration that rewrites rows
        // in an append-only record is a contradiction.
        //
        // `approved_by`/`approved_at` arriving NULL is the point rather than a side effect.
        // Grants written before a countersignature was required stop moving notes when the
        // hub is upgraded, and the refusal names the one step that revives them. The other
        // reading — treat what is already there as signed — would carry the hole over the
        // upgrade and call it compatibility.
        for (table, column, ddl) in [
            (
                "devices",
                "version",
                "ALTER TABLE devices ADD COLUMN version TEXT",
            ),
            (
                "devices",
                "last_refusal",
                "ALTER TABLE devices ADD COLUMN last_refusal TEXT",
            ),
            (
                "devices",
                "last_refusal_at",
                "ALTER TABLE devices ADD COLUMN last_refusal_at TEXT",
            ),
            (
                "bereich_grants",
                "approved_by",
                "ALTER TABLE bereich_grants ADD COLUMN approved_by TEXT",
            ),
            (
                "bereich_grants",
                "approved_at",
                "ALTER TABLE bereich_grants ADD COLUMN approved_at TEXT",
            ),
            (
                "devices",
                "floor_hash",
                "ALTER TABLE devices ADD COLUMN floor_hash TEXT",
            ),
            (
                "devices",
                "floor_seq",
                "ALTER TABLE devices ADD COLUMN floor_seq INTEGER",
            ),
            (
                "devices",
                "machine",
                "ALTER TABLE devices ADD COLUMN machine TEXT",
            ),
        ] {
            if !self.has_column(table, column)? {
                ix(self.conn.execute(ddl, []))?;
            }
        }
        Ok(())
    }

    fn has_column(&self, table: &str, column: &str) -> Result<bool> {
        let mut stmt = ix(self.conn.prepare(&format!("PRAGMA table_info({table})")))?;
        let names = ix(stmt.query_map([], |r| r.get::<_, String>(1)))?;
        for n in names {
            if ix(n)? == column {
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Register a device. Returns it with the plaintext token, which is the only time that
    /// value exists anywhere: the table keeps a hash, so a stolen database is not a set of
    /// working credentials.
    pub fn add_device(&self, name: &str, now: &str) -> Result<(Device, String)> {
        let id = format!("dev_{}", cyberbrain_core::NoteId::generate());
        let token = format!("cbh_{}", cyberbrain_core::NoteId::generate());
        let device = Device {
            id: id.clone(),
            name: name.to_string(),
            created_at: now.to_string(),
            revoked_at: None,
            last_seen: None,
            anchor: GENESIS.to_string(),
            rows: 0,
            version: None,
            last_refusal: None,
            last_refusal_at: None,
            floor_hash: None,
            floor_seq: None,
            machine: None,
        };
        ix(self.conn.execute(
            "INSERT INTO devices (id, name, token_hash, created_at, anchor)
             VALUES (?, ?, ?, ?, ?)",
            params![id, name, token_hash(&token), now, GENESIS],
        ))?;
        // In the chain, like a role grant, and for the same reason: a new device is a new
        // pair of eyes on whatever it is later granted, and it used to appear out of
        // nothing. Recorded inside the store rather than at the two call sites, so neither
        // the web form nor `hub add` can be the one that forgets.
        self.record(
            "hub",
            "device.registered",
            serde_json::json!({ "device": device.id, "name": name }),
            now,
        )?;
        Ok((device, token))
    }

    pub fn device_by_token(&self, token: &str) -> Result<Option<Device>> {
        let hash = token_hash(token);
        ix(self
            .conn
            .query_row(
                "SELECT id, name, created_at, revoked_at, last_seen, anchor, rows, version,
                        last_refusal, last_refusal_at, floor_hash, floor_seq, machine
                 FROM devices WHERE token_hash = ?",
                params![hash],
                row_to_device,
            )
            .optional())
    }

    pub fn devices(&self) -> Result<Vec<Device>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT id, name, created_at, revoked_at, last_seen, anchor, rows, version,
                    last_refusal, last_refusal_at, floor_hash, floor_seq, machine
             FROM devices ORDER BY created_at, id",
        ))?;
        let rows = ix(stmt.query_map([], row_to_device))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(ix(r)?);
        }
        Ok(out)
    }

    /// Revoking is a state, not a deletion: the rows a device sent stay, and so does the
    /// record of who sent them.
    pub fn revoke(&self, id: &str, now: &str) -> Result<bool> {
        let n = ix(self.conn.execute(
            "UPDATE devices SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL",
            params![now, id],
        ))?;
        // Only when something changed: revoking twice is not two events, and a log that
        // says otherwise is a log somebody has to explain.
        if n > 0 {
            self.record(
                "hub",
                "device.revoked",
                serde_json::json!({ "device": id }),
                now,
            )?;
        }
        Ok(n > 0)
    }

    /// Append verified rows for a device and move its anchor on.
    ///
    /// The caller has already checked the bundle and that its anchor matches this device's.
    /// One transaction: a half-accepted bundle would leave an anchor nobody can continue
    /// from, and the next delivery would look like tampering.
    pub fn append(
        &mut self,
        device: &Device,
        rows: &[AuditEvent],
        new_anchor: &str,
        version: Option<&str>,
        now: &str,
    ) -> Result<i64> {
        let tx = ix(self.conn.transaction())?;
        let mut seq = device.rows;
        for e in rows {
            seq += 1;
            let hash = e.chain_hash().unwrap_or_default();
            ix(tx.execute(
                "INSERT INTO entries (device, seq, ts, actor, action, subject, detail, hash, received_at)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
                params![
                    device.id,
                    seq,
                    e.ts.to_string(),
                    e.actor,
                    e.action,
                    e.subject,
                    e.detail.to_string(),
                    hash,
                    now
                ],
            ))?;
        }
        ix(tx.execute(
            // A successful delivery clears the refusal: the device is not in that state any
            // more, and a stale complaint in the fleet view is worse than none.
            "UPDATE devices SET anchor = ?, rows = ?, last_seen = ?,
                 version = coalesce(?, version),
                 last_refusal = NULL, last_refusal_at = NULL
             WHERE id = ?",
            params![new_anchor, seq, now, version, device.id],
        ))?;
        ix(tx.commit())?;
        Ok(seq)
    }

    /// Record that a delivery was turned away. Also counts as contact: the device did
    /// reach us, it just could not be taken.
    pub fn note_refusal(&self, device: &str, reason: &str, now: &str) -> Result<()> {
        ix(self.conn.execute(
            "UPDATE devices SET last_refusal = ?, last_refusal_at = ?, last_seen = ?
             WHERE id = ?",
            params![reason, now, now, device],
        ))
        .map(|_| ())
    }

    /// Rows of one device, oldest first: sequence, timestamp and action, never the detail.
    ///
    /// Deliberately narrow. The hub holds other people's audit trails, and a convenience
    /// method that hands out whole rows is how the "collects but does not read" rule would
    /// quietly stop being true. The report in a later slice builds on this shape.
    #[allow(dead_code)] // the fleet report is the next slice; the shape is fixed here.
    pub fn entries(&self, device: &str, limit: usize) -> Result<Vec<(i64, String, String)>> {
        let mut stmt = ix(self
            .conn
            .prepare("SELECT seq, ts, action FROM entries WHERE device = ? ORDER BY seq LIMIT ?"))?;
        let rows = ix(stmt.query_map(params![device, limit as i64], |r| {
            Ok((r.get(0)?, r.get(1)?, r.get(2)?))
        }))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(ix(r)?);
        }
        Ok(out)
    }

    /// One row of the settings table, for the things that are not the licence.
    pub fn setting(&self, key: &str) -> Result<Option<String>> {
        ix(self
            .conn
            .query_row(
                "SELECT value FROM settings WHERE key = ?",
                params![key],
                |r| r.get(0),
            )
            .optional())
    }

    pub fn set_setting(&self, key: &str, value: &str) -> Result<()> {
        ix(self.conn.execute(
            "INSERT INTO settings (key, value) VALUES (?, ?)
             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
            params![key, value],
        ))
        .map(|_| ())
    }

    pub fn clear_setting(&self, key: &str) -> Result<()> {
        ix(self
            .conn
            .execute("DELETE FROM settings WHERE key = ?", params![key]))
        .map(|_| ())
    }

    /// The installed licence text, if there is one.
    pub fn licence_text(&self) -> Result<Option<String>> {
        ix(self
            .conn
            .query_row(
                "SELECT value FROM settings WHERE key = 'licence'",
                [],
                |r| r.get(0),
            )
            .optional())
    }

    pub fn set_licence(&self, text: &str) -> Result<()> {
        ix(self.conn.execute(
            "INSERT INTO settings (key, value) VALUES ('licence', ?)
             ON CONFLICT(key) DO UPDATE SET value = excluded.value",
            params![text],
        ))
        .map(|_| ())
    }

    /// Devices that count against the seat limit: everything not revoked.
    ///
    /// Revoked devices are excluded on purpose — a seat freed by someone leaving should be
    /// usable, and their rows stay either way.
    pub fn active_device_count(&self) -> Result<usize> {
        ix(self.conn.query_row(
            "SELECT count(*) FROM devices WHERE revoked_at IS NULL",
            [],
            |r| r.get::<_, i64>(0),
        ))
        .map(|n| n as usize)
    }

    /// Seats in use: machines, not devices.
    ///
    /// Every project a person opens is its own store, so its own device with its own chain,
    /// and the licence promises a seat per machine. Devices that report the same machine share
    /// a seat. A device that has not yet said which machine it is on counts as one of its own
    /// until it does, because guessing would hand out seats nobody paid for.
    pub fn seats_in_use(&self) -> Result<usize> {
        ix(self.conn.query_row(
            "SELECT count(DISTINCT coalesce(machine, id)) FROM devices WHERE revoked_at IS NULL",
            [],
            |r| r.get::<_, i64>(0),
        ))
        .map(|n| n as usize)
    }

    /// Whether registering a device on this machine takes a seat: not when a device that can
    /// still send already reports the same machine.
    pub fn needs_seat(&self, machine: Option<&str>) -> Result<bool> {
        let Some(m) = machine else {
            return Ok(true);
        };
        let n: i64 = ix(self.conn.query_row(
            "SELECT count(*) FROM devices WHERE revoked_at IS NULL AND machine = ?",
            params![m],
            |r| r.get(0),
        ))?;
        Ok(n == 0)
    }

    /// Record which machine a device is on. It comes from the device itself, so it is exactly
    /// as trustworthy as the machine that sends it, which is the trust an offline licence
    /// already rests on.
    pub fn set_machine(&self, device: &str, machine: &str) -> Result<()> {
        ix(self.conn.execute(
            "UPDATE devices SET machine = ? WHERE id = ?",
            params![machine, device],
        ))
        .map(|_| ())
    }

    /// One device's rows, rebuilt as audit events in the order they were accepted.
    ///
    /// The detail column holds the row's JSON exactly as it arrived, `_chain` included, so
    /// what comes back out is what the client signed into its chain — which is the only
    /// reason a report can be re-verified by somebody else.
    pub fn rows_of(&self, device: &str) -> Result<Vec<AuditEvent>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT ts, actor, action, subject, detail FROM entries
             WHERE device = ? ORDER BY seq",
        ))?;
        let rows = ix(stmt.query_map(params![device], |r| {
            Ok((
                r.get::<_, String>(0)?,
                r.get::<_, String>(1)?,
                r.get::<_, String>(2)?,
                r.get::<_, String>(3)?,
                r.get::<_, String>(4)?,
            ))
        }))?;
        let mut out = Vec::new();
        for r in rows {
            let (ts, actor, action, subject, detail) = ix(r)?;
            out.push(AuditEvent {
                ts: ts
                    .parse()
                    .map_err(|e| Error::Index(format!("hub store: stored ts {ts:?}: {e}")))?,
                actor,
                action,
                subject,
                detail: serde_json::from_str(&detail)
                    .map_err(|e| Error::Index(format!("hub store: stored detail: {e}")))?,
            });
        }
        Ok(out)
    }

    pub fn total_entries(&self) -> Result<i64> {
        ix(self
            .conn
            .query_row("SELECT count(*) FROM entries", [], |r| r.get(0)))
    }
}

fn row_to_device(r: &rusqlite::Row<'_>) -> rusqlite::Result<Device> {
    Ok(Device {
        id: r.get(0)?,
        name: r.get(1)?,
        created_at: r.get(2)?,
        revoked_at: r.get(3)?,
        last_seen: r.get(4)?,
        anchor: r.get(5)?,
        rows: r.get(6)?,
        version: r.get(7)?,
        last_refusal: r.get(8)?,
        last_refusal_at: r.get(9)?,
        floor_hash: r.get(10)?,
        floor_seq: r.get(11)?,
        machine: r.get(12)?,
    })
}

/// Tokens are stored as a hash, like passwords, for the same reason.
fn token_hash(token: &str) -> String {
    blake3::hash(token.as_bytes()).to_hex().to_string()
}

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

    #[test]
    fn a_token_is_never_stored_in_the_clear() {
        let s = HubStore::in_memory().unwrap();
        let (_, token) = s.add_device("laptop", "2026-09-07T00:00:00Z").unwrap();
        let stored: String = s
            .conn
            .query_row("SELECT token_hash FROM devices", [], |r| r.get(0))
            .unwrap();
        assert_ne!(stored, token);
        assert_eq!(stored, token_hash(&token));
        assert!(s.device_by_token(&token).unwrap().is_some());
        assert!(s.device_by_token("cbh_wrong").unwrap().is_none());
    }

    #[test]
    fn a_new_device_starts_at_genesis() {
        let s = HubStore::in_memory().unwrap();
        let (d, _) = s.add_device("laptop", "2026-09-07T00:00:00Z").unwrap();
        assert_eq!(d.anchor, GENESIS);
        assert_eq!(d.rows, 0);
        assert!(d.is_active());
    }

    #[test]
    fn revoking_keeps_the_device_and_its_rows() {
        let s = HubStore::in_memory().unwrap();
        let (d, token) = s.add_device("laptop", "2026-09-07T00:00:00Z").unwrap();
        assert!(s.revoke(&d.id, "2026-09-08T00:00:00Z").unwrap());
        let back = s.device_by_token(&token).unwrap().unwrap();
        assert!(!back.is_active(), "a revoked device is still findable");
        // Revoking twice is not an error, but it is not a second event either.
        assert!(!s.revoke(&d.id, "2026-09-09T00:00:00Z").unwrap());
    }

    #[test]
    fn the_record_refuses_to_be_edited() {
        let mut s = HubStore::in_memory().unwrap();
        let (d, _) = s.add_device("laptop", "2026-09-07T00:00:00Z").unwrap();
        let event = AuditEvent {
            ts: "2026-09-07T00:00:01Z".parse().unwrap(),
            actor: "operator".into(),
            action: "note.write".into(),
            subject: "note:x".into(),
            detail: serde_json::json!({"_chain": {"prev": "genesis", "hash": "abc", "at": "t"}}),
        };
        s.append(&d, &[event], "abc", Some("0.2.1"), "2026-09-07T00:00:02Z")
            .unwrap();

        let update = s
            .conn
            .execute("UPDATE entries SET action = 'note.forget'", [])
            .unwrap_err()
            .to_string();
        assert!(update.contains("append-only"), "{update}");
        let delete = s
            .conn
            .execute("DELETE FROM entries", [])
            .unwrap_err()
            .to_string();
        assert!(delete.contains("append-only"), "{delete}");
    }

    fn rows(n: usize) -> Vec<AuditEvent> {
        (1..=n)
            .map(|i| AuditEvent {
                ts: format!("2026-09-07T00:00:0{i}Z").parse().unwrap(),
                actor: "operator".into(),
                action: "note.write".into(),
                subject: format!("note:{i}"),
                detail: serde_json::json!({}),
            })
            .collect()
    }

    /// The window a purge opens admits the rows below it, for its own device, and nothing else.
    #[test]
    fn a_purge_window_lets_only_rows_below_it_go() {
        let mut s = HubStore::in_memory().unwrap();
        let (d, _) = s.add_device("laptop", "2026-09-07T00:00:00Z").unwrap();
        let (other, _) = s.add_device("desk", "2026-09-07T00:00:00Z").unwrap();
        s.append(&d, &rows(3), "a", None, "2026-09-07T00:00:04Z")
            .unwrap();
        s.append(&other, &rows(3), "b", None, "2026-09-07T00:00:04Z")
            .unwrap();
        s.conn
            .execute(
                "INSERT INTO purge_window (device, below_seq) VALUES (?, 2)",
                params![d.id],
            )
            .unwrap();

        let above = s
            .conn
            .execute(
                "DELETE FROM entries WHERE device = ? AND seq >= 2",
                params![d.id],
            )
            .unwrap_err()
            .to_string();
        assert!(above.contains("append-only"), "{above}");
        let elsewhere = s
            .conn
            .execute(
                "DELETE FROM entries WHERE device = ? AND seq < 2",
                params![other.id],
            )
            .unwrap_err()
            .to_string();
        assert!(elsewhere.contains("append-only"), "{elsewhere}");
        assert_eq!(
            s.conn
                .execute(
                    "DELETE FROM entries WHERE device = ? AND seq < 2",
                    params![d.id]
                )
                .unwrap(),
            1
        );
    }

    /// A hub created before purges existed has the unconditional trigger; opening it replaces
    /// that once, and the replacement still refuses a delete outside a purge.
    #[test]
    fn a_hub_from_before_purges_gets_the_trigger_that_knows_them() {
        let mut s = HubStore::in_memory().unwrap();
        s.conn
            .execute_batch(
                "DROP TRIGGER entries_no_delete;
                 CREATE TRIGGER entries_no_delete BEFORE DELETE ON entries
                 BEGIN SELECT raise(ABORT, 'the hub record is append-only'); END;",
            )
            .unwrap();
        s.upgrade_delete_trigger().unwrap();
        let sql: String = s
            .conn
            .query_row(
                "SELECT sql FROM sqlite_master WHERE name = 'entries_no_delete'",
                [],
                |r| r.get(0),
            )
            .unwrap();
        assert!(sql.contains("purge_window"), "{sql}");

        let (d, _) = s.add_device("laptop", "2026-09-07T00:00:00Z").unwrap();
        s.append(&d, &rows(1), "a", None, "2026-09-07T00:00:02Z")
            .unwrap();
        let delete = s
            .conn
            .execute("DELETE FROM entries", [])
            .unwrap_err()
            .to_string();
        assert!(delete.contains("append-only"), "{delete}");
    }

    #[test]
    fn a_resolved_conflict_keeps_its_decision_and_drops_the_texts() {
        let s = HubStore::in_memory().unwrap();
        s.conn
            .execute(
                "INSERT INTO note_conflicts (id, bereich, name, held_updated, held_from_device,
                     offered_updated, offered_from_device, offered_frontmatter, offered_body,
                     detected_at)
                 VALUES ('c1', 'dispo', 'tour', 't1', 'dev_a', 't2', 'dev_b', 'name: tour',
                         'Die abgelehnte Fassung', 't3')",
                [],
            )
            .unwrap();
        assert!(
            s.resolve_conflict("c1", false, "2026-09-07T00:00:05Z")
                .unwrap()
        );
        let (body, front, resolution): (String, String, String) = s
            .conn
            .query_row(
                "SELECT offered_body, offered_frontmatter, resolution FROM note_conflicts",
                [],
                |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
            )
            .unwrap();
        assert_eq!((body.as_str(), front.as_str()), ("", ""));
        assert_eq!(resolution, "held");
    }
}

// ---------------------------------------------------------------------------------------
// People, requests, and the hub's own chain (slice 7).

use super::access::{AccessRequest, Denied, Principal, Role};

/// One event in the hub's own audit chain.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct HubEvent {
    pub seq: i64,
    pub ts: String,
    pub actor: String,
    pub action: String,
    pub detail: serde_json::Value,
    pub hash: String,
}

impl HubStore {
    // ----- note sync: grants and the notes themselves ------------------------------------

    /// Every grant recorded for a device, revoked ones included. `sync_access::may_move`
    /// needs the withdrawn ones to tell "never granted" from "taken away", which are
    /// different answers to whoever reads the refusal.
    pub fn grants_for_device(&self, device: &str) -> Result<Vec<super::sync_access::BereichGrant>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT id, device, bereich, direction, reason, granted_by, created_at,
                    approved_by, approved_at, revoked_at
             FROM bereich_grants WHERE device = ? ORDER BY created_at",
        ))?;
        let rows = ix(stmt.query_map(params![device], |r| {
            Ok((
                r.get::<_, String>(0)?,
                r.get::<_, String>(1)?,
                r.get::<_, String>(2)?,
                r.get::<_, String>(3)?,
                r.get::<_, String>(4)?,
                r.get::<_, String>(5)?,
                r.get::<_, String>(6)?,
                r.get::<_, Option<String>>(7)?,
                r.get::<_, Option<String>>(8)?,
                r.get::<_, Option<String>>(9)?,
            ))
        }))?;
        let mut out = Vec::new();
        for row in rows {
            let (
                id,
                device,
                bereich,
                direction,
                reason,
                granted_by,
                created_at,
                approved_by,
                approved_at,
                revoked_at,
            ) = ix(row)?;
            out.push(super::sync_access::BereichGrant {
                id,
                device,
                bereich,
                direction: super::sync_access::Direction::parse(&direction)?,
                reason,
                granted_by,
                created_at,
                approved_by,
                approved_at,
                revoked_at,
            });
        }
        Ok(out)
    }

    /// One grant, by id.
    pub fn grant(&self, id: &str) -> Result<Option<super::sync_access::BereichGrant>> {
        let device: Option<String> = ix(self
            .conn
            .query_row(
                "SELECT device FROM bereich_grants WHERE id = ?",
                params![id],
                |r| r.get(0),
            )
            .optional())?;
        let Some(device) = device else {
            return Ok(None);
        };
        Ok(self
            .grants_for_device(&device)?
            .into_iter()
            .find(|g| g.id == id))
    }

    /// Let a grant take effect. The second of the two people a bereich takes.
    ///
    /// Refuses the person who wrote it, whatever role they hold: two signatures from one
    /// hand are one signature. Refuses a grant that is already signed, so "countersigned by"
    /// names the person who actually decided rather than the last one to run the command,
    /// and refuses a withdrawn one, because reviving it is a new decision and should look
    /// like one.
    pub fn countersign_grant(
        &self,
        id: &str,
        who: &super::access::Principal,
        now: &str,
    ) -> Result<CountersignOutcome> {
        let Some(g) = self.grant(id)? else {
            return Ok(CountersignOutcome::Unknown);
        };
        if g.revoked_at.is_some() {
            return Ok(CountersignOutcome::Withdrawn);
        }
        if let Some(by) = &g.approved_by {
            return Ok(CountersignOutcome::AlreadySigned { by: by.clone() });
        }
        if g.granted_by == who.id {
            return Ok(CountersignOutcome::SamePerson);
        }
        ix(self.conn.execute(
            "UPDATE bereich_grants SET approved_by = ?, approved_at = ?
             WHERE id = ? AND approved_at IS NULL",
            params![who.id, now, id],
        ))?;
        self.record(
            &who.id,
            "grant.countersigned",
            serde_json::json!({
                "id": g.id,
                "device": g.device,
                "bereich": g.bereich,
                "direction": g.direction.as_str(),
                "granted_by": g.granted_by,
                "by": who.name,
            }),
            now,
        )?;
        Ok(CountersignOutcome::Signed)
    }

    /// Record a grant. The caller checks that the granter is an administrator; this writes.
    ///
    /// One argument per column, and a struct to carry them would be a second name for the
    /// row that already has one.
    #[allow(clippy::too_many_arguments)]
    pub fn grant_bereich(
        &self,
        id: &str,
        device: &str,
        bereich: &str,
        direction: super::sync_access::Direction,
        reason: &str,
        granted_by: &str,
        now: &str,
    ) -> Result<()> {
        ix(self.conn.execute(
            "INSERT INTO bereich_grants
                (id, device, bereich, direction, reason, granted_by, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
            params![
                id,
                device,
                bereich,
                direction.as_str(),
                reason,
                granted_by,
                now
            ],
        ))?;
        Ok(())
    }

    pub fn revoke_grant(&self, id: &str, now: &str) -> Result<bool> {
        let n = ix(self.conn.execute(
            "UPDATE bereich_grants SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL",
            params![now, id],
        ))?;
        Ok(n > 0)
    }

    /// What became of one offered note.
    #[allow(clippy::too_many_arguments)]
    pub fn offer_synced_note(
        &self,
        id: &str,
        bereich: &str,
        name: &str,
        ring: u8,
        kind: &str,
        updated: &str,
        frontmatter: &str,
        body: &str,
        based_on: Option<&str>,
        from_device: &str,
        now: &str,
    ) -> Result<NoteOutcome> {
        let held: Option<(String, String)> = ix(self
            .conn
            .query_row(
                "SELECT updated, from_device FROM synced_notes WHERE bereich = ? AND name = ?",
                params![bereich, name],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .optional())?;

        match held {
            // Nothing held: nothing to conflict with.
            None => {
                self.write_synced_note(
                    id,
                    bereich,
                    name,
                    ring,
                    kind,
                    updated,
                    frontmatter,
                    body,
                    from_device,
                    now,
                )?;
                Ok(NoteOutcome::Stored)
            }
            Some((held_updated, held_device)) => {
                // The sender says which version it started from. Equal means it saw what the
                // hub holds and moved on from there: a continuation, and safe to take.
                if based_on == Some(held_updated.as_str()) {
                    self.write_synced_note(
                        id,
                        bereich,
                        name,
                        ring,
                        kind,
                        updated,
                        frontmatter,
                        body,
                        from_device,
                        now,
                    )?;
                    return Ok(NoteOutcome::Stored);
                }
                // Byte-identical to what is held is not a conflict, it is a re-send.
                if updated == held_updated {
                    return Ok(NoteOutcome::Unchanged);
                }
                // Anything else is two machines that did not see each other. Keep both.
                let cid = format!("nc_{}", cyberbrain_core::NoteId::generate());
                ix(self.conn.execute(
                    "INSERT INTO note_conflicts
                        (id, bereich, name, held_updated, held_from_device, offered_updated,
                         offered_from_device, offered_frontmatter, offered_body, based_on,
                         detected_at)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                    params![
                        cid,
                        bereich,
                        name,
                        held_updated,
                        held_device,
                        updated,
                        from_device,
                        frontmatter,
                        body,
                        based_on,
                        now
                    ],
                ))?;
                Ok(NoteOutcome::Conflict {
                    id: cid,
                    held_updated,
                })
            }
        }
    }

    /// Hold a note on behalf of a bereich, unconditionally. Callers reach this through
    /// `offer_synced_note`, which is where the decision lives.
    #[allow(clippy::too_many_arguments)]
    fn write_synced_note(
        &self,
        id: &str,
        bereich: &str,
        name: &str,
        ring: u8,
        kind: &str,
        updated: &str,
        frontmatter: &str,
        body: &str,
        from_device: &str,
        now: &str,
    ) -> Result<()> {
        ix(self.conn.execute(
            "INSERT INTO synced_notes
                (id, bereich, name, ring, kind, updated, frontmatter, body, from_device,
                 received_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
             ON CONFLICT(bereich, name) DO UPDATE SET
                id = excluded.id, ring = excluded.ring, kind = excluded.kind,
                updated = excluded.updated, frontmatter = excluded.frontmatter,
                body = excluded.body, from_device = excluded.from_device,
                received_at = excluded.received_at",
            params![
                id,
                bereich,
                name,
                ring,
                kind,
                updated,
                frontmatter,
                body,
                from_device,
                now
            ],
        ))?;
        Ok(())
    }

    /// Erase a note the hub holds, everywhere it holds it.
    ///
    /// Four places carry the text, not one: the held note's body and frontmatter, and the
    /// offered body and frontmatter of every conflict about it. An erasure that only clears
    /// `synced_notes` leaves the text sitting in a conflict row, which is the same data with
    /// a different column name.
    ///
    /// Returns how many rows in each, so the caller can say what was actually removed rather
    /// than assert that something was.
    pub fn erase_note(
        &self,
        bereich: &str,
        name: &str,
        by_device: &str,
        now: &str,
    ) -> Result<ErasureCount> {
        let notes = ix(self.conn.execute(
            "DELETE FROM synced_notes WHERE bereich = ? AND name = ?",
            params![bereich, name],
        ))?;
        let conflicts = ix(self.conn.execute(
            "DELETE FROM note_conflicts WHERE bereich = ? AND name = ?",
            params![bereich, name],
        ))?;
        // The tombstone carries no text. It is what stops the next delivery from recreating
        // what somebody asked to have removed.
        ix(self.conn.execute(
            "INSERT INTO erasures (bereich, name, erased_at, by_device)
             VALUES (?, ?, ?, ?)
             ON CONFLICT(bereich, name) DO UPDATE SET
                erased_at = excluded.erased_at, by_device = excluded.by_device",
            params![bereich, name, now, by_device],
        ))?;
        Ok(ErasureCount { notes, conflicts })
    }

    /// Was this note erased, and when? Checked before taking a delivery, so a machine that
    /// still has its own copy cannot put it back.
    pub fn erased_at(&self, bereich: &str, name: &str) -> Result<Option<String>> {
        ix(self
            .conn
            .query_row(
                "SELECT erased_at FROM erasures WHERE bereich = ? AND name = ?",
                params![bereich, name],
                |r| r.get::<_, String>(0),
            )
            .optional())
    }

    /// Every text column of every table, concatenated. Only for the erasure test, which
    /// checks the whole record rather than a list of columns: a table added later must not
    /// be able to reintroduce erased text without that test noticing.
    #[cfg(test)]
    pub fn dump_all_text(&self) -> Result<String> {
        let mut out = String::new();
        let mut tables = Vec::new();
        {
            let mut stmt = ix(self
                .conn
                .prepare("SELECT name FROM sqlite_master WHERE type = 'table'"))?;
            let rows = ix(stmt.query_map([], |r| r.get::<_, String>(0)))?;
            for r in rows {
                tables.push(ix(r)?);
            }
        }
        for t in tables {
            let mut stmt = ix(self.conn.prepare(&format!("SELECT * FROM \"{t}\"")))?;
            let cols = stmt.column_count();
            let rows = ix(stmt.query_map([], move |r| {
                let mut line = String::new();
                for i in 0..cols {
                    if let Ok(v) = r.get::<_, String>(i) {
                        line.push_str(&v);
                        line.push('\n');
                    }
                }
                Ok(line)
            }))?;
            for r in rows {
                out.push_str(&ix(r)?);
            }
        }
        Ok(out)
    }

    /// Notes a device may fetch: everything held in the bereiche it holds a receive grant
    /// in, changed since `since`. The filter is by grant and not by request, so asking for a
    /// bereich you were not granted returns nothing rather than an error — a fetch is not a
    /// place to learn which departments exist.
    pub fn notes_for_device(&self, device: &str, since: Option<&str>) -> Result<Vec<SyncedNote>> {
        let grants = self.grants_for_device(device)?;
        let mut out = Vec::new();
        // `is_effective`, not `is_active`: a grant nobody countersigned is written down and
        // inert. These two loops are the reading side of the same rule `may_move` states,
        // and they answer without asking it — so the rule has to hold here in its own
        // right, or the operator writes themselves a grant and reads the department.
        for g in grants.iter().filter(|g| {
            g.is_effective()
                && matches!(
                    g.direction,
                    super::sync_access::Direction::Receive | super::sync_access::Direction::Both
                )
        }) {
            for n in self.synced_notes(&g.bereich)? {
                if let Some(s) = since
                    && n.updated.as_str() <= s
                {
                    continue;
                }
                out.push(n);
            }
        }
        Ok(out)
    }

    /// Erasures in the bereiche a device may receive. Sent alongside the notes so a puller
    /// learns that something was withdrawn, not merely that it stopped being offered —
    /// which are indistinguishable if only present notes travel.
    pub fn erasures_for_device(
        &self,
        device: &str,
        since: Option<&str>,
    ) -> Result<Vec<(String, String, String)>> {
        let grants = self.grants_for_device(device)?;
        let mut out = Vec::new();
        // `is_effective`, not `is_active`: a grant nobody countersigned is written down and
        // inert. These two loops are the reading side of the same rule `may_move` states,
        // and they answer without asking it — so the rule has to hold here in its own
        // right, or the operator writes themselves a grant and reads the department.
        for g in grants.iter().filter(|g| {
            g.is_effective()
                && matches!(
                    g.direction,
                    super::sync_access::Direction::Receive | super::sync_access::Direction::Both
                )
        }) {
            let mut stmt = ix(self.conn.prepare(
                "SELECT bereich, name, erased_at FROM erasures
                 WHERE bereich = ? AND (?2 IS NULL OR erased_at > ?2)
                 ORDER BY erased_at",
            ))?;
            let rows = ix(stmt.query_map(params![g.bereich, since], |r| {
                Ok((r.get(0)?, r.get(1)?, r.get(2)?))
            }))?;
            for r in rows {
                out.push(ix(r)?);
            }
        }
        Ok(out)
    }

    /// Put a person in charge of a bereich. Only meaningful for an `editor`; the caller
    /// checks the role, this writes.
    pub fn assign_bereich(&self, principal: &str, bereich: &str, now: &str) -> Result<()> {
        ix(self.conn.execute(
            "INSERT INTO principal_bereiche (principal, bereich, added_at) VALUES (?, ?, ?)
             ON CONFLICT(principal, bereich) DO NOTHING",
            params![principal, bereich, now],
        ))?;
        Ok(())
    }

    /// The bereiche a person is responsible for.
    pub fn bereiche_of(&self, principal: &str) -> Result<Vec<String>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT bereich FROM principal_bereiche WHERE principal = ? ORDER BY bereich",
        ))?;
        let rows = ix(stmt.query_map(params![principal], |r| r.get::<_, String>(0)))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(ix(r)?);
        }
        Ok(out)
    }

    /// Open conflicts this person may see: the ones in their bereiche, and no others.
    /// Filtering here rather than at the page means a mistake in a template cannot widen it.
    ///
    /// The held text is fetched alongside. A conflict row holds only the version that was
    /// turned away; showing that on its own asks somebody to choose between a text and a
    /// blank, which is not a choice.
    pub fn conflicts_for_principal(&self, principal: &str) -> Result<Vec<(NoteConflict, String)>> {
        let mut out = Vec::new();
        for b in self.bereiche_of(principal)? {
            for c in self.open_conflicts(&b)? {
                let held: Option<String> = ix(self
                    .conn
                    .query_row(
                        "SELECT body FROM synced_notes WHERE bereich = ? AND name = ?",
                        params![c.bereich, c.name],
                        |r| r.get(0),
                    )
                    .optional())?;
                let held = held.unwrap_or_else(|| {
                    "(the held version is no longer here — it was erased or replaced)".into()
                });
                out.push((c, held));
            }
        }
        Ok(out)
    }

    /// One conflict, but only if this person is responsible for its bereich.
    pub fn conflict_for_principal(
        &self,
        principal: &str,
        id: &str,
    ) -> Result<Option<NoteConflict>> {
        Ok(self
            .conflicts_for_principal(principal)?
            .into_iter()
            .map(|(c, _)| c)
            .find(|c| c.id == id))
    }

    /// Conflicts nobody has decided yet. Open ones only: a resolved conflict is history and
    /// belongs in the log, not in a list of things waiting for a person.
    pub fn open_conflicts(&self, bereich: &str) -> Result<Vec<NoteConflict>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT id, bereich, name, held_updated, held_from_device, offered_updated,
                    offered_from_device, offered_frontmatter, offered_body, based_on, detected_at
             FROM note_conflicts
             WHERE bereich = ? AND resolved_at IS NULL
             ORDER BY detected_at",
        ))?;
        let rows = ix(stmt.query_map(params![bereich], |r| {
            Ok(NoteConflict {
                id: r.get(0)?,
                bereich: r.get(1)?,
                name: r.get(2)?,
                held_updated: r.get(3)?,
                held_from_device: r.get(4)?,
                offered_updated: r.get(5)?,
                offered_from_device: r.get(6)?,
                offered_frontmatter: r.get(7)?,
                offered_body: r.get(8)?,
                based_on: r.get(9)?,
                detected_at: r.get(10)?,
            })
        }))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(ix(r)?);
        }
        Ok(out)
    }

    /// Settle one conflict. `take_offered` replaces what is held with the version that was
    /// turned away; otherwise the held version stands. Either way the conflict is closed
    /// with a note of which way it went, so the decision is not folded into the data.
    pub fn resolve_conflict(&self, id: &str, take_offered: bool, now: &str) -> Result<bool> {
        let c: Option<NoteConflict> = ix(self
            .conn
            .query_row(
                "SELECT id, bereich, name, held_updated, held_from_device, offered_updated,
                        offered_from_device, offered_frontmatter, offered_body, based_on,
                        detected_at
                 FROM note_conflicts WHERE id = ? AND resolved_at IS NULL",
                params![id],
                |r| {
                    Ok(NoteConflict {
                        id: r.get(0)?,
                        bereich: r.get(1)?,
                        name: r.get(2)?,
                        held_updated: r.get(3)?,
                        held_from_device: r.get(4)?,
                        offered_updated: r.get(5)?,
                        offered_from_device: r.get(6)?,
                        offered_frontmatter: r.get(7)?,
                        offered_body: r.get(8)?,
                        based_on: r.get(9)?,
                        detected_at: r.get(10)?,
                    })
                },
            )
            .optional())?;
        let Some(c) = c else { return Ok(false) };
        if take_offered {
            ix(self.conn.execute(
                "UPDATE synced_notes
                 SET updated = ?, frontmatter = ?, body = ?, from_device = ?, received_at = ?
                 WHERE bereich = ? AND name = ?",
                params![
                    c.offered_updated,
                    c.offered_frontmatter,
                    c.offered_body,
                    c.offered_from_device,
                    now,
                    c.bereich,
                    c.name
                ],
            ))?;
        }
        ix(self.conn.execute(
            // The texts go with the resolution. The decision (which way, when) is the record;
            // keeping the version that lost would keep a second copy of a department's
            // text for as long as the hub lives, for no purpose anybody could name.
            "UPDATE note_conflicts SET resolved_at = ?, resolution = ?,
                 offered_frontmatter = '', offered_body = '' WHERE id = ?",
            params![now, if take_offered { "offered" } else { "held" }, id],
        ))?;
        Ok(true)
    }

    /// What the hub holds for a bereich, newest first.
    pub fn synced_notes(&self, bereich: &str) -> Result<Vec<SyncedNote>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT id, bereich, name, ring, kind, updated, frontmatter, body, from_device
             FROM synced_notes WHERE bereich = ? ORDER BY updated DESC",
        ))?;
        let rows = ix(stmt.query_map(params![bereich], |r| {
            Ok(SyncedNote {
                id: r.get(0)?,
                bereich: r.get(1)?,
                name: r.get(2)?,
                ring: r.get::<_, i64>(3)? as u8,
                kind: r.get(4)?,
                updated: r.get(5)?,
                frontmatter: r.get(6)?,
                body: r.get(7)?,
                from_device: r.get(8)?,
            })
        }))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(ix(r)?);
        }
        Ok(out)
    }

    /// Append to the hub's own chain. Every call in this file that changes who may see what
    /// goes through here, so "it happened but was not recorded" is not a reachable state.
    pub fn record(
        &self,
        actor: &str,
        action: &str,
        detail: serde_json::Value,
        now: &str,
    ) -> Result<String> {
        let prev = self.last_hub_hash()?;
        let detail_text = detail.to_string();
        // Same rule as the store's audit chain: prev, timestamp, actor, action, detail,
        // each terminated, so a reader can recompute it without knowing this code.
        let mut h = blake3::Hasher::new();
        for part in [prev.as_str(), now, actor, action] {
            h.update(part.as_bytes());
            h.update(b"\n");
        }
        h.update(detail_text.as_bytes());
        let hash = h.finalize().to_hex().to_string();
        ix(self.conn.execute(
            "INSERT INTO hub_audit (ts, actor, action, detail, prev, hash)
             VALUES (?, ?, ?, ?, ?, ?)",
            params![now, actor, action, detail_text, prev, hash],
        ))?;
        Ok(hash)
    }

    fn last_hub_hash(&self) -> Result<String> {
        ix(self
            .conn
            .query_row(
                "SELECT hash FROM hub_audit ORDER BY seq DESC LIMIT 1",
                [],
                |r| r.get::<_, String>(0),
            )
            .optional())
        .map(|h| h.unwrap_or_else(|| GENESIS.to_string()))
    }

    /// The hub's own events, oldest first.
    pub fn hub_events(&self, limit: usize) -> Result<Vec<HubEvent>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT seq, ts, actor, action, detail, hash FROM hub_audit ORDER BY seq LIMIT ?",
        ))?;
        let rows = ix(stmt.query_map(params![limit as i64], |r| {
            Ok(HubEvent {
                seq: r.get(0)?,
                ts: r.get(1)?,
                actor: r.get(2)?,
                action: r.get(3)?,
                detail: serde_json::from_str(&r.get::<_, String>(4)?)
                    .unwrap_or(serde_json::Value::Null),
                hash: r.get(5)?,
            })
        }))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(ix(r)?);
        }
        Ok(out)
    }

    /// Recompute the hub's own chain. Same question as `hub verify` asks of device rows.
    pub fn verify_hub_chain(&self) -> Result<usize> {
        let mut stmt = ix(self
            .conn
            .prepare("SELECT ts, actor, action, detail, prev, hash FROM hub_audit ORDER BY seq"))?;
        let rows = ix(stmt.query_map([], |r| {
            Ok((
                r.get::<_, String>(0)?,
                r.get::<_, String>(1)?,
                r.get::<_, String>(2)?,
                r.get::<_, String>(3)?,
                r.get::<_, String>(4)?,
                r.get::<_, String>(5)?,
            ))
        }))?;
        let mut prev = GENESIS.to_string();
        let mut n = 0usize;
        for row in rows {
            let (ts, actor, action, detail, stored_prev, stored_hash) = ix(row)?;
            n += 1;
            if stored_prev != prev {
                return Err(Error::Index(format!(
                    "hub audit chain broken at row {n} ({action}): a row was removed, \
                     reordered or inserted"
                )));
            }
            let mut h = blake3::Hasher::new();
            for part in [prev.as_str(), &ts, &actor, &action] {
                h.update(part.as_bytes());
                h.update(b"\n");
            }
            h.update(detail.as_bytes());
            let want = h.finalize().to_hex().to_string();
            if want != stored_hash {
                return Err(Error::Index(format!(
                    "hub audit chain broken at row {n} ({action}): the row was edited"
                )));
            }
            prev = stored_hash;
        }
        Ok(n)
    }

    pub fn add_principal(&self, name: &str, role: Role, now: &str) -> Result<(Principal, String)> {
        let id = format!("who_{}", cyberbrain_core::NoteId::generate());
        let token = format!("cbp_{}", cyberbrain_core::NoteId::generate());
        ix(self.conn.execute(
            "INSERT INTO principals (id, name, role, token_hash, created_at)
             VALUES (?, ?, ?, ?, ?)",
            params![id, name, role.as_str(), token_hash(&token), now],
        ))?;
        self.record(
            "hub",
            "role.granted",
            serde_json::json!({ "principal": id, "name": name, "role": role.as_str() }),
            now,
        )?;
        Ok((
            Principal {
                id,
                name: name.to_string(),
                role,
                created_at: now.to_string(),
                revoked_at: None,
            },
            token,
        ))
    }

    pub fn principal_by_token(&self, token: &str) -> Result<Option<Principal>> {
        let hash = token_hash(token);
        ix(self
            .conn
            .query_row(
                "SELECT id, name, role, created_at, revoked_at FROM principals
                 WHERE token_hash = ?",
                params![hash],
                row_to_principal,
            )
            .optional())
    }

    pub fn principals(&self) -> Result<Vec<Principal>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT id, name, role, created_at, revoked_at FROM principals
             ORDER BY created_at, id",
        ))?;
        let rows = ix(stmt.query_map([], row_to_principal))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(ix(r)?);
        }
        Ok(out)
    }

    pub fn revoke_principal(&self, id: &str, now: &str) -> Result<bool> {
        let n = ix(self.conn.execute(
            "UPDATE principals SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL",
            params![now, id],
        ))?;
        if n > 0 {
            self.record(
                "hub",
                "role.revoked",
                serde_json::json!({ "principal": id }),
                now,
            )?;
        }
        Ok(n > 0)
    }

    /// Authenticate a person and check their role in one step, so no caller can do the
    /// first and forget the second.
    pub fn principal_for(
        &self,
        token: Option<&str>,
        need: Role,
    ) -> std::result::Result<Principal, Denied> {
        let token = token.ok_or_else(|| {
            Denied::NotAuthorised(
                "no credential; pass --as <token> or set CYBERBRAIN_HUB_PRINCIPAL_TOKEN".into(),
            )
        })?;
        let who = self
            .principal_by_token(token)
            .map_err(|e| Denied::NotAuthorised(format!("cannot check the credential: {e}")))?
            .ok_or_else(|| Denied::NotAuthorised("unknown credential".into()))?;
        if !who.is_active() {
            return Err(Denied::NotAuthorised(format!("{} was revoked", who.name)));
        }
        if who.role != need {
            return Err(Denied::WrongRole {
                need,
                has: who.role,
            });
        }
        Ok(who)
    }

    pub fn create_request(
        &self,
        requester: &Principal,
        device: Option<&str>,
        from: Option<&str>,
        to: Option<&str>,
        reason: &str,
        now: &str,
    ) -> Result<AccessRequest> {
        let id = format!("req_{}", cyberbrain_core::NoteId::generate());
        ix(self.conn.execute(
            "INSERT INTO access_requests (id, requester, device, from_ts, to_ts, reason, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
            params![id, requester.id, device, from, to, reason, now],
        ))?;
        self.record(
            &requester.id,
            "access.requested",
            serde_json::json!({
                "request": id, "device": device, "from": from, "to": to, "reason": reason,
            }),
            now,
        )?;
        Ok(AccessRequest {
            id,
            requester: requester.id.clone(),
            requester_name: requester.name.clone(),
            device: device.map(str::to_owned),
            from: from.map(str::to_owned),
            to: to.map(str::to_owned),
            reason: reason.to_string(),
            created_at: now.to_string(),
            approved_by: None,
            approved_by_name: None,
            approved_at: None,
            expires_at: None,
            disclosures: 0,
        })
    }

    pub fn request(&self, id: &str) -> Result<Option<AccessRequest>> {
        ix(self
            .conn
            .query_row(
                "SELECT r.id, r.requester, p.name, r.device, r.from_ts, r.to_ts, r.reason,
                        r.created_at, r.approved_by, q.name, r.approved_at, r.expires_at,
                        r.disclosures
                 FROM access_requests r
                 JOIN principals p ON p.id = r.requester
                 LEFT JOIN principals q ON q.id = r.approved_by
                 WHERE r.id = ?",
                params![id],
                row_to_request,
            )
            .optional())
    }

    pub fn requests(&self) -> Result<Vec<AccessRequest>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT r.id, r.requester, p.name, r.device, r.from_ts, r.to_ts, r.reason,
                    r.created_at, r.approved_by, q.name, r.approved_at, r.expires_at,
                    r.disclosures
             FROM access_requests r
             JOIN principals p ON p.id = r.requester
             LEFT JOIN principals q ON q.id = r.approved_by
             ORDER BY r.created_at DESC",
        ))?;
        let rows = ix(stmt.query_map([], row_to_request))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(ix(r)?);
        }
        Ok(out)
    }

    /// Countersign. The caller has already checked the role; this enforces the part that is
    /// about identity rather than permission.
    pub fn approve_request(
        &self,
        id: &str,
        by: &Principal,
        expires_at: &str,
        now: &str,
    ) -> std::result::Result<AccessRequest, Denied> {
        let req = self
            .request(id)
            .map_err(|e| Denied::NotAuthorised(e.to_string()))?
            .ok_or_else(|| Denied::NotApproved(id.to_string()))?;
        if req.requester == by.id {
            return Err(Denied::SamePerson);
        }
        self.conn
            .execute(
                "UPDATE access_requests SET approved_by = ?, approved_at = ?, expires_at = ?
                 WHERE id = ? AND approved_at IS NULL",
                params![by.id, now, expires_at, id],
            )
            .map_err(|e| Denied::NotAuthorised(format!("cannot record the approval: {e}")))?;
        let _ = self.record(
            &by.id,
            "access.approved",
            serde_json::json!({ "request": id, "expires_at": expires_at }),
            now,
        );
        self.request(id)
            .map_err(|e| Denied::NotAuthorised(e.to_string()))?
            .ok_or_else(|| Denied::NotApproved(id.to_string()))
    }

    /// Note that rows were handed out under a request.
    pub fn note_disclosure(&self, id: &str, by: &str, rows: usize, now: &str) -> Result<()> {
        ix(self.conn.execute(
            "UPDATE access_requests SET disclosures = disclosures + 1 WHERE id = ?",
            params![id],
        ))?;
        self.record(
            by,
            "access.disclosed",
            serde_json::json!({ "request": id, "rows": rows }),
            now,
        )?;
        Ok(())
    }
}

fn row_to_principal(r: &rusqlite::Row<'_>) -> rusqlite::Result<Principal> {
    Ok(Principal {
        id: r.get(0)?,
        name: r.get(1)?,
        role: Role::parse(&r.get::<_, String>(2)?).unwrap_or(Role::Admin),
        created_at: r.get(3)?,
        revoked_at: r.get(4)?,
    })
}

fn row_to_request(r: &rusqlite::Row<'_>) -> rusqlite::Result<AccessRequest> {
    Ok(AccessRequest {
        id: r.get(0)?,
        requester: r.get(1)?,
        requester_name: r.get(2)?,
        device: r.get(3)?,
        from: r.get(4)?,
        to: r.get(5)?,
        reason: r.get(6)?,
        created_at: r.get(7)?,
        approved_by: r.get(8)?,
        approved_by_name: r.get(9)?,
        approved_at: r.get(10)?,
        expires_at: r.get(11)?,
        disclosures: r.get(12)?,
    })
}

// ---------------------------------------------------------------------------------------
// How long activity rows are kept, and removing the ones past that (retention).

/// A purge: every device's rows older than `cutoff` go, once a second person has signed.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct Purge {
    pub id: String,
    pub cutoff: String,
    pub retention: String,
    pub reason: String,
    pub proposed_by: String,
    pub created_at: String,
    pub approved_by: Option<String>,
    pub approved_at: Option<String>,
    pub rows_removed: Option<i64>,
}

impl Purge {
    pub fn is_pending(&self) -> bool {
        self.approved_at.is_none()
    }
}

/// What became of a countersignature on a purge.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
#[serde(tag = "outcome", rename_all = "kebab-case")]
pub enum PurgeOutcome {
    /// Carried out: how many rows went, in total and per device.
    CarriedOut {
        rows: i64,
        devices: Vec<(String, i64)>,
    },
    Unknown,
    AlreadyDone {
        by: String,
    },
    /// The person who proposed it is the person trying to sign it.
    SamePerson,
}

impl HubStore {
    /// The retention period, as an ISO-8601 duration, if one was set.
    pub fn retention(&self) -> Result<Option<String>> {
        self.setting("retention")
    }

    /// Set how long activity rows are kept. Setting it removes nothing: a purge is a separate,
    /// countersigned step, because a typo in a period must not be able to delete a year.
    pub fn set_retention(&self, period: &str, by: &str, now: &str) -> Result<()> {
        cutoff_for(period, now)?;
        self.set_setting("retention", period)?;
        self.record(
            by,
            "retention.set",
            serde_json::json!({ "retention": period }),
            now,
        )?;
        Ok(())
    }

    /// Per device: how many rows a purge with this cutoff removes, and the seq it stops below.
    ///
    /// A prefix of the chain, never a selection. Everything before the first row that is not
    /// old enough goes, and nothing after it, even a row that looks old: a device whose clock
    /// once ran backwards has one, and removing it would cut a hole no floor can bridge.
    pub fn purge_plan(&self, cutoff: &str) -> Result<Vec<(String, i64, i64)>> {
        let mut out = Vec::new();
        for d in self.devices()? {
            let boundary: i64 = ix(self.conn.query_row(
                "SELECT coalesce(
                     (SELECT min(seq) FROM entries WHERE device = ?1 AND ts >= ?2),
                     (SELECT coalesce(max(seq), 0) + 1 FROM entries WHERE device = ?1))",
                params![d.id, cutoff],
                |r| r.get(0),
            ))?;
            let n: i64 = ix(self.conn.query_row(
                "SELECT count(*) FROM entries WHERE device = ? AND seq < ?",
                params![d.id, boundary],
                |r| r.get(0),
            ))?;
            out.push((d.id, n, boundary));
        }
        Ok(out)
    }

    /// Write a purge down. Removes nothing; the countersignature does.
    pub fn propose_purge(&self, reason: &str, by: &str, now: &str) -> Result<(Purge, i64)> {
        if reason.trim().is_empty() {
            return Err(Error::Config(
                "a purge needs a reason: the countersigner reads it, and so does an auditor later"
                    .into(),
            ));
        }
        let Some(retention) = self.retention()? else {
            return Err(Error::Config(
                "no retention period is set; run `cyberbrain hub retention set <period>` first"
                    .into(),
            ));
        };
        let cutoff = cutoff_for(&retention, now)?;
        let would = self
            .purge_plan(&cutoff)?
            .iter()
            .map(|(_, n, _)| n)
            .sum::<i64>();
        let p = Purge {
            id: format!("pg_{}", cyberbrain_core::NoteId::generate()),
            cutoff,
            retention,
            reason: reason.to_string(),
            proposed_by: by.to_string(),
            created_at: now.to_string(),
            approved_by: None,
            approved_at: None,
            rows_removed: None,
        };
        ix(self.conn.execute(
            "INSERT INTO purges (id, cutoff, retention, reason, proposed_by, created_at)
             VALUES (?, ?, ?, ?, ?, ?)",
            params![
                p.id,
                p.cutoff,
                p.retention,
                p.reason,
                p.proposed_by,
                p.created_at
            ],
        ))?;
        self.record(
            by,
            "purge.proposed",
            serde_json::json!({
                "id": p.id, "cutoff": p.cutoff, "retention": p.retention,
                "reason": p.reason, "would_remove": would,
            }),
            now,
        )?;
        Ok((p, would))
    }

    /// Every purge, oldest first.
    pub fn purges(&self) -> Result<Vec<Purge>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT id, cutoff, retention, reason, proposed_by, created_at, approved_by,
                    approved_at, rows_removed
             FROM purges ORDER BY created_at, id",
        ))?;
        let rows = ix(stmt.query_map([], |r| {
            Ok(Purge {
                id: r.get(0)?,
                cutoff: r.get(1)?,
                retention: r.get(2)?,
                reason: r.get(3)?,
                proposed_by: r.get(4)?,
                created_at: r.get(5)?,
                approved_by: r.get(6)?,
                approved_at: r.get(7)?,
                rows_removed: r.get(8)?,
            })
        }))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(ix(r)?);
        }
        Ok(out)
    }

    /// The second signature, and the purge itself.
    ///
    /// One transaction around all of it, the record included: rows removed without the entry
    /// that says so, or an entry for rows that are still there, are both states nobody should
    /// be able to find. Each device's chain gets a floor, the hash of its last removed row,
    /// so what remains still verifies (`report::verify` starts there).
    pub fn countersign_purge(
        &self,
        id: &str,
        who: &super::access::Principal,
        now: &str,
    ) -> Result<PurgeOutcome> {
        let Some(p) = self.purges()?.into_iter().find(|p| p.id == id) else {
            return Ok(PurgeOutcome::Unknown);
        };
        if let Some(by) = &p.approved_by {
            return Ok(PurgeOutcome::AlreadyDone { by: by.clone() });
        }
        if p.proposed_by == who.id {
            return Ok(PurgeOutcome::SamePerson);
        }
        ix(self.conn.execute_batch("BEGIN IMMEDIATE"))?;
        let carried = (|| -> Result<PurgeOutcome> {
            let mut devices = Vec::new();
            let mut total = 0i64;
            for (device, n, boundary) in self.purge_plan(&p.cutoff)? {
                if n == 0 {
                    continue;
                }
                let (floor_seq, floor_hash): (i64, String) = ix(self.conn.query_row(
                    "SELECT seq, hash FROM entries WHERE device = ? AND seq < ?
                     ORDER BY seq DESC LIMIT 1",
                    params![device, boundary],
                    |r| Ok((r.get(0)?, r.get(1)?)),
                ))?;
                ix(self.conn.execute(
                    "INSERT INTO purge_window (device, below_seq) VALUES (?, ?)",
                    params![device, boundary],
                ))?;
                let removed = ix(self.conn.execute(
                    "DELETE FROM entries WHERE device = ? AND seq < ?",
                    params![device, boundary],
                ))? as i64;
                ix(self
                    .conn
                    .execute("DELETE FROM purge_window WHERE device = ?", params![device]))?;
                ix(self.conn.execute(
                    "UPDATE devices SET floor_hash = ?, floor_seq = ? WHERE id = ?",
                    params![floor_hash, floor_seq, device],
                ))?;
                total += removed;
                devices.push((device, removed));
            }
            ix(self.conn.execute(
                "UPDATE purges SET approved_by = ?, approved_at = ?, rows_removed = ? WHERE id = ?",
                params![who.id, now, total, id],
            ))?;
            self.record(
                &who.id,
                "purge.carried_out",
                serde_json::json!({
                    "id": id, "cutoff": p.cutoff, "retention": p.retention,
                    "proposed_by": p.proposed_by, "by": who.name, "rows": total,
                    "devices": devices.iter()
                        .map(|(d, n)| serde_json::json!({ "device": d, "rows": n }))
                        .collect::<Vec<_>>(),
                }),
                now,
            )?;
            Ok(PurgeOutcome::CarriedOut {
                rows: total,
                devices,
            })
        })();
        match carried {
            Ok(outcome) => {
                ix(self.conn.execute_batch("COMMIT"))?;
                Ok(outcome)
            }
            Err(e) => {
                let _ = self.conn.execute_batch("ROLLBACK");
                Err(e)
            }
        }
    }
}

/// `now` minus a retention period, in whole seconds so it compares the way the stored
/// timestamps do. Only calendar periods of more than nothing: `PT12H` is a valid duration and
/// no retention period, and `P0D` would purge everything the moment it is signed.
pub fn cutoff_for(period: &str, now: &str) -> Result<String> {
    let bad = |why: String| Error::Config(format!("retention `{period}`: {why}"));
    cyberbrain_core::frontmatter::validate_retention(period).map_err(|w| bad(w.to_string()))?;
    if period.contains('T') {
        return Err(bad(
            "give it in days, weeks, months or years; hours are not a retention period".into(),
        ));
    }
    let span: jiff::Span = period.parse().map_err(|e| bad(format!("{e}")))?;
    if span.is_zero() {
        return Err(bad(
            "a retention period of nothing would purge everything".into()
        ));
    }
    let now: jiff::Timestamp = now
        .parse()
        .map_err(|e| Error::Config(format!("timestamp `{now}`: {e}")))?;
    let then = now
        .to_zoned(jiff::tz::TimeZone::UTC)
        .checked_sub(span)
        .map_err(|e| bad(format!("{e}")))?
        .timestamp();
    jiff::Timestamp::from_second(then.as_second())
        .map(|t| t.to_string())
        .map_err(|e| bad(format!("{e}")))
}

// ---------------------------------------------------------------------------------------
// Fleet invitations: one code that enrols many projects, until it runs out or expires.

/// A fleet invitation's code as the hub keeps it: a hash, a limit and an end.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct EnrolmentCode {
    pub id: String,
    pub label: String,
    pub max_uses: i64,
    pub uses: i64,
    pub expires_at: String,
    pub created_by: String,
    pub created_at: String,
    pub revoked_at: Option<String>,
}

/// Why a machine was not enrolled.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
#[serde(tag = "refused", content = "detail", rename_all = "kebab-case")]
pub enum EnrolRefusal {
    /// No such code, or one that was withdrawn. One answer for both, so a guessed code
    /// learns nothing from the reply.
    UnknownCode,
    Expired(String),
    UsedUp(i64),
    NotLicensed(String),
    NoSeat(usize),
    BadRequest(String),
}

impl std::fmt::Display for EnrolRefusal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EnrolRefusal::UnknownCode => write!(
                f,
                "the hub does not know this invitation's code, or it was withdrawn; ask for a new invitation"
            ),
            EnrolRefusal::Expired(at) => {
                write!(f, "this invitation expired at {at}; ask for a new one")
            }
            EnrolRefusal::UsedUp(n) => write!(
                f,
                "this invitation has enrolled {n} project(s), which is all it allows; ask for a new one"
            ),
            EnrolRefusal::NotLicensed(line) => write!(f, "{line}"),
            EnrolRefusal::NoSeat(seats) => write!(
                f,
                "the licence covers {seats} machine(s) and all of them are in use; revoke a machine \
                 that is gone, or extend the licence"
            ),
            EnrolRefusal::BadRequest(m) => write!(f, "{m}"),
        }
    }
}

/// The part of a device's name that says which project it is: the folder's name, as one word.
pub fn project_label(raw: &str) -> Option<String> {
    let joined = raw.split_whitespace().collect::<Vec<_>>().join("-");
    let label: String = joined
        .chars()
        .filter(|c| !c.is_control() && *c != '/' && *c != '\\')
        .take(64)
        .collect();
    (!label.is_empty()).then_some(label)
}

/// When an invitation stops working: `now` plus a period in days or weeks, at most ninety
/// days. A code is a credential for many machines, and one that outlives its rollout is one
/// that somebody finds in a mailbox next year.
pub fn invitation_expiry(period: &str, now: &str) -> Result<String> {
    let bad = |why: String| Error::Config(format!("--expires `{period}`: {why}"));
    cyberbrain_core::frontmatter::validate_retention(period).map_err(|w| bad(w.to_string()))?;
    if !period
        .chars()
        .skip(1)
        .all(|c| c.is_ascii_digit() || c == 'D' || c == 'W')
    {
        return Err(bad("give it in days or weeks, e.g. P14D".into()));
    }
    let span: jiff::Span = period.parse().map_err(|e| bad(format!("{e}")))?;
    let start: jiff::Timestamp = now
        .parse()
        .map_err(|e| Error::Config(format!("timestamp `{now}`: {e}")))?;
    let zoned = start.to_zoned(jiff::tz::TimeZone::UTC);
    let end = zoned
        .checked_add(span)
        .map_err(|e| bad(format!("{e}")))?
        .timestamp();
    let limit = zoned
        .checked_add(jiff::Span::new().days(90))
        .map_err(|e| bad(format!("{e}")))?
        .timestamp();
    if end <= start {
        return Err(bad(
            "an invitation that expires at once enrols nobody".into()
        ));
    }
    if end > limit {
        return Err(bad(
            "at most 90 days: a code for many machines should not outlive its rollout".into(),
        ));
    }
    jiff::Timestamp::from_second(end.as_second())
        .map(|t| t.to_string())
        .map_err(|e| bad(format!("{e}")))
}

impl HubStore {
    /// Issue a fleet invitation's code. Returns the code once; the record keeps its hash.
    pub fn create_enrolment_code(
        &self,
        label: &str,
        max_uses: i64,
        expires: &str,
        by: &str,
        now: &str,
    ) -> Result<(EnrolmentCode, String)> {
        if label.trim().is_empty() {
            return Err(Error::Config(
                "an invitation needs a label: it is how the log says which rollout a device came from"
                    .into(),
            ));
        }
        if !(1..=1000).contains(&max_uses) {
            return Err(Error::Config("--uses has to be between 1 and 1000".into()));
        }
        let expires_at = invitation_expiry(expires, now)?;
        let code = format!("cbe_{}", cyberbrain_core::NoteId::generate());
        let c = EnrolmentCode {
            id: format!("ec_{}", cyberbrain_core::NoteId::generate()),
            label: label.trim().to_string(),
            max_uses,
            uses: 0,
            expires_at,
            created_by: by.to_string(),
            created_at: now.to_string(),
            revoked_at: None,
        };
        ix(self.conn.execute(
            "INSERT INTO enrolment_codes
                 (id, code_hash, label, max_uses, expires_at, created_by, created_at)
             VALUES (?, ?, ?, ?, ?, ?, ?)",
            params![
                c.id,
                token_hash(&code),
                c.label,
                c.max_uses,
                c.expires_at,
                c.created_by,
                c.created_at
            ],
        ))?;
        self.record(
            by,
            "invitation.created",
            serde_json::json!({
                "id": c.id, "label": c.label, "max_uses": c.max_uses, "expires_at": c.expires_at,
            }),
            now,
        )?;
        Ok((c, code))
    }

    /// Every fleet invitation ever issued, oldest first.
    pub fn enrolment_codes(&self) -> Result<Vec<EnrolmentCode>> {
        let mut stmt = ix(self.conn.prepare(
            "SELECT id, label, max_uses, uses, expires_at, created_by, created_at, revoked_at
             FROM enrolment_codes ORDER BY created_at, id",
        ))?;
        let rows = ix(stmt.query_map([], |r| {
            Ok(EnrolmentCode {
                id: r.get(0)?,
                label: r.get(1)?,
                max_uses: r.get(2)?,
                uses: r.get(3)?,
                expires_at: r.get(4)?,
                created_by: r.get(5)?,
                created_at: r.get(6)?,
                revoked_at: r.get(7)?,
            })
        }))?;
        let mut out = Vec::new();
        for r in rows {
            out.push(ix(r)?);
        }
        Ok(out)
    }

    /// Withdraw an invitation. Devices it already enrolled stay; nobody further gets in.
    pub fn revoke_enrolment_code(&self, id: &str, by: &str, now: &str) -> Result<bool> {
        let n = ix(self.conn.execute(
            "UPDATE enrolment_codes SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL",
            params![now, id],
        ))?;
        if n > 0 {
            self.record(
                by,
                "invitation.revoked",
                serde_json::json!({ "id": id }),
                now,
            )?;
        }
        Ok(n > 0)
    }

    /// A machine asking for a device of its own with a fleet invitation's code.
    ///
    /// One transaction around the checks and the registration, so two machines using the last
    /// use of a code at the same moment cannot both get in. The order is the order of the
    /// questions: is this a code at all, is it still good, is there a licence, is there a seat
    /// for this machine. A second project on a machine that already has a seat takes none.
    pub fn enrol_with_code(
        &self,
        code: &str,
        machine: &str,
        project: &str,
        licence: &super::LicenceState,
        now: &str,
    ) -> Result<std::result::Result<(Device, String), EnrolRefusal>> {
        let Some(machine) = super::normalise_machine(machine) else {
            return Ok(Err(EnrolRefusal::BadRequest(
                "the machine name is empty or not one word".into(),
            )));
        };
        let Some(project) = project_label(project) else {
            return Ok(Err(EnrolRefusal::BadRequest(
                "the project name is empty".into(),
            )));
        };
        ix(self.conn.execute_batch("BEGIN IMMEDIATE"))?;
        let outcome = (|| -> Result<std::result::Result<(Device, String), EnrolRefusal>> {
            let row: Option<(String, String, i64, i64, String, Option<String>)> = ix(self
                .conn
                .query_row(
                    "SELECT id, label, max_uses, uses, expires_at, revoked_at
                     FROM enrolment_codes WHERE code_hash = ?",
                    params![token_hash(code)],
                    |r| {
                        Ok((
                            r.get(0)?,
                            r.get(1)?,
                            r.get(2)?,
                            r.get(3)?,
                            r.get(4)?,
                            r.get(5)?,
                        ))
                    },
                )
                .optional())?;
            let Some((id, label, max_uses, uses, expires_at, revoked_at)) = row else {
                return Ok(Err(EnrolRefusal::UnknownCode));
            };
            if revoked_at.is_some() {
                return Ok(Err(EnrolRefusal::UnknownCode));
            }
            if now >= expires_at.as_str() {
                return Ok(Err(EnrolRefusal::Expired(expires_at)));
            }
            if uses >= max_uses {
                return Ok(Err(EnrolRefusal::UsedUp(uses)));
            }
            let Some(seats) = licence.seats() else {
                return Ok(Err(EnrolRefusal::NotLicensed(licence.line())));
            };
            if self.needs_seat(Some(&machine))? && self.seats_in_use()? >= seats {
                return Ok(Err(EnrolRefusal::NoSeat(seats)));
            }
            let (mut device, token) = self.add_device(&format!("{machine}/{project}"), now)?;
            self.set_machine(&device.id, &machine)?;
            device.machine = Some(machine.clone());
            ix(self.conn.execute(
                "UPDATE enrolment_codes SET uses = uses + 1 WHERE id = ?",
                params![id],
            ))?;
            self.record(
                "enrolment",
                "device.enrolled",
                serde_json::json!({
                    "device": device.id, "machine": machine, "project": project,
                    "invitation": id, "label": label,
                }),
                now,
            )?;
            Ok(Ok((device, token)))
        })();
        match outcome {
            Ok(o) => {
                ix(self.conn.execute_batch("COMMIT"))?;
                Ok(o)
            }
            Err(e) => {
                let _ = self.conn.execute_batch("ROLLBACK");
                Err(e)
            }
        }
    }
}