faculties 0.21.0

An office suite for AI agents: kanban, wiki, files, messaging, and a Lissajous-backed viewer — all persisted in a TribleSpace pile.
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
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
//! Typed finite Message operations over one frozen Message/Relations observation.
//! Text is literal; sender selection and output routing belong to the caller.

use std::collections::BTreeSet;
use std::path::PathBuf;

use crate::clock;
use crate::collection_names::open_configured_acquiring;
#[cfg(test)]
use crate::collection_names::open_exact_in;
use crate::message::{self, IntervalValue};
use crate::relations::{self, IdentityComponents, TextHandle};
use crate::schemas::message::{local, DEFAULT_SCOPE_ID, KIND_MESSAGE_ID, KIND_READ_ID};
use crate::schemas::relations::{
    group as relation_group, DEFAULT_SCOPE_ID as DEFAULT_RELATIONS_SCOPE_ID,
};
use crate::storage::{self, FactArchive, FacultySnapshot, FacultyStore, Storage};
use anyhow::{bail, Context, Result};
use ed25519_dalek::SigningKey;
use itertools::Itertools;
use triblespace::core::blob::encodings::simplearchive::SimpleArchive;
use triblespace::core::blob::encodings::succinctarchive::{
    Rank9AcceleratedSuccinctArchiveBlob, SuccinctArchiveBlob,
};
use triblespace::core::collection::{Collection, CollectionStoreExt};
use triblespace::core::metadata;
use triblespace::core::query::intersectionconstraint::and;
use triblespace::core::query::sortedsliceconstraint::SortedSlice;
use triblespace::core::query::temp;
use triblespace::core::query::TriblePattern;
use triblespace::core::repo::async_store::AsyncBlobStoreAcquire;
use triblespace::macros::{exists, find, pattern};
use triblespace::prelude::*;

/// A configured Message capability. Every call observes one frozen
/// Message/Relations view through its storage handle. Authorized operations
/// maintain both chains before selecting that view and carry newly published
/// Message facts before returning. A principal without derived WRITE still
/// reads the resident targets and may publish when it has source WRITE; no
/// operation manufactures a grant or mixes raw facts into an indexed view.
/// No transport, sender environment, or text-file convention is consulted.
#[derive(Clone, Debug)]
pub struct Message {
    storage: Storage,
}

#[derive(Clone, Copy, Debug)]
pub struct SendOptions<'a> {
    pub from: &'a str,
    pub to: &'a str,
    /// Literal text, including strings beginning with `@`.
    pub text: &'a str,
}

impl SendOptions<'_> {
    pub fn validate(&self) -> Result<()> {
        anyhow::ensure!(!self.from.trim().is_empty(), "message sender is empty");
        anyhow::ensure!(!self.to.trim().is_empty(), "message recipient is empty");
        anyhow::ensure!(!self.text.trim().is_empty(), "message text is empty");
        Ok(())
    }
}

#[derive(Clone, Copy, Debug)]
pub struct ListOptions<'a> {
    pub reader: &'a str,
    pub unread: bool,
    pub limit: usize,
}

impl<'a> ListOptions<'a> {
    pub fn new(reader: &'a str) -> Self {
        Self {
            reader,
            unread: false,
            limit: 20,
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub struct AckAllOptions<'a> {
    pub by: &'a str,
    pub from: Option<&'a str>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SentMessage {
    pub id: Id,
    pub from: Id,
    /// The exact recipient, including a group's witnessed delivery snapshot.
    pub recipient: message::Recipient,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MessageStatus {
    Unread,
    Read,
    Sent,
    ReadByRecipient,
}

/// A text blob as a reader can report it.
///
/// Two of the three ways a text can fail to show are facts about the DATA, and
/// a reader reports them rather than refusing: the bytes have not arrived, or
/// they are not text. The envelope is still a valid, signed message -- who sent
/// it, to whom, when -- and it can still be read and acknowledged. Refusing the
/// whole inbox because one body is missing turned a single record that synced
/// ahead of its blob into a reader that could show nothing at all.
///
/// The third way is NOT a variant: the store itself failing to acquire says
/// nothing about the message and everything about the reader, so it stays an
/// error.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum MessageText {
    /// The text, decoded.
    Text(String),
    /// Not resident, and acquisition found no copy. It may still arrive.
    Unavailable(TextHandle),
    /// Resident, but not UTF-8.
    Undecodable(TextHandle),
}

/// One envelope as this reader saw it. Every field is a column of the query
/// that selected it: nothing is loaded before a question is asked, and the
/// exact sender and recipient anchors stay as written even when delivery and
/// receipts use settled identity equivalence.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MessageObservation {
    pub id: Id,
    pub from: Id,
    pub to: Id,
    pub created_at: IntervalValue,
    pub body: MessageText,
    pub from_label: String,
    pub to_label: String,
    pub incoming: bool,
    pub outgoing: bool,
    pub status: MessageStatus,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MessageList {
    pub reader: Id,
    pub observed_at: IntervalValue,
    pub entries: Vec<MessageObservation>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Acknowledgement {
    pub message: Id,
    pub reader: Id,
    pub already_read: bool,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AcknowledgedMessages {
    pub reader: Id,
    /// Envelopes acknowledged by this operation, empty for an idempotent replay.
    pub message_ids: Vec<Id>,
}

impl Message {
    pub fn new(pile: PathBuf, key: Option<PathBuf>) -> Self {
        Self::with_storage(Storage::new(pile, key))
    }

    pub fn with_storage(storage: Storage) -> Self {
        Self { storage }
    }

    pub fn send(&self, options: &SendOptions<'_>) -> Result<SentMessage> {
        options.validate()?;
        with_storage(self, |storage, runtime| {
            runtime.block_on(send(storage, options))
        })
    }

    pub fn list(&self, options: &ListOptions<'_>) -> Result<MessageList> {
        with_storage(self, |storage, runtime| {
            runtime.block_on(list(storage, options))
        })
    }

    pub fn ack(&self, id: &str, by: &str) -> Result<Acknowledgement> {
        with_storage(self, |storage, runtime| {
            runtime.block_on(ack(storage, id, by))
        })
    }

    pub fn ack_all(&self, options: &AckAllOptions<'_>) -> Result<AcknowledgedMessages> {
        with_storage(self, |storage, runtime| {
            runtime.block_on(ack_all(storage, options))
        })
    }
}

/// The facts one operation queries: its frozen Rank9 view, for reads and
/// edits alike. A write ensures its derived views after publication; reads
/// attach what the maintenance worker carried and never maintain, so a later
/// raw COMMIT is never mixed into these facts.
type MessageFacts = FactArchive;

struct MessageStorage<'a> {
    pile: &'a mut FacultyStore,
    signer: &'a SigningKey,
    collection: Collection<SimpleArchive>,
    reader: &'a FacultySnapshot,
    messages: &'a MessageFacts,
    relations: &'a MessageFacts,
}

impl MessageStorage<'_> {
    /// Publish at most one locally constructed typed fragment.
    async fn update<T>(
        &mut self,
        description: &'static str,
        operation: impl FnOnce(&MessageFacts, &MessageFacts) -> Result<(Option<Fragment>, T)>,
    ) -> Result<T> {
        let (fragment, value) = operation(self.messages, self.relations)?;
        if let Some(mut fragment) = fragment {
            let snapshot = self
                .pile
                .snapshot()
                .context("freeze Message publication authority")?;
            let collection = self.collection;
            let subject = self.signer.verifying_key();
            let runtime = tokio::runtime::Handle::current();
            let admitted = tokio::task::spawn_blocking(move || {
                let reader = storage::AcquiringReader::with_handle(snapshot, runtime);
                collection
                    .writer_is_admitted_acquiring(&reader, subject)
                    .context("check Message source WRITE admission")
            })
            .await
            .context("join Message WRITE admission")??;
            anyhow::ensure!(
                admitted,
                "publishing a Message fragment requires source collection WRITE"
            );
            fragment.describe_with(entity! { metadata::description: description });
            self.pile
                .commit(self.collection, self.signer, fragment)
                .context("commit authored Message fragment")?;
            drop(
                crate::storage::ensure_downstream(self.pile, self.collection, self.signer)
                    .await
                    .context(
                        "Message fragment was committed, but ensuring its derived views failed",
                    )?,
            );
        }
        Ok(value)
    }
}

pub(super) fn interval_key(interval: IntervalValue) -> i128 {
    let (lower, _): (i128, i128) = interval
        .try_from_inline()
        .expect("stored Message timestamp is a valid interval");
    lower
}

fn fmt_id(id: Id) -> String {
    format!("{id:x}")
}

/// The columns of one envelope these operations read. Nothing else is
/// selected, so a record carrying fields this reader does not model still
/// answers, and one that is missing a field it does model simply does not.
/// The columns of one envelope these operations read, including the exact
/// group snapshot that delivered it to this reader — `None` for a direct
/// send. The delivering snapshot is a column of the join that selected the
/// envelope, not a second lookup: an envelope naming two snapshots is
/// delivered by the one that names the reader, and only that one may name
/// the audience a listing shows.
pub(crate) type Envelope = (Id, Id, Id, message::TextHandle, IntervalValue, Option<Id>);

pub(crate) fn envelope_id(envelope: &Envelope) -> Id {
    envelope.0
}

/// Every anchor Relations has settled as this same person, ordered so a query
/// can join on it directly. An unobserved or contradictory component still
/// identifies its own anchor: settlement may widen who a reader is, but a
/// stranger's unsettled verdict never erases them.
pub(crate) fn settled_identity(identities: &IdentityComponents, person: Id) -> Vec<Id> {
    identities
        .component(person)
        .map(|component| component.into_iter().collect())
        .unwrap_or_else(|_| vec![person])
}

/// Envelopes delivered to one settled identity: addressed to it directly, or
/// carried by the Relations group snapshot frozen at send time that names it as
/// a member. Each arm is one join — the second across both views, on the
/// snapshot — and a sender's own envelope is outgoing, never inbox.
pub(crate) fn inbox<M, R>(message_facts: &M, relation_facts: &R, mine: &[Id]) -> Vec<Envelope>
where
    M: TriblePattern,
    R: TriblePattern,
{
    let direct = find!(
        (id: Id, from: Id, to: Id, body: message::TextHandle, created_at: IntervalValue),
        and!(
            SortedSlice::new_unchecked(mine).has(to),
            pattern!(message_facts, [{ ?id @
                metadata::tag: &KIND_MESSAGE_ID,
                local::from: ?from,
                local::to: ?to,
                local::body: ?body,
                metadata::created_at: ?created_at,
            }])
        )
    )
    .map(|(id, from, to, body, created_at)| (id, from, to, body, created_at, None));
    let delivered = find!(
        (
            id: Id,
            from: Id,
            to: Id,
            body: message::TextHandle,
            created_at: IntervalValue,
            snapshot: Id
        ),
        temp!(
            (member),
            and!(
                SortedSlice::new_unchecked(mine).has(member),
                pattern!(message_facts, [{ ?id @
                    metadata::tag: &KIND_MESSAGE_ID,
                    local::from: ?from,
                    local::to: ?to,
                    local::body: ?body,
                    metadata::created_at: ?created_at,
                    local::group_snapshot: ?snapshot,
                }]),
                pattern!(relation_facts, [{ ?snapshot @ relation_group::member: ?member }])
            )
        )
    )
    .map(|(id, from, to, body, created_at, snapshot)| {
        (id, from, to, body, created_at, Some(snapshot))
    });
    // Sending is a property of the envelope, not of one witness of it: if any
    // witness names this identity as the sender the envelope is outgoing, so
    // inbox and outbox stay disjoint by id however many senders are asserted.
    let sent: BTreeSet<Id> = outbox(message_facts, mine)
        .iter()
        .map(envelope_id)
        .collect();
    direct
        .chain(delivered)
        .filter(|envelope| !sent.contains(&envelope_id(envelope)))
        .collect()
}

/// Envelopes one settled identity sent.
pub(crate) fn outbox<M>(message_facts: &M, mine: &[Id]) -> Vec<Envelope>
where
    M: TriblePattern,
{
    find!(
        (id: Id, from: Id, to: Id, body: message::TextHandle, created_at: IntervalValue),
        and!(
            SortedSlice::new_unchecked(mine).has(from),
            pattern!(message_facts, [{ ?id @
                metadata::tag: &KIND_MESSAGE_ID,
                local::from: ?from,
                local::to: ?to,
                local::body: ?body,
                metadata::created_at: ?created_at,
            }])
        )
    )
    .map(|(id, from, to, body, created_at)| {
        // A sender's own envelope was not delivered *to* them, so its audience
        // is whatever snapshot it names.
        let snapshot = delivery_snapshot(message_facts, id);
        (id, from, to, body, created_at, snapshot)
    })
    .collect()
}

/// The exact audience an envelope was delivered to, when it was a group send.
fn delivery_snapshot<M>(message_facts: &M, message: Id) -> Option<Id>
where
    M: TriblePattern,
{
    find!(
        snapshot: Id,
        pattern!(message_facts, [{ message @ local::group_snapshot: ?snapshot }])
    )
    .next()
}

/// The envelopes among these witnesses that a sender selector accepts, reduced
/// to one id each. Witnesses are filtered *before* the reduction: an envelope
/// asserting two senders is selected when any of its witnesses matches, and
/// reducing first would let an unmatched witness hide it.
pub(crate) fn envelopes_from(envelopes: Vec<Envelope>, senders: Option<&[Id]>) -> Vec<Id> {
    envelopes
        .into_iter()
        .filter(|(_, sender, ..)| {
            senders.map_or(true, |senders| senders.binary_search(sender).is_ok())
        })
        .map(|envelope| envelope_id(&envelope))
        .unique()
        .collect()
}

/// Whether any canonical read marker about this envelope belongs to one of
/// these settled anchors. The first witness answers.
pub(crate) fn read_by<M>(message_facts: &M, message: Id, readers: &[Id]) -> bool
where
    M: TriblePattern,
{
    exists!(
        (reader: Id),
        and!(
            SortedSlice::new_unchecked(readers).has(reader),
            pattern!(message_facts, [{ _?marker @
                metadata::tag: &KIND_READ_ID,
                local::about_message: &message,
                local::reader: ?reader,
            }])
        )
    )
}

/// Acquire a text blob and say what came back. Only an acquisition failure is
/// an error; see [`MessageText`] for why the other two are values.
async fn observe_text<S>(store: &mut S, handle: TextHandle) -> Result<MessageText>
where
    S: AsyncBlobStoreAcquire,
{
    let Some(bytes) = store
        .acquire(handle.transmute())
        .await
        .with_context(|| format!("acquire Message text blake3:{}", hex::encode(handle.raw)))?
    else {
        return Ok(MessageText::Unavailable(handle));
    };
    Ok(match std::str::from_utf8(&bytes) {
        Ok(text) => MessageText::Text(text.to_owned()),
        Err(_) => MessageText::Undecodable(handle),
    })
}

async fn person_label<S, P>(store: &mut S, facts: &P, person: Id) -> Result<String>
where
    S: AsyncBlobStoreAcquire,
    P: TriblePattern,
{
    if matches!(
        relations::profile_head(facts, person)?,
        relations::Head::Missing
    ) {
        return Ok(format!("{person:x} [profile unavailable]"));
    }
    let profile = relations::current_profile(facts, person)?;
    let Some(bytes) = store
        .acquire(profile.label.transmute())
        .await
        .context("acquire Message person label")?
    else {
        return Ok(format!("{person:x} [label unavailable]"));
    };
    // The same convention as absence, one line up: a label that is not text is
    // a fact about that label, not a reason to show nobody's messages.
    Ok(match std::str::from_utf8(&bytes) {
        Ok(label) => label.to_owned(),
        Err(_) => format!("{person:x} [label undecodable]"),
    })
}

async fn recipient_label<S, P>(
    store: &mut S,
    facts: &P,
    message: Id,
    to: Id,
    delivered_through: Option<Id>,
) -> Result<String>
where
    S: AsyncBlobStoreAcquire,
    P: TriblePattern,
{
    match delivered_through {
        None => person_label(store, facts, to).await,
        Some(snapshot) => {
            let snapshot = relations::group_snapshot(facts, snapshot)?;
            let name = observe_text(store, snapshot.name).await.with_context(|| {
                format!(
                    "read name of group snapshot {:x} for Message {:x}",
                    snapshot.id, message
                )
            })?;
            // Degrades the way `person_label` always has.
            Ok(match name {
                MessageText::Text(name) => name,
                MessageText::Unavailable(_) => {
                    format!("{:x} [group name unavailable]", snapshot.id)
                }
                MessageText::Undecodable(_) => {
                    format!("{:x} [group name undecodable]", snapshot.id)
                }
            })
        }
    }
}

async fn send(storage: &mut MessageStorage<'_>, options: &SendOptions<'_>) -> Result<SentMessage> {
    let relation_facts = storage.relations;
    let (from_id, recipient) = storage::read(storage.pile, storage.reader, |reader| {
        let from_id = message::resolve_person(reader, relation_facts, options.from)?
            .require_unique("active person", options.from)?;
        let recipient = message::resolve_recipient(reader, relation_facts, options.to)?
            .require_unique(options.to)?;
        Ok((from_id, recipient))
    })
    .await?;
    storage
        .update("local message", |_, _| {
            let (fragment, id) =
                message::message_fragment(from_id, &recipient, options.text, clock::point_now()?);
            Ok((
                Some(fragment),
                SentMessage {
                    id,
                    from: from_id,
                    recipient,
                },
            ))
        })
        .await
}

async fn ack(storage: &mut MessageStorage<'_>, id: &str, by: &str) -> Result<Acknowledgement> {
    let relation_facts = storage.relations;
    let reader_id = storage::read(storage.pile, storage.reader, |reader| {
        message::resolve_person(reader, relation_facts, by)?.require_unique("active person", by)
    })
    .await?;
    storage
        .update("local message read", |message_facts, relation_facts| {
            let identities = IdentityComponents::from_facts(relation_facts)?;
            let mine = settled_identity(&identities, reader_id);
            // The prefix resolves against exactly what this reader may
            // acknowledge, so an id outside that inbox never names a message.
            let delivered = inbox(message_facts, relation_facts, &mine);
            let message_id = crate::resolve_id_prefix(id, delivered.iter().map(envelope_id))?;
            if !delivered
                .iter()
                .any(|envelope| envelope_id(envelope) == message_id)
            {
                bail!(
                    "message {} is not in {}'s inbox",
                    fmt_id(message_id),
                    fmt_id(reader_id)
                );
            }
            let already_read = read_by(message_facts, message_id, &mine);
            let fragment = if already_read {
                None
            } else {
                Some(message::read_fragment(message_id, reader_id, Some(clock::point_now()?)).0)
            };
            Ok((
                fragment,
                Acknowledgement {
                    message: message_id,
                    reader: reader_id,
                    already_read,
                },
            ))
        })
        .await
}

async fn ack_all(
    storage: &mut MessageStorage<'_>,
    options: &AckAllOptions<'_>,
) -> Result<AcknowledgedMessages> {
    let relation_facts = storage.relations;
    let (reader_id, from) = storage::read(storage.pile, storage.reader, |reader| {
        let reader_id = message::resolve_person(reader, relation_facts, options.by)?
            .require_unique("active person", options.by)?;
        let from = options
            .from
            .map(|selector| {
                message::resolve_person(reader, relation_facts, selector)?
                    .require_unique("active person", selector)
            })
            .transpose()?;
        Ok((reader_id, from))
    })
    .await?;
    storage
        .update(
            "local messages bulk read",
            |message_facts, relation_facts| {
                let identities = IdentityComponents::from_facts(relation_facts)?;
                let mine = settled_identity(&identities, reader_id);
                let senders = from.map(|sender| settled_identity(&identities, sender));
                let observed_at = clock::point_now()?;
                let mut fragment = Fragment::empty();
                let mut message_ids = Vec::new();
                for id in envelopes_from(
                    inbox(message_facts, relation_facts, &mine),
                    senders.as_deref(),
                ) {
                    if read_by(message_facts, id, &mine) {
                        continue;
                    }
                    fragment += message::read_fragment(id, reader_id, Some(observed_at)).0;
                    message_ids.push(id);
                }
                Ok((
                    (!message_ids.is_empty()).then_some(fragment),
                    AcknowledgedMessages {
                        reader: reader_id,
                        message_ids,
                    },
                ))
            },
        )
        .await
}

async fn list(storage: &mut MessageStorage<'_>, options: &ListOptions<'_>) -> Result<MessageList> {
    let message_facts = storage.messages;
    let relation_facts = storage.relations;
    let reader_id = storage::read(storage.pile, storage.reader, |reader| {
        message::resolve_person(reader, relation_facts, options.reader)?
            .require_unique("active person", options.reader)
    })
    .await?;
    let identities = IdentityComponents::from_facts(relation_facts)?;
    let mine = settled_identity(&identities, reader_id);

    // Newest first, one entry per envelope: both views answer with a bag, so a
    // repeated field or a person settled across two anchors is one more witness
    // of the same envelope rather than another message. Inbox and outbox are
    // disjoint, because an envelope this reader sent is never delivered to it.
    let candidates: Vec<(bool, Envelope)> = inbox(message_facts, relation_facts, &mine)
        .into_iter()
        .map(|envelope| (true, envelope))
        .chain(
            outbox(message_facts, &mine)
                .into_iter()
                .map(|envelope| (false, envelope)),
        )
        .sorted_by(|(_, left), (_, right)| {
            interval_key(right.4)
                .cmp(&interval_key(left.4))
                .then_with(|| left.0.cmp(&right.0))
        })
        .unique_by(|(_, envelope)| envelope_id(envelope))
        .collect();

    let observed_at = clock::point_now()?;
    let mut entries = Vec::new();
    for (incoming, (id, from, to, body, created_at, delivered_through)) in candidates {
        if entries.len() >= options.limit {
            break;
        }
        let read = read_by(message_facts, id, &mine);
        if options.unread && !(incoming && !read) {
            continue;
        }
        let from_label = person_label(storage.pile, relation_facts, from).await?;
        let to_label =
            recipient_label(storage.pile, relation_facts, id, to, delivered_through).await?;
        let status = if incoming {
            if read {
                MessageStatus::Read
            } else {
                MessageStatus::Unread
            }
        } else if delivered_through.is_none()
            && read_by(message_facts, id, &settled_identity(&identities, to))
        {
            MessageStatus::ReadByRecipient
        } else {
            MessageStatus::Sent
        };
        let body = observe_text(storage.pile, body)
            .await
            .with_context(|| format!("read body of Message {id:x}"))?;
        entries.push(MessageObservation {
            id,
            from,
            to,
            created_at,
            body,
            from_label,
            to_label,
            incoming,
            outgoing: !incoming,
            status,
        });
    }
    Ok(MessageList {
        reader: reader_id,
        observed_at,
        entries,
    })
}

fn with_storage<T>(
    capability: &Message,
    operation: impl FnOnce(&mut MessageStorage<'_>, &tokio::runtime::Runtime) -> Result<T>,
) -> Result<T> {
    capability.storage.with_store(|pile, signer, runtime| {
        let relations_source = open_configured_acquiring(
            pile,
            DEFAULT_RELATIONS_SCOPE_ID,
            signer.verifying_key(),
            runtime,
        )?;
        let message_source =
            open_configured_acquiring(pile, DEFAULT_SCOPE_ID, signer.verifying_key(), runtime)?;
        let (reader, relation_facts, message_facts) = runtime.block_on(message_views(
            pile,
            signer,
            relations_source,
            message_source,
        ))?;
        let mut storage = MessageStorage {
            pile,
            signer,
            collection: message_source,
            reader: &reader,
            messages: &message_facts,
            relations: &relation_facts,
        };
        operation(&mut storage, runtime)
    })
}

async fn message_views(
    pile: &mut FacultyStore,
    _signer: &SigningKey,
    relations_source: Collection<SimpleArchive>,
    message_source: Collection<SimpleArchive>,
) -> Result<(FacultySnapshot, MessageFacts, MessageFacts)> {
    let trace = std::env::var_os("MESSAGE_RESIDUAL_TRACE").is_some();
    let started = std::time::Instant::now();
    // Reads attach what the maintenance worker carried and never maintain:
    // each chain is only registered here so its Rank9 handle can be attached.
    let relations_rank9 = register_fact_chain(pile, relations_source, "Relations")?;
    let message_rank9 = register_fact_chain(pile, message_source, "Message")?;
    let registered_at = started.elapsed();
    // Both query views retain their selected support. Later selected-text
    // acquisition may add bytes, but never replaces these frozen facts.
    let reader = pile.snapshot().context("freeze Message observation")?;
    let acquiring_snapshot = reader.clone();
    let runtime = tokio::runtime::Handle::current();
    let (relation_facts, message_facts) = tokio::task::spawn_blocking(move || {
        // Select only once, after resolving definitions against this frozen
        // proof/record evidence. No cache fill advances the observation.
        let acquiring = storage::AcquiringReader::with_handle(acquiring_snapshot, runtime);
        let relations = storage::acquire_facts(&acquiring, relations_rank9)
            .context("read Relations Rank9 projection")?;
        let messages = storage::acquire_facts(&acquiring, message_rank9)
            .context("read Message Rank9 projection")?;
        Ok::<_, anyhow::Error>((relations, messages))
    })
    .await
    .context("join Message observation acquisition")??;
    let attached_at = started.elapsed();
    if trace {
        eprintln!(
            "views: registered in {:.2?}, attached in {:.2?}",
            registered_at,
            attached_at - registered_at
        );
    }
    Ok((reader, relation_facts, message_facts))
}

/// Register the Succinct and Rank9 pair over `source` and return the Rank9
/// handle a reader attaches. Registration only: nothing is maintained here.
fn register_fact_chain(
    pile: &mut FacultyStore,
    source: Collection<SimpleArchive>,
    name: &'static str,
) -> Result<Collection<Rank9AcceleratedSuccinctArchiveBlob>> {
    let succinct = pile
        .attach::<SuccinctArchiveBlob>(source, ())
        .with_context(|| format!("register {name} Succinct collection"))?;
    let rank9 = pile
        .attach::<Rank9AcceleratedSuccinctArchiveBlob>(source, succinct)
        .with_context(|| format!("register {name} Rank9 collection"))?;
    Ok(rank9)
}

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

    use std::collections::BTreeSet;
    use std::future::{ready, Future};
    use std::io;

    use anybytes::Bytes;
    use hifitime::Epoch;
    use triblespace::core::blob::encodings::UnknownBlob;
    use triblespace::core::blob::MemoryBlobStoreSnapshot;
    use triblespace::core::collection::{
        empty_metadata_handle, grant_collection_write, CollectionCommit, CollectionRead,
        CollectionRecord, CollectionRecordSelector,
    };
    use triblespace::core::repo::pile::ReadError;
    use triblespace::core::repo::StorageClose;

    /// A real resident-only pile with a deterministic remote blob fixture.
    struct AcquiringPile {
        pile: Pile,
        remote: MemoryBlobStoreSnapshot,
        requested: Vec<Inline<inlineencodings::Handle<UnknownBlob>>>,
        failure: Option<io::ErrorKind>,
        arriving: Option<(Collection<SimpleArchive>, SigningKey, Fragment)>,
        _file: tempfile::NamedTempFile,
    }

    impl AcquiringPile {
        fn new(remote: MemoryBlobStore) -> Self {
            Self::open(remote, None)
        }

        /// A store whose MAPs are signed by `host`, so its attachments are
        /// believed.
        fn hosted(remote: MemoryBlobStore, host: ed25519_dalek::VerifyingKey) -> Self {
            Self::open(remote, Some(host))
        }

        fn open(mut remote: MemoryBlobStore, host: Option<ed25519_dalek::VerifyingKey>) -> Self {
            let file = tempfile::NamedTempFile::new().unwrap();
            let pile = match host {
                Some(host) => Pile::open_as(file.path(), host),
                None => Pile::open(file.path()),
            };
            Self {
                pile: pile.unwrap(),
                remote: remote.snapshot().unwrap(),
                requested: Vec::new(),
                failure: None,
                arriving: None,
                _file: file,
            }
        }
    }

    impl SnapshotSource for AcquiringPile {
        type Snapshot = PileSnapshot;
        type SnapshotError = ReadError;

        fn snapshot(&mut self) -> Result<PileSnapshot, ReadError> {
            self.pile.snapshot()
        }
    }

    impl AsyncBlobStoreAcquire for AcquiringPile {
        type AcquireError = io::Error;

        fn acquire(
            &mut self,
            handle: Inline<inlineencodings::Handle<UnknownBlob>>,
        ) -> impl Future<Output = Result<Option<Bytes>, io::Error>> + Send {
            let resident = self.pile.snapshot().unwrap();
            if resident.contains_blob(handle).unwrap() {
                return ready(Ok(Some(resident.get(handle).unwrap())));
            }
            self.requested.push(handle);
            if let Some(kind) = self.failure {
                return ready(Err(io::Error::new(
                    kind,
                    "injected Message acquisition failure",
                )));
            }
            if let Some((collection, signer, fragment)) = self.arriving.take() {
                self.pile.commit(collection, &signer, fragment).unwrap();
            }
            if !self.remote.contains_blob(handle).unwrap() {
                return ready(Ok(None));
            }
            let bytes: Bytes = self.remote.get(handle).unwrap();
            let cached: Inline<inlineencodings::Handle<UnknownBlob>> =
                self.pile.put(bytes.clone()).unwrap();
            assert_eq!(cached, handle);
            ready(Ok(Some(bytes)))
        }
    }

    fn test_id(byte: u8) -> Id {
        Id::new([byte; 16]).unwrap()
    }

    /// Every envelope this view answers with, asked the way the operations ask:
    /// a typed pattern over the attributes, never a catalog.
    fn visible<M>(message_facts: &M) -> BTreeSet<Id>
    where
        M: TriblePattern,
    {
        find!(
            id: Id,
            pattern!(message_facts, [{ ?id @ metadata::tag: &KIND_MESSAGE_ID }])
        )
        .collect()
    }

    /// Fixture preparation by a principal admitted to both derived targets.
    fn carry(
        pile: &mut FacultyStore,
        runtime: &tokio::runtime::Runtime,
        source: Collection<SimpleArchive>,
        signer: &SigningKey,
    ) {
        let succinct = pile.attach::<SuccinctArchiveBlob>(source, ()).unwrap();
        let rank9 = pile
            .attach::<Rank9AcceleratedSuccinctArchiveBlob>(source, succinct)
            .unwrap();
        drop(
            runtime
                .block_on(pile.maintain_attached(succinct, signer))
                .unwrap(),
        );
        drop(
            runtime
                .block_on(pile.maintain_attached(rank9, signer))
                .unwrap(),
        );
    }

    #[test]
    fn non_writer_lists_resident_messages_but_cannot_publish() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let runtime = storage::runtime().unwrap();
        let owner = SigningKey::from_bytes(&[91; 32]);
        let mut pile = storage::open_store_as(file.path(), owner.verifying_key()).unwrap();
        let observer = SigningKey::from_bytes(&[92; 32]);
        let relations_source = crate::collection_names::open(
            &mut pile,
            DEFAULT_RELATIONS_SCOPE_ID,
            owner.verifying_key(),
        )
        .unwrap();
        let message_source =
            crate::collection_names::open(&mut pile, DEFAULT_SCOPE_ID, owner.verifying_key())
                .unwrap();
        let mut selectors = BTreeSet::new();
        for source in [relations_source, message_source] {
            let succinct = pile.attach::<SuccinctArchiveBlob>(source, ()).unwrap();
            let rank9 = pile
                .attach::<Rank9AcceleratedSuccinctArchiveBlob>(source, succinct)
                .unwrap();
            for handle in [source.handle(), succinct.handle(), rank9.handle()] {
                selectors.insert(CollectionRecordSelector::Collection(handle));
            }
        }
        let sender = test_id(61);
        let recipient = test_id(62);
        let mut people = relations::person_fragment(
            sender,
            relations::ProfileInput {
                label: "sender".to_owned(),
                ..Default::default()
            },
        )
        .unwrap()
        .0;
        people += relations::person_fragment(
            recipient,
            relations::ProfileInput {
                label: "reader".to_owned(),
                ..Default::default()
            },
        )
        .unwrap()
        .0;
        pile.commit(relations_source, &owner, people).unwrap();
        let (first, first_id) = message::message_fragment(
            sender,
            &message::Recipient::Person(recipient),
            "first message",
            clock::point_now().unwrap(),
        );
        pile.commit(message_source, &owner, first).unwrap();
        // Prepare the resident views before the non-writer observes them.
        carry(&mut pile, &runtime, relations_source, &owner);
        carry(&mut pile, &runtime, message_source, &owner);

        let (second, second_id) = message::message_fragment(
            sender,
            &message::Recipient::Person(recipient),
            "second message",
            clock::point_now().unwrap(),
        );
        let later_person = test_id(63);
        let later = relations::person_fragment(
            later_person,
            relations::ProfileInput {
                label: "later person".to_owned(),
                ..Default::default()
            },
        )
        .unwrap()
        .0;
        let options = ListOptions::new("reader");
        for growth in [None, Some((later, second))] {
            let grown = growth.is_some();
            if let Some((person, message)) = growth {
                pile.commit(relations_source, &owner, person).unwrap();
                pile.commit(message_source, &owner, message).unwrap();
            }
            let before = pile.snapshot().unwrap().select_records(&selectors).unwrap();
            // The observer attaches nothing; it reads the attached views and
            // the newer commits from their own bytes, and publishes nothing.
            let (snapshot, relation_facts, message_facts) = runtime
                .block_on(message_views(
                    &mut pile,
                    &observer,
                    relations_source,
                    message_source,
                ))
                .unwrap();
            assert_eq!(
                relations::person_anchors(&relation_facts).contains(&later_person),
                grown
            );
            let mut input = MessageStorage {
                pile: &mut pile,
                signer: &observer,
                collection: message_source,
                reader: &snapshot,
                messages: &message_facts,
                relations: &relation_facts,
            };
            let result = runtime.block_on(list(&mut input, &options)).unwrap();
            assert_eq!(result.reader, recipient);
            assert_eq!(
                result
                    .entries
                    .iter()
                    .map(|entry| entry.id)
                    .collect::<BTreeSet<_>>(),
                if grown {
                    BTreeSet::from([first_id, second_id])
                } else {
                    BTreeSet::from([first_id])
                }
            );
            let first = result
                .entries
                .iter()
                .find(|entry| entry.id == first_id)
                .unwrap();
            assert_eq!(first.body, MessageText::Text("first message".to_owned()));
            assert_eq!(first.status, MessageStatus::Unread);
            assert_eq!(
                pile.snapshot().unwrap().select_records(&selectors).unwrap(),
                before
            );
        }

        let before = pile.snapshot().unwrap().select_records(&selectors).unwrap();
        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &observer,
                relations_source,
                message_source,
            ))
            .unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &observer,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let error = runtime
            .block_on(send(
                &mut input,
                &SendOptions {
                    from: "sender",
                    to: "reader",
                    text: "unauthorized message",
                },
            ))
            .unwrap_err();
        assert!(format!("{error:#}").contains("requires source collection WRITE"));
        let error = runtime
            .block_on(ack(&mut input, &fmt_id(first_id), "reader"))
            .unwrap_err();
        assert!(format!("{error:#}").contains("requires source collection WRITE"));
        runtime
            .block_on(input.update("no-op", |_, _| Ok((None, ()))))
            .unwrap();
        assert_eq!(
            pile.snapshot().unwrap().select_records(&selectors).unwrap(),
            before
        );

        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let acknowledgement = runtime
            .block_on(ack(&mut input, &fmt_id(first_id), "reader"))
            .unwrap();
        assert!(!acknowledgement.already_read);
        // The owner carries its receipt before returning; acknowledging the
        // same observed receipt again is a no-op that publishes nothing.
        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let before_noop = pile.snapshot().unwrap().select_records(&selectors).unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        assert!(
            runtime
                .block_on(ack(&mut input, &fmt_id(first_id), "reader"))
                .unwrap()
                .already_read
        );
        assert_eq!(
            pile.snapshot().unwrap().select_records(&selectors).unwrap(),
            before_noop
        );
        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let result = runtime.block_on(list(&mut input, &options)).unwrap();
        assert_eq!(result.entries.len(), 2);
        assert_eq!(
            result
                .entries
                .iter()
                .find(|entry| entry.id == first_id)
                .unwrap()
                .status,
            MessageStatus::Read
        );
        assert_eq!(
            result
                .entries
                .iter()
                .find(|entry| entry.id == second_id)
                .unwrap()
                .status,
            MessageStatus::Unread
        );
        pile.close().unwrap();
    }

    /// A writer with source WRITE but none on the views can still append:
    /// its send and ack are committed. A write derives only its own key's
    /// commits, and this key may not write the views, so no reader sees
    /// either yet and each command says so instead of succeeding silently.
    /// The owner's next maintenance pass derives both, without any grant,
    /// and every reader sees them.
    #[test]
    fn source_only_writer_sends_and_acks_readably_before_maintenance_attaches_them() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let runtime = storage::runtime().unwrap();
        let owner = SigningKey::from_bytes(&[95; 32]);
        let mut pile = storage::open_store_as(file.path(), owner.verifying_key()).unwrap();
        let sender = SigningKey::from_bytes(&[96; 32]);
        let relations_source = crate::collection_names::open(
            &mut pile,
            DEFAULT_RELATIONS_SCOPE_ID,
            owner.verifying_key(),
        )
        .unwrap();
        let message_source =
            crate::collection_names::open(&mut pile, DEFAULT_SCOPE_ID, owner.verifying_key())
                .unwrap();
        let person = test_id(66);
        pile.commit(
            relations_source,
            &owner,
            relations::person_fragment(
                person,
                relations::ProfileInput {
                    label: "sender".to_owned(),
                    ..Default::default()
                },
            )
            .unwrap()
            .0,
        )
        .unwrap();
        let (first, first_id) = message::message_fragment(
            test_id(68),
            &message::Recipient::Person(person),
            "already readable",
            clock::point_now().unwrap(),
        );
        pile.commit(message_source, &owner, first).unwrap();
        // Persona lookup is a read, and a writer without derived WRITE sees
        // only what the maintainer carried: the owner carries both chains
        // before the sender can address anyone or acknowledge anything.
        carry(&mut pile, &runtime, relations_source, &owner);
        carry(&mut pile, &runtime, message_source, &owner);
        drop(
            runtime
                .block_on(message_views(
                    &mut pile,
                    &sender,
                    relations_source,
                    message_source,
                ))
                .unwrap(),
        );
        grant_collection_write(
            &mut pile,
            message_source.handle(),
            &owner,
            sender.verifying_key(),
        )
        .unwrap();
        for source in [relations_source, message_source] {
            let succinct = pile.attach::<SuccinctArchiveBlob>(source, ()).unwrap();
            let rank9 = pile
                .attach::<Rank9AcceleratedSuccinctArchiveBlob>(source, succinct)
                .unwrap();
            let snapshot = pile.snapshot().unwrap();
            assert!(!succinct
                .writer_is_admitted(&snapshot, sender.verifying_key())
                .unwrap());
            assert!(!rank9
                .writer_is_admitted(&snapshot, sender.verifying_key())
                .unwrap());
        }
        let before = pile
            .snapshot()
            .unwrap()
            .records()
            .unwrap()
            .map(|record| record.unwrap())
            .collect::<BTreeSet<_>>();
        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &sender,
                relations_source,
                message_source,
            ))
            .unwrap();
        assert!(message_source
            .writer_is_admitted(&snapshot, sender.verifying_key())
            .unwrap());
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &sender,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        // The sender is not the host, so its writes attach nothing; every
        // reader reads them from their bytes until the host's worker does.
        runtime
            .block_on(send(
                &mut input,
                &SendOptions {
                    from: "sender",
                    to: "sender",
                    text: "published without index WRITE",
                },
            ))
            .unwrap();
        runtime
            .block_on(ack(&mut input, &fmt_id(first_id), "sender"))
            .unwrap();
        let after = pile
            .snapshot()
            .unwrap()
            .records()
            .unwrap()
            .map(|record| record.unwrap())
            .collect::<BTreeSet<_>>();
        let added: Vec<_> = after.difference(&before).copied().collect();
        assert_eq!(added.len(), 2);
        assert!(added.iter().all(|record| matches!(
            record,
            CollectionRecord::Commit(commit) if commit.collection() == message_source.handle()
        )));

        // The sender's two commits are the attachments' lag, counted as such,
        // and already readable.
        let lag = |pile: &mut FacultyStore| {
            let snapshot = pile.snapshot().unwrap();
            let succinct = pile
                .attach::<SuccinctArchiveBlob>(message_source, ())
                .unwrap();
            let rank9 = pile
                .attach::<Rank9AcceleratedSuccinctArchiveBlob>(message_source, succinct)
                .unwrap();
            storage::FactLag::of(&snapshot, message_source, succinct, rank9).unwrap()
        };
        assert_eq!(
            lag(&mut pile),
            storage::FactLag {
                succinct: 2,
                rank9: 2
            }
        );
        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let listed = runtime
            .block_on(list(&mut input, &ListOptions::new("sender")))
            .unwrap();
        assert_eq!(listed.entries.len(), 2);

        // The host's worker attaches them: a MAP is a function of the node,
        // so no grant is needed, and the read is the same.
        carry(&mut pile, &runtime, message_source, &owner);
        assert!(lag(&mut pile).is_current(), "{:?}", lag(&mut pile));
        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let listed = runtime
            .block_on(list(&mut input, &ListOptions::new("sender")))
            .unwrap();
        assert_eq!(listed.entries.len(), 2);
        assert!(listed.entries.iter().any(
            |entry| entry.body == MessageText::Text("published without index WRITE".to_owned())
        ));
        assert!(pile.health().started_at.is_none());
        pile.close().unwrap();
    }

    #[test]
    fn owner_reads_name_unavailable_selected_foundations_instead_of_hiding_them() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let runtime = storage::runtime().unwrap();
        let owner = SigningKey::from_bytes(&[97; 32]);
        let mut pile = storage::open_store_as(file.path(), owner.verifying_key()).unwrap();
        let relations_source = crate::collection_names::open(
            &mut pile,
            DEFAULT_RELATIONS_SCOPE_ID,
            owner.verifying_key(),
        )
        .unwrap();
        let message_source =
            crate::collection_names::open(&mut pile, DEFAULT_SCOPE_ID, owner.verifying_key())
                .unwrap();
        let person = test_id(67);
        pile.commit(
            relations_source,
            &owner,
            relations::person_fragment(
                person,
                relations::ProfileInput {
                    label: "reader".to_owned(),
                    ..Default::default()
                },
            )
            .unwrap()
            .0,
        )
        .unwrap();
        let (first, first_id) = message::message_fragment(
            person,
            &message::Recipient::Person(person),
            "the resident message",
            clock::point_now().unwrap(),
        );
        pile.commit(message_source, &owner, first).unwrap();
        // The worker carries both chains once, so the targets are warm.
        carry(&mut pile, &runtime, relations_source, &owner);
        carry(&mut pile, &runtime, message_source, &owner);
        assert!(pile.health().started_at.is_none());

        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let listed = runtime
            .block_on(list(&mut input, &ListOptions::new("reader")))
            .unwrap();
        assert_eq!(listed.entries.len(), 1);
        assert_eq!(listed.entries[0].id, first_id);
        assert_eq!(
            listed.entries[0].body,
            MessageText::Text("the resident message".to_owned())
        );

        let mut missing = Vec::new();
        for (source, name) in [
            (relations_source, "cold Relations member"),
            (message_source, "cold Message member"),
        ] {
            // Model record-first repair: the real signed member arrives, but
            // its archive does not. Its bytes exist only in this local value.
            let blob = IntoBlob::<SimpleArchive>::to_blob(
                entity! { metadata::name: name }.facts().clone(),
            );
            let handle = blob.get_handle();
            pile.insert(CollectionRecord::Commit(CollectionCommit::sign(
                &owner,
                source.handle(),
                inlineencodings::Handle::<SimpleArchive>::to_hash(handle),
                empty_metadata_handle(),
            )))
            .unwrap();
            let snapshot = pile.snapshot().unwrap();
            assert!(source.admitted(&snapshot).unwrap().contains(handle));
            assert!(!snapshot.contains_blob(handle).unwrap());
            missing.push(handle);
        }
        let before = pile
            .snapshot()
            .unwrap()
            .records()
            .unwrap()
            .map(|record| record.unwrap())
            .collect::<Vec<_>>();
        let error = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .err()
            .expect("an unavailable selected member must not become a partial success");
        let unread = &error
            .downcast_ref::<storage::IncompleteAttachedRead>()
            .expect("preserve the typed incomplete observation")
            .unread;
        assert_eq!(unread.collection(), relations_source);
        assert_eq!(unread.members().collect::<Vec<_>>(), vec![missing[0]]);
        let after = pile.snapshot().unwrap();
        assert_eq!(
            after
                .records()
                .unwrap()
                .map(|record| record.unwrap())
                .collect::<Vec<_>>(),
            before
        );
        for handle in missing {
            assert!(!after.contains_blob(handle).unwrap());
        }
        // Unlike the resident read above, demanding the missing selected
        // foundation starts the foreground Peer even when no provider has it.
        assert!(pile.health().started_at.is_some());
        pile.close().unwrap();
    }

    #[test]
    fn reads_see_every_commit_whether_its_chain_was_carried_or_not() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let runtime = storage::runtime().unwrap();
        let relations_owner = SigningKey::from_bytes(&[93; 32]);
        let message_owner = SigningKey::from_bytes(&[94; 32]);
        // The store's host maintains every chain, whoever writes into it.
        let mut pile = storage::open_store_as(file.path(), message_owner.verifying_key()).unwrap();
        let relations_source = crate::collection_names::open(
            &mut pile,
            DEFAULT_RELATIONS_SCOPE_ID,
            relations_owner.verifying_key(),
        )
        .unwrap();
        let message_source = crate::collection_names::open(
            &mut pile,
            DEFAULT_SCOPE_ID,
            message_owner.verifying_key(),
        )
        .unwrap();
        let first_person = test_id(64);
        let second_person = test_id(65);
        pile.commit(
            relations_source,
            &relations_owner,
            relations::person_fragment(
                first_person,
                relations::ProfileInput {
                    label: "first".to_owned(),
                    ..Default::default()
                },
            )
            .unwrap()
            .0,
        )
        .unwrap();
        let (first, first_message) = message::message_fragment(
            first_person,
            &message::Recipient::Person(first_person),
            "first message",
            clock::point_now().unwrap(),
        );
        pile.commit(message_source, &message_owner, first).unwrap();
        // The host's worker carries both chains.
        carry(&mut pile, &runtime, relations_source, &message_owner);
        carry(&mut pile, &runtime, message_source, &message_owner);
        // Fresh raw records in both chains that nobody has carried yet.
        pile.commit(
            relations_source,
            &relations_owner,
            relations::person_fragment(
                second_person,
                relations::ProfileInput {
                    label: "second".to_owned(),
                    ..Default::default()
                },
            )
            .unwrap()
            .0,
        )
        .unwrap();
        let (second, second_message) = message::message_fragment(
            first_person,
            &message::Recipient::Person(first_person),
            "second message",
            clock::point_now().unwrap(),
        );
        pile.commit(message_source, &message_owner, second).unwrap();
        let records = |pile: &mut FacultyStore| {
            pile.snapshot()
                .unwrap()
                .records()
                .unwrap()
                .map(|record| record.unwrap())
                .collect::<BTreeSet<_>>()
        };
        let before = records(&mut pile);

        // A read takes what the worker attached and reads the fresh commits
        // in both chains from their own bytes; it publishes nothing.
        let (_, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &message_owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        assert_eq!(
            relations::person_anchors(&relation_facts),
            BTreeSet::from([first_person, second_person])
        );
        assert_eq!(
            visible(&message_facts),
            BTreeSet::from([first_message, second_message])
        );
        assert_eq!(records(&mut pile), before, "a read publishes nothing");

        // Once the worker carries both chains again, the same read sees the
        // same facts, now through attachments alone.
        carry(&mut pile, &runtime, relations_source, &message_owner);
        carry(&mut pile, &runtime, message_source, &message_owner);
        let (_, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &message_owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        assert_eq!(
            relations::person_anchors(&relation_facts),
            BTreeSet::from([first_person, second_person])
        );
        assert_eq!(
            visible(&message_facts),
            BTreeSet::from([first_message, second_message])
        );
        pile.close().unwrap();
    }

    #[test]
    fn configured_descriptor_read_acquires_its_descriptor_and_name_only() {
        let mut remote = MemoryRepo::default();
        let signer = SigningKey::from_bytes(&[8; 32]);
        let source =
            crate::collection_names::open(&mut remote, DEFAULT_SCOPE_ID, signer.verifying_key())
                .unwrap();
        let descriptor: TribleSet = remote.snapshot().unwrap().get(source.handle()).unwrap();
        let name = triblespace::core::collection::descriptor::name(&descriptor)
            .unwrap()
            .unwrap();
        let mut store = AcquiringPile::new(remote.into_inner().blobs);
        let before = store.snapshot().unwrap();

        let opened = pollster::block_on(storage::read(&mut store, &before, |reader| {
            open_exact_in(reader, DEFAULT_SCOPE_ID, source.handle())
        }))
        .unwrap();

        assert_eq!(opened, source);
        assert_eq!(
            store.requested,
            vec![source.handle().transmute(), name.transmute()]
        );
        assert!(!before.contains_blob(source.handle()).unwrap());
    }

    #[test]
    fn exact_person_and_group_selectors_do_not_acquire_text() {
        let person = test_id(1);
        let group = test_id(2);
        let (mut fragment, _, _) = relations::person_fragment(
            person,
            relations::ProfileInput {
                label: "person".to_owned(),
                ..Default::default()
            },
        )
        .unwrap();
        fragment += relations::group_create_fragment(group, "group").unwrap().0;
        let mut store = AcquiringPile::new(MemoryBlobStore::new());
        let before = store.snapshot().unwrap();

        let (actual_person, actual_group) =
            pollster::block_on(storage::read(&mut store, &before, |reader| {
                Ok((
                    message::resolve_person(reader, fragment.facts(), &fmt_id(person))?,
                    message::resolve_recipient(reader, fragment.facts(), &fmt_id(group))?,
                ))
            }))
            .unwrap();

        assert_eq!(actual_person, relations::SelectorOutcome::Unique(person));
        assert_eq!(
            message::resolve_person(&before, fragment.facts(), &fmt_id(test_id(3))).unwrap(),
            relations::SelectorOutcome::Missing
        );
        assert_eq!(
            actual_group.require_unique("group").unwrap().anchor(),
            group
        );
        assert!(store.requested.is_empty());
    }

    #[test]
    fn label_and_alias_selection_acquire_only_current_selector_text() {
        let person = test_id(3);
        let (mut fragment, predecessor, _) = relations::person_fragment(
            person,
            relations::ProfileInput {
                label: "superseded label".to_owned(),
                aliases: vec!["superseded alias".to_owned()],
                ..Default::default()
            },
        )
        .unwrap();
        fragment += relations::profile_fragment(
            person,
            relations::ProfileInput {
                label: "current label".to_owned(),
                aliases: vec!["current alias".to_owned()],
                note: Some("not a selector input".to_owned()),
                emails: vec!["not-a-selector@example.test".to_owned()],
                ..Default::default()
            },
            &[predecessor],
        )
        .unwrap();
        let profile = relations::current_profile(fragment.facts(), person).unwrap();

        for (input, expected) in [
            ("current label", vec![profile.label.transmute()]),
            (
                "current alias",
                vec![profile.label.transmute(), profile.aliases[0].transmute()],
            ),
        ] {
            let mut store = AcquiringPile::new(fragment.blobs().clone());
            let before = store.snapshot().unwrap();
            let outcome = pollster::block_on(storage::read(&mut store, &before, |reader| {
                message::resolve_person(reader, fragment.facts(), input)
            }))
            .unwrap();

            assert_eq!(outcome, relations::SelectorOutcome::Unique(person));
            assert_eq!(store.requested, expected);
            assert!(!before.contains_blob(profile.label).unwrap());
            assert_eq!(store.snapshot().unwrap().wants().unwrap().count(), 0);
        }
    }

    #[test]
    fn person_display_acquires_only_the_selected_label() {
        let person = test_id(4);
        let (fragment, _, _) = relations::person_fragment(
            person,
            relations::ProfileInput {
                label: "display label".to_owned(),
                aliases: vec!["unneeded alias".to_owned()],
                note: Some("unneeded note".to_owned()),
                ..Default::default()
            },
        )
        .unwrap();
        let profile = relations::current_profile(fragment.facts(), person).unwrap();
        let mut store = AcquiringPile::new(fragment.blobs().clone());

        assert_eq!(
            pollster::block_on(person_label(&mut store, fragment.facts(), person)).unwrap(),
            "display label"
        );
        assert_eq!(store.requested, vec![profile.label.transmute()]);
    }

    #[test]
    fn exact_inbox_message_keeps_an_unobserved_senders_anchor_and_body() {
        let sender = test_id(8);
        let reader = test_id(9);
        let (relations, _, _) = relations::person_fragment(
            reader,
            relations::ProfileInput {
                label: "reader".to_owned(),
                ..Default::default()
            },
        )
        .unwrap();
        let (envelope, id) = message::message_fragment(
            sender,
            &message::Recipient::Person(reader),
            "visible inbox body",
            (Epoch::from_tai_seconds(0.0), Epoch::from_tai_seconds(0.0))
                .try_to_inline()
                .unwrap(),
        );
        let identities = IdentityComponents::from_facts(relations.facts()).unwrap();
        let mine = settled_identity(&identities, reader);
        let delivered = inbox(envelope.facts(), relations.facts(), &mine);
        assert_eq!(
            delivered.iter().map(envelope_id).collect::<Vec<_>>(),
            vec![id]
        );
        assert!(outbox(envelope.facts(), &mine).is_empty());
        let (_, from, to, body, _, snapshot) = delivered[0];
        assert_eq!(snapshot, None, "a direct send is delivered by no snapshot");
        let mut store = AcquiringPile::new(envelope.blobs().clone());

        assert_eq!(
            pollster::block_on(person_label(&mut store, relations.facts(), from)).unwrap(),
            format!("{sender:x} [profile unavailable]")
        );
        assert!(store.requested.is_empty());
        assert_eq!(
            pollster::block_on(observe_text(&mut store, body)).unwrap(),
            MessageText::Text("visible inbox body".to_owned())
        );
        // The unobserved sender keeps its exact anchor; delivery equivalence
        // never rewrites attribution.
        assert_eq!((from, to), (sender, reader));
        assert_eq!(store.requested, vec![body.transmute()]);
    }

    #[test]
    fn person_display_distinguishes_absent_profile_from_unavailable_label() {
        let person = test_id(10);
        let (fragment, _, _) = relations::person_fragment(
            person,
            relations::ProfileInput {
                label: "unavailable label".to_owned(),
                ..Default::default()
            },
        )
        .unwrap();
        let profile = relations::current_profile(fragment.facts(), person).unwrap();
        let mut store = AcquiringPile::new(MemoryBlobStore::new());
        let anchor_only = entity! {
            ExclusiveId::force_ref(&person) @
            metadata::tag: &crate::schemas::relations::KIND_PERSON_ID
        };

        assert_eq!(
            pollster::block_on(person_label(&mut store, anchor_only.facts(), person)).unwrap(),
            format!("{person:x} [profile unavailable]")
        );
        assert!(store.requested.is_empty());

        assert_eq!(
            pollster::block_on(person_label(&mut store, fragment.facts(), person)).unwrap(),
            format!("{person:x} [label unavailable]")
        );
        assert_eq!(store.requested, vec![profile.label.transmute()]);
        assert_eq!(store.snapshot().unwrap().wants().unwrap().count(), 0);
    }

    #[test]
    fn person_display_does_not_hide_a_profile_fork() {
        let person = test_id(11);
        let (mut fragment, _, _) = relations::person_fragment(
            person,
            relations::ProfileInput {
                label: "first head".to_owned(),
                ..Default::default()
            },
        )
        .unwrap();
        fragment += relations::profile_fragment(
            person,
            relations::ProfileInput {
                label: "second head".to_owned(),
                ..Default::default()
            },
            &[],
        )
        .unwrap();
        let mut store = AcquiringPile::new(fragment.blobs().clone());

        let error =
            pollster::block_on(person_label(&mut store, fragment.facts(), person)).unwrap_err();
        assert!(error.to_string().contains("profile is forked"));
        assert!(store.requested.is_empty());
    }

    #[test]
    fn recipient_display_uses_the_messages_frozen_group_snapshot() {
        let group = test_id(5);
        let (mut fragment, original) =
            relations::group_create_fragment(group, "original group").unwrap();
        let original_name = relations::group_snapshot(fragment.facts(), original)
            .unwrap()
            .name;
        let (message, id) = message::message_fragment(
            test_id(6),
            &message::Recipient::Group {
                anchor: group,
                snapshot: original,
                basis: crate::schemas::message::GROUP_SNAPSHOT_BASIS_WITNESSED,
            },
            "unneeded message body",
            (Epoch::from_tai_seconds(0.0), Epoch::from_tai_seconds(0.0))
                .try_to_inline()
                .unwrap(),
        );
        fragment += message;
        fragment +=
            relations::group_snapshot_fragment(group, "renamed group", &[], &[original]).unwrap();
        let mut store = AcquiringPile::new(fragment.blobs().clone());

        assert_eq!(
            pollster::block_on(recipient_label(
                &mut store,
                fragment.facts(),
                id,
                group,
                Some(original)
            ))
            .unwrap(),
            "original group"
        );
        assert_eq!(store.requested, vec![original_name.transmute()]);
    }

    #[test]
    fn a_missing_group_name_degrades_and_a_failed_one_identifies_itself() {
        let group = test_id(13);
        let (relations, snapshot) =
            relations::group_create_fragment(group, "unavailable group name").unwrap();
        let name = relations::group_snapshot(relations.facts(), snapshot)
            .unwrap()
            .name;
        let (_envelope, id) = message::message_fragment(
            test_id(14),
            &message::Recipient::Group {
                anchor: group,
                snapshot,
                basis: crate::schemas::message::GROUP_SNAPSHOT_BASIS_WITNESSED,
            },
            "not the unavailable attachment",
            (Epoch::from_tai_seconds(0.0), Epoch::from_tai_seconds(0.0))
                .try_to_inline()
                .unwrap(),
        );
        // A missing group name is a fact about that name. It degrades to the
        // snapshot's id, the way a missing person label always has, and the
        // message it labels is still listed.
        let mut store = AcquiringPile::new(MemoryBlobStore::new());
        assert_eq!(
            pollster::block_on(recipient_label(
                &mut store,
                relations.facts(),
                id,
                group,
                Some(snapshot),
            ))
            .unwrap(),
            format!("{snapshot:x} [group name unavailable]")
        );
        assert_eq!(store.requested, vec![name.transmute()]);

        // The store FAILING is still an error, and still identifies the
        // snapshot, the message and the handle, which is what this test was
        // written to guarantee.
        let mut store = AcquiringPile::new(MemoryBlobStore::new());
        store.failure = Some(io::ErrorKind::TimedOut);
        let error = pollster::block_on(recipient_label(
            &mut store,
            relations.facts(),
            id,
            group,
            Some(snapshot),
        ))
        .unwrap_err();
        assert_eq!(
            error.to_string(),
            format!("read name of group snapshot {snapshot:x} for Message {id:x}")
        );
        let report = format!("{error:#}");
        assert!(report.contains(&format!("blake3:{}", hex::encode(name.raw))));
        assert!(report.contains("acquire Message text"));
        assert!(!report.contains("read body of Message"));
        assert_eq!(
            error.downcast_ref::<io::Error>().unwrap().kind(),
            io::ErrorKind::TimedOut
        );
        assert_eq!(store.requested, vec![name.transmute()]);
    }

    #[test]
    fn one_unreadable_body_does_not_hide_the_rest_of_the_inbox() {
        // This was list_body_decode_error_identifies_message_and_handle, and it
        // pinned the opposite: one body that could not be shown failed the
        // whole listing. On 2026-09-22 a message record synced to sky ahead of
        // its text blob, and that refusal made the reader unable to show ANY
        // message -- including every perfectly readable one behind it.
        //
        // The body here is resident but not UTF-8, so the real list path runs
        // without starting the lazy network host. An ABSENT body takes the same
        // path through `list` -- observe_text returns it as a value, not an
        // error -- and that half is proved directly in
        // acquisition_distinguishes_missing_failed_and_invalid_text.
        let file = tempfile::NamedTempFile::new().unwrap();
        let runtime = storage::runtime().unwrap();
        let owner = SigningKey::from_bytes(&[98; 32]);
        let mut pile = storage::open_store_as(file.path(), owner.verifying_key()).unwrap();
        let relations_source = crate::collection_names::open(
            &mut pile,
            DEFAULT_RELATIONS_SCOPE_ID,
            owner.verifying_key(),
        )
        .unwrap();
        let message_source =
            crate::collection_names::open(&mut pile, DEFAULT_SCOPE_ID, owner.verifying_key())
                .unwrap();
        let person = test_id(15);
        pile.commit(
            relations_source,
            &owner,
            relations::person_fragment(
                person,
                relations::ProfileInput {
                    label: "reader".to_owned(),
                    ..Default::default()
                },
            )
            .unwrap()
            .0,
        )
        .unwrap();
        // Keep the malformed body resident: this exercises the real list
        // caller without starting the lazy network host or changing visibility.
        let bytes: Inline<inlineencodings::Handle<UnknownBlob>> =
            pile.put(Bytes::from_source(vec![0xff_u8])).unwrap();
        let body: TextHandle = bytes.transmute();
        let envelope = message::envelope_fragment(
            person,
            person,
            body,
            clock::point_now().unwrap(),
            None,
            None,
        );
        let id = envelope.root().unwrap();
        pile.commit(message_source, &owner, envelope).unwrap();
        // And a perfectly readable message beside it.
        let good: TextHandle = pile.put("still readable").unwrap();
        let readable = message::envelope_fragment(
            person,
            person,
            good,
            clock::point_now().unwrap(),
            None,
            None,
        );
        let readable_id = readable.root().unwrap();
        pile.commit(message_source, &owner, readable).unwrap();
        carry(&mut pile, &runtime, relations_source, &owner);
        carry(&mut pile, &runtime, message_source, &owner);
        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let listed = runtime
            .block_on(list(&mut input, &ListOptions::new("reader")))
            .unwrap();
        let body_of = |wanted: Id| {
            listed
                .entries
                .iter()
                .find(|entry| entry.id == wanted)
                .map(|entry| entry.body.clone())
        };
        assert_eq!(
            body_of(readable_id),
            Some(MessageText::Text("still readable".to_owned())),
            "the readable message is listed despite its neighbour"
        );
        // The unreadable one is listed too, and still identifies its handle --
        // which is what the old test existed to guarantee.
        assert_eq!(body_of(id), Some(MessageText::Undecodable(body)));
        assert!(pile.health().started_at.is_none());
        pile.close().unwrap();
    }

    #[test]
    fn acquiring_a_selected_body_leaves_other_bodies_and_old_snapshot_untouched() {
        let mut remote = MemoryBlobStore::new();
        let selected: TextHandle = remote.put("selected body").unwrap();
        let unrelated: TextHandle = remote.put("unselected body").unwrap();
        let mut store = AcquiringPile::new(remote);
        let before = store.snapshot().unwrap();

        assert_eq!(
            pollster::block_on(observe_text(&mut store, selected)).unwrap(),
            MessageText::Text("selected body".to_owned())
        );
        assert_eq!(store.requested, vec![selected.transmute()]);
        assert!(!before.contains_blob(selected).unwrap());
        let after = store.snapshot().unwrap();
        assert!(after.contains_blob(selected).unwrap());
        assert!(!after.contains_blob(unrelated).unwrap());
        assert_eq!(after.wants().unwrap().count(), 0);
    }

    #[test]
    fn acquisition_distinguishes_missing_failed_and_invalid_text() {
        // Three outcomes, still told apart -- that part of this test is
        // unchanged. What changed is which of them are errors. Absent and
        // undecodable are facts about the DATA and come back as values the
        // reader reports; only the store failing is an error, because it is a
        // fact about the reader.
        let mut remote = MemoryBlobStore::new();
        let invalid = remote.insert(Blob::<blobencodings::UTF8String>::new(Bytes::from_source(
            vec![0xff_u8],
        )));
        let absent: TextHandle = "absent".to_blob().get_handle();
        let mut store = AcquiringPile::new(remote);

        assert_eq!(
            pollster::block_on(observe_text(&mut store, absent)).unwrap(),
            MessageText::Unavailable(absent),
            "a missing body is named by its handle, so a peer can be asked for it"
        );

        store.failure = Some(io::ErrorKind::PermissionDenied);
        let failed = pollster::block_on(observe_text(&mut store, absent)).unwrap_err();
        assert_eq!(
            failed.to_string(),
            format!("acquire Message text blake3:{}", hex::encode(absent.raw))
        );
        assert_eq!(
            failed.downcast_ref::<io::Error>().unwrap().kind(),
            io::ErrorKind::PermissionDenied
        );
        assert_eq!(
            failed.root_cause().to_string(),
            "injected Message acquisition failure"
        );

        store.failure = None;
        assert_eq!(
            pollster::block_on(observe_text(&mut store, invalid)).unwrap(),
            MessageText::Undecodable(invalid),
        );

        // And a person label that is not text degrades the way an absent one
        // always has, instead of taking the whole listing down with it.
        let person = test_id(12);
        let profile = entity! {
            metadata::tag: &crate::schemas::relations::KIND_PERSON_PROFILE,
            crate::schemas::relations::profile::of: &person,
            metadata::name: invalid,
        };
        assert_eq!(
            pollster::block_on(person_label(&mut store, profile.facts(), person)).unwrap(),
            format!("{person:x} [label undecodable]")
        );
    }

    #[test]
    fn selector_retry_keeps_frozen_support_when_a_commit_arrives_during_acquisition() {
        let person = test_id(7);
        let (mut fragment, predecessor, _) = relations::person_fragment(
            person,
            relations::ProfileInput {
                label: "original label".to_owned(),
                ..Default::default()
            },
        )
        .unwrap();
        let signer = SigningKey::from_bytes(&[7; 32]);
        let mut store = AcquiringPile::hosted(fragment.blobs().clone(), signer.verifying_key());
        fragment.blobs_mut().keep([]);
        let source = crate::collection_names::open(
            &mut store.pile,
            DEFAULT_RELATIONS_SCOPE_ID,
            signer.verifying_key(),
        )
        .unwrap();
        store.pile.commit(source, &signer, fragment).unwrap();
        let succinct = store
            .pile
            .attach::<SuccinctArchiveBlob>(source, ())
            .unwrap();
        let rank9 = store
            .pile
            .attach::<Rank9AcceleratedSuccinctArchiveBlob>(source, succinct)
            .unwrap();
        let before = pollster::block_on(async {
            drop(store.pile.ensure(source, &signer).await.unwrap());
            drop(
                store
                    .pile
                    .maintain_attached(succinct, &signer)
                    .await
                    .unwrap(),
            );
            store.pile.maintain_attached(rank9, &signer).await.unwrap()
        });
        let observed = before.attached(rank9).unwrap();
        let facts = observed.facts().unwrap();
        let original_support = observed.support().clone();
        let successor = relations::profile_fragment(
            person,
            relations::ProfileInput {
                label: "later label".to_owned(),
                ..Default::default()
            },
            &[predecessor],
        )
        .unwrap();
        store.arriving = Some((source, signer, successor));

        let outcome = pollster::block_on(storage::read(&mut store, &before, |reader| {
            message::resolve_person(reader, &facts, "original label")
        }))
        .unwrap();

        assert_eq!(outcome, relations::SelectorOutcome::Unique(person));
        assert_eq!(store.requested.len(), 1);
        assert_eq!(observed.support(), &original_support);
        assert_eq!(original_support.len(), 1);
        let after = store.snapshot().unwrap();
        assert_eq!(source.admitted(&after).unwrap().len(), 2);
        assert_eq!(after.wants().unwrap().count(), 0);
    }

    #[test]
    fn reads_see_fresh_commits_and_publish_nothing() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let runtime = storage::runtime().unwrap();
        let owner = SigningKey::from_bytes(&[93; 32]);
        let mut pile = storage::open_store_as(file.path(), owner.verifying_key()).unwrap();
        let relations_source = crate::collection_names::open(
            &mut pile,
            DEFAULT_RELATIONS_SCOPE_ID,
            owner.verifying_key(),
        )
        .unwrap();
        let message_source =
            crate::collection_names::open(&mut pile, DEFAULT_SCOPE_ID, owner.verifying_key())
                .unwrap();
        let mut selectors = BTreeSet::new();
        for source in [relations_source, message_source] {
            let succinct = pile.attach::<SuccinctArchiveBlob>(source, ()).unwrap();
            let rank9 = pile
                .attach::<Rank9AcceleratedSuccinctArchiveBlob>(source, succinct)
                .unwrap();
            for handle in [source.handle(), succinct.handle(), rank9.handle()] {
                selectors.insert(CollectionRecordSelector::Collection(handle));
            }
        }
        let sender = test_id(63);
        let recipient = test_id(64);
        let mut people = relations::person_fragment(
            sender,
            relations::ProfileInput {
                label: "sender".to_owned(),
                ..Default::default()
            },
        )
        .unwrap()
        .0;
        people += relations::person_fragment(
            recipient,
            relations::ProfileInput {
                label: "reader".to_owned(),
                ..Default::default()
            },
        )
        .unwrap()
        .0;
        pile.commit(relations_source, &owner, people).unwrap();
        let (first, first_id) = message::message_fragment(
            sender,
            &message::Recipient::Person(recipient),
            "maintained message",
            clock::point_now().unwrap(),
        );
        pile.commit(message_source, &owner, first).unwrap();
        // Start with a carried view, then append facts no worker has seen.
        carry(&mut pile, &runtime, relations_source, &owner);
        carry(&mut pile, &runtime, message_source, &owner);
        let (_old_reader, old_relations, old_messages) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let later_person = test_id(65);
        pile.commit(
            relations_source,
            &owner,
            relations::person_fragment(
                later_person,
                relations::ProfileInput {
                    label: "new person".to_owned(),
                    ..Default::default()
                },
            )
            .unwrap()
            .0,
        )
        .unwrap();
        let (second, second_id) = message::message_fragment(
            sender,
            &message::Recipient::Person(recipient),
            "fresh raw message",
            clock::point_now().unwrap(),
        );
        pile.commit(message_source, &owner, second).unwrap();
        let before = pile
            .snapshot()
            .unwrap()
            .select_records(&selectors)
            .unwrap()
            .into_iter()
            .collect::<BTreeSet<_>>();
        let (_, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let after = pile
            .snapshot()
            .unwrap()
            .select_records(&selectors)
            .unwrap()
            .into_iter()
            .collect::<BTreeSet<_>>();
        assert_eq!(
            before, after,
            "a read publishes nothing, even for the owner"
        );
        // The fresh commits are read from their own bytes before any
        // worker attaches them; the earlier read stays as it was taken.
        assert_eq!(
            visible(&message_facts),
            BTreeSet::from([first_id, second_id])
        );
        assert!(relations::person_anchors(&relation_facts).contains(&later_person));
        assert_eq!(visible(&old_messages), BTreeSet::from([first_id]));
        assert!(!relations::person_anchors(&old_relations).contains(&later_person));
        assert_eq!(pile.snapshot().unwrap().wants().unwrap().count(), 0);
        assert!(pile.health().started_at.is_none());

        // The worker carries the fresh commits; the same read then sees them
        // and, repeated, has no new work to publish.
        carry(&mut pile, &runtime, relations_source, &owner);
        carry(&mut pile, &runtime, message_source, &owner);
        let after = pile
            .snapshot()
            .unwrap()
            .select_records(&selectors)
            .unwrap()
            .into_iter()
            .collect::<BTreeSet<_>>();
        assert!(after.difference(&before).all(|record| matches!(
            record,
            CollectionRecord::Map(_) | CollectionRecord::Merge(_)
        )));
        let bytes_after = std::fs::metadata(file.path()).unwrap().len();
        let (_, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        assert_eq!(
            visible(&message_facts),
            BTreeSet::from([first_id, second_id])
        );
        assert!(relations::person_anchors(&relation_facts).contains(&later_person));
        assert_eq!(
            pile.snapshot()
                .unwrap()
                .select_records(&selectors)
                .unwrap()
                .into_iter()
                .collect::<BTreeSet<_>>(),
            after
        );
        assert_eq!(std::fs::metadata(file.path()).unwrap().len(), bytes_after);
        pile.close().unwrap();
    }

    #[test]
    fn sends_and_acknowledgements_finish_their_views_before_returning() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let runtime = storage::runtime().unwrap();
        let owner = SigningKey::from_bytes(&[98; 32]);
        let mut pile = storage::open_store_as(file.path(), owner.verifying_key()).unwrap();
        let relations_source = crate::collection_names::open(
            &mut pile,
            DEFAULT_RELATIONS_SCOPE_ID,
            owner.verifying_key(),
        )
        .unwrap();
        let message_source =
            crate::collection_names::open(&mut pile, DEFAULT_SCOPE_ID, owner.verifying_key())
                .unwrap();
        let succinct = pile
            .attach::<SuccinctArchiveBlob>(message_source, ())
            .unwrap();
        let rank9 = pile
            .attach::<Rank9AcceleratedSuccinctArchiveBlob>(message_source, succinct)
            .unwrap();
        let sender = test_id(81);
        let recipient = test_id(82);
        let mut people = Fragment::empty();
        for (person, label) in [(sender, "sender"), (recipient, "reader")] {
            people += relations::person_fragment(
                person,
                relations::ProfileInput {
                    label: label.to_owned(),
                    ..Default::default()
                },
            )
            .unwrap()
            .0;
        }
        pile.commit(relations_source, &owner, people).unwrap();
        // The worker carries the names a sender is resolved against; each
        // send then ensures its own images before it returns, which is the
        // property under test.
        carry(&mut pile, &runtime, relations_source, &owner);
        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let mut sent = Vec::new();
        for text in ["first eager message", "second eager message"] {
            sent.push(
                runtime
                    .block_on(send(
                        &mut input,
                        &SendOptions {
                            from: "sender",
                            to: "reader",
                            text,
                        },
                    ))
                    .unwrap()
                    .id,
            );
            // This is a passive target query, not another faculty call that
            // could repair an incomplete send before the assertion.
            let after = input.pile.snapshot().unwrap();
            let selected = after.attached(rank9).unwrap();
            let facts = selected.facts().unwrap();
            assert_eq!(visible(&facts), sent.iter().copied().collect());
            assert_eq!(message_source.admitted(&after).unwrap().len(), sent.len());
        }
        assert!(
            visible(&message_facts).is_empty(),
            "the operation view stays frozen"
        );

        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let acknowledged = runtime
            .block_on(ack(&mut input, &fmt_id(sent[0]), "reader"))
            .unwrap();
        assert!(!acknowledged.already_read);
        let after = input.pile.snapshot().unwrap();
        let selected = after.attached(rank9).unwrap();
        let facts = selected.facts().unwrap();
        assert!(read_by(&facts, sent[0], &[recipient]));
        assert!(!read_by(&facts, sent[1], &[recipient]));
        assert!(!read_by(&message_facts, sent[0], &[recipient]));

        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let acknowledged = runtime
            .block_on(ack_all(
                &mut input,
                &AckAllOptions {
                    by: "reader",
                    from: None,
                },
            ))
            .unwrap();
        assert_eq!(acknowledged.message_ids, vec![sent[1]]);
        let after = input.pile.snapshot().unwrap();
        let selected = after.attached(rank9).unwrap();
        let facts = selected.facts().unwrap();
        assert!(sent.iter().all(|id| read_by(&facts, *id, &[recipient])));
        assert!(!read_by(&message_facts, sent[1], &[recipient]));
        assert_eq!(after.wants().unwrap().count(), 0);
        assert!(pile.health().started_at.is_none());
        pile.close().unwrap();
    }

    #[test]
    fn post_commit_ensure_failure_names_the_already_published_fragment() {
        let file = tempfile::NamedTempFile::new().unwrap();
        let runtime = storage::runtime().unwrap();
        let owner = SigningKey::from_bytes(&[99; 32]);
        let mut pile = storage::open_store_as(file.path(), owner.verifying_key()).unwrap();
        let relations_source = crate::collection_names::open(
            &mut pile,
            DEFAULT_RELATIONS_SCOPE_ID,
            owner.verifying_key(),
        )
        .unwrap();
        let message_source =
            crate::collection_names::open(&mut pile, DEFAULT_SCOPE_ID, owner.verifying_key())
                .unwrap();
        let (snapshot, relation_facts, message_facts) = runtime
            .block_on(message_views(
                &mut pile,
                &owner,
                relations_source,
                message_source,
            ))
            .unwrap();
        // This admitted but malformed input arrives after the operation's
        // frozen view. It cannot prevent the raw COMMIT; it does prevent
        // ensuring the Succinct image after the commit.
        let raw: Inline<inlineencodings::Handle<UnknownBlob>> =
            pile.put(Bytes::from_source(vec![0_u8])).unwrap();
        let malformed: Inline<inlineencodings::Handle<SimpleArchive>> = raw.transmute();
        pile.insert(CollectionRecord::Commit(CollectionCommit::sign(
            &owner,
            message_source.handle(),
            inlineencodings::Handle::<SimpleArchive>::to_hash(malformed),
            empty_metadata_handle(),
        )))
        .unwrap();
        let before = message_source.admitted(&pile.snapshot().unwrap()).unwrap();
        assert_eq!(before.len(), 1);
        let (fragment, id) = message::message_fragment(
            test_id(83),
            &message::Recipient::Person(test_id(84)),
            "the committed message survives its maintenance failure",
            clock::point_now().unwrap(),
        );
        let mut input = MessageStorage {
            pile: &mut pile,
            signer: &owner,
            collection: message_source,
            reader: &snapshot,
            messages: &message_facts,
            relations: &relation_facts,
        };
        let error = runtime
            .block_on(input.update("failure witness", |_, _| Ok((Some(fragment), id))))
            .unwrap_err();
        let text = format!("{error:#}");
        assert!(
            text.contains("Message fragment was committed, but ensuring its derived views failed")
        );
        let after = pile.snapshot().unwrap();
        let admitted = message_source.admitted(&after).unwrap();
        assert_eq!(admitted.len(), before.len() + 1);
        assert!(admitted.contains(malformed));
        assert!(visible(&message_facts).is_empty());
        pile.close().unwrap();
    }

    fn at(seconds: f64) -> IntervalValue {
        let epoch = Epoch::from_tai_seconds(seconds);
        (epoch, epoch).try_to_inline().unwrap()
    }

    fn person_anchor(person: Id) -> TribleSet {
        entity! { ExclusiveId::force_ref(&person) @
            metadata::tag: &crate::schemas::relations::KIND_PERSON_ID
        }
        .into_facts()
    }

    fn test_body() -> message::TextHandle {
        "body".to_owned().to_blob().get_handle()
    }

    fn delivered_ids<M, R>(message_facts: &M, relation_facts: &R, mine: &[Id]) -> Vec<Id>
    where
        M: TriblePattern,
        R: TriblePattern,
    {
        inbox(message_facts, relation_facts, mine)
            .iter()
            .map(envelope_id)
            .collect()
    }

    /// Delivery is decided by the audience frozen into the envelope at send
    /// time, never by the group's later head.
    #[test]
    fn group_delivery_uses_the_frozen_snapshot_not_a_later_head() {
        let sender = test_id(0x31);
        let original_member = test_id(0x32);
        let later_member = test_id(0x33);
        let group = test_id(0x34);

        let mut relation_facts = TribleSet::new();
        for person in [sender, original_member, later_member] {
            relation_facts += person_anchor(person);
        }
        relation_facts += entity! { ExclusiveId::force_ref(&group) @
            metadata::tag: &crate::schemas::relations::KIND_GROUP
        }
        .into_facts();
        let old =
            relations::group_snapshot_fragment(group, "group", &[original_member], &[]).unwrap();
        let old_id = old.root().unwrap();
        relation_facts += old.into_facts();
        relation_facts +=
            relations::group_snapshot_fragment(group, "group", &[later_member], &[old_id])
                .unwrap()
                .into_facts();

        let envelope = message::envelope_fragment(
            sender,
            group,
            test_body(),
            at(13.0),
            Some(old_id),
            Some(crate::schemas::message::GROUP_SNAPSHOT_BASIS_WITNESSED),
        );
        let id = envelope.root().unwrap();
        let message_facts = envelope.into_facts();

        let identities = IdentityComponents::from_facts(&relation_facts).unwrap();
        assert_eq!(
            delivered_ids(
                &message_facts,
                &relation_facts,
                &settled_identity(&identities, original_member)
            ),
            vec![id]
        );
        assert!(delivered_ids(
            &message_facts,
            &relation_facts,
            &settled_identity(&identities, later_member)
        )
        .is_empty());
        assert_eq!(delivery_snapshot(&message_facts, id), Some(old_id));
    }

    /// People Relations has never observed still address each other. Their
    /// envelopes are simply not this reader's, and none of them is an error.
    #[test]
    fn unobserved_senders_do_not_poison_exact_inbox_membership() {
        let reader = test_id(0x70);
        let unknown_sender = test_id(0x71);
        let unknown_recipient = test_id(0x72);
        let relation_facts = person_anchor(reader);

        let mut message_facts = TribleSet::new();
        let mut ids = Vec::new();
        for (from, to, seconds) in [
            (unknown_sender, unknown_recipient, 15.0),
            (unknown_sender, reader, 14.0),
            (reader, unknown_recipient, 13.0),
        ] {
            let envelope =
                message::envelope_fragment(from, to, test_body(), at(seconds), None, None);
            ids.push(envelope.root().unwrap());
            message_facts += envelope.into_facts();
        }

        let identities = IdentityComponents::from_facts(&relation_facts).unwrap();
        let mine = settled_identity(&identities, reader);
        assert_eq!(
            delivered_ids(&message_facts, &relation_facts, &mine),
            vec![ids[1]]
        );
        assert_eq!(
            outbox(&message_facts, &mine)
                .iter()
                .map(envelope_id)
                .collect::<Vec<_>>(),
            vec![ids[2]]
        );
    }

    /// A receipt written by someone Relations has not observed neither marks
    /// the message read for another reader nor hides that reader's own receipt.
    #[test]
    fn unobserved_receipt_readers_neither_acknowledge_nor_hide_an_exact_reader() {
        let reader = test_id(0x73);
        let absent = test_id(0x74);
        let message = test_id(0x75);
        let relation_facts = person_anchor(reader);
        let identities = IdentityComponents::from_facts(&relation_facts).unwrap();
        let mine = settled_identity(&identities, reader);
        // An anchor with no Relations evidence still identifies itself.
        let theirs = settled_identity(&identities, absent);
        assert_eq!(theirs, vec![absent]);

        let mut message_facts = message::read_fragment(message, absent, None).0.into_facts();
        assert!(!read_by(&message_facts, message, &mine));
        assert!(read_by(&message_facts, message, &theirs));
        message_facts += message::read_fragment(message, reader, None).0.into_facts();
        assert!(read_by(&message_facts, message, &mine));
    }

    /// Settled same-person evidence widens who may read and acknowledge an
    /// envelope; it never rewrites the anchors the envelope names.
    #[test]
    fn settled_same_identity_delivers_without_rewriting_attribution() {
        let sender = test_id(0x36);
        let addressed = test_id(0x37);
        let equivalent_reader = test_id(0x38);
        let mut relation_facts = TribleSet::new();
        for person in [sender, addressed, equivalent_reader] {
            relation_facts += person_anchor(person);
        }
        relation_facts +=
            relations::identity_verdict_fragment(addressed, equivalent_reader, true, &[])
                .unwrap()
                .into_facts();

        let envelope =
            message::envelope_fragment(sender, addressed, test_body(), at(13.5), None, None);
        let id = envelope.root().unwrap();
        let message_facts = envelope.into_facts();

        let identities = IdentityComponents::from_facts(&relation_facts).unwrap();
        let mine = settled_identity(&identities, equivalent_reader);
        let delivered = inbox(&message_facts, &relation_facts, &mine);
        assert_eq!(
            delivered.iter().map(envelope_id).collect::<Vec<_>>(),
            vec![id]
        );
        let (_, from, to, ..) = delivered[0];
        assert_eq!((from, to), (sender, addressed));

        // The receipt one anchor writes answers for the whole settled person.
        let acknowledged = message::read_fragment(id, equivalent_reader, None)
            .0
            .into_facts();
        assert!(read_by(
            &acknowledged,
            id,
            &settled_identity(&identities, addressed)
        ));
    }

    /// The sender's own envelope is outgoing, so `ack` has nothing to mark and
    /// an unrelated person sees neither side of it.
    #[test]
    fn a_sender_never_finds_their_own_envelope_in_their_inbox() {
        let sender = test_id(0x45);
        let recipient = test_id(0x46);
        let unrelated = test_id(0x47);
        let mut relation_facts = TribleSet::new();
        for person in [sender, recipient, unrelated] {
            relation_facts += person_anchor(person);
        }
        let envelope =
            message::envelope_fragment(sender, recipient, test_body(), at(13.75), None, None);
        let id = envelope.root().unwrap();
        let message_facts = envelope.into_facts();

        let identities = IdentityComponents::from_facts(&relation_facts).unwrap();
        let mine = settled_identity(&identities, sender);
        assert!(delivered_ids(&message_facts, &relation_facts, &mine).is_empty());
        assert_eq!(
            outbox(&message_facts, &mine)
                .iter()
                .map(envelope_id)
                .collect::<Vec<_>>(),
            vec![id]
        );

        let stranger = settled_identity(&identities, unrelated);
        assert!(delivered_ids(&message_facts, &relation_facts, &stranger).is_empty());
        assert!(outbox(&message_facts, &stranger).is_empty());
    }

    /// Sending is a property of the envelope, not of one witness: an envelope
    /// that names this reader as a sender anywhere is outgoing, even when
    /// another witness names someone else, so inbox and outbox stay disjoint.
    #[test]
    fn a_second_sender_witness_does_not_put_my_own_envelope_in_my_inbox() {
        let me = test_id(0x50);
        let other_sender = test_id(0x51);
        let relation_facts = person_anchor(me) + person_anchor(other_sender);

        let envelope = message::envelope_fragment(me, me, test_body(), at(17.0), None, None);
        let id = envelope.root().unwrap();
        let mut message_facts = envelope.into_facts();
        message_facts +=
            entity! { ExclusiveId::force_ref(&id) @ local::from: other_sender }.into_facts();

        let identities = IdentityComponents::from_facts(&relation_facts).unwrap();
        let mine = settled_identity(&identities, me);
        assert!(
            delivered_ids(&message_facts, &relation_facts, &mine).is_empty(),
            "an envelope I am a sender of is never in my inbox"
        );
        assert_eq!(
            outbox(&message_facts, &mine)
                .iter()
                .map(envelope_id)
                .collect::<BTreeSet<_>>(),
            BTreeSet::from([id])
        );
    }

    /// An envelope naming two snapshots is delivered by the one that names the
    /// reader, and the row carries that snapshot so the audience a listing
    /// shows cannot come from the other one.
    #[test]
    fn the_delivering_snapshot_is_the_one_that_names_the_reader() {
        let sender = test_id(0x52);
        let member = test_id(0x53);
        let stranger = test_id(0x54);
        let group = test_id(0x55);
        let mut relation_facts =
            person_anchor(sender) + person_anchor(member) + person_anchor(stranger);
        relation_facts += entity! { ExclusiveId::force_ref(&group) @
            metadata::tag: &crate::schemas::relations::KIND_GROUP
        }
        .into_facts();
        let without =
            relations::group_snapshot_fragment(group, "without", &[stranger], &[]).unwrap();
        let without_id = without.root().unwrap();
        relation_facts += without.into_facts();
        let with =
            relations::group_snapshot_fragment(group, "with", &[member], &[without_id]).unwrap();
        let with_id = with.root().unwrap();
        relation_facts += with.into_facts();

        let envelope = message::envelope_fragment(
            sender,
            group,
            test_body(),
            at(18.0),
            Some(without_id),
            Some(crate::schemas::message::GROUP_SNAPSHOT_BASIS_WITNESSED),
        );
        let id = envelope.root().unwrap();
        let mut message_facts = envelope.into_facts();
        message_facts += entity! { ExclusiveId::force_ref(&id) @
            local::group_snapshot: with_id,
        }
        .into_facts();

        let identities = IdentityComponents::from_facts(&relation_facts).unwrap();
        let mine = settled_identity(&identities, member);
        let delivered = inbox(&message_facts, &relation_facts, &mine);
        assert_eq!(
            delivered.iter().map(envelope_id).collect::<Vec<_>>(),
            vec![id]
        );
        assert_eq!(
            delivered[0].5,
            Some(with_id),
            "the snapshot that delivered it, not the one it also names"
        );
    }

    /// `--from` selects an envelope when any witness names that sender, so a
    /// second sender witness cannot hide it behind the reduction.
    #[test]
    fn a_sender_selector_matches_any_witness_of_the_envelope() {
        let first = test_id(0x56);
        let second = test_id(0x57);
        let reader = test_id(0x58);
        let relation_facts = person_anchor(first) + person_anchor(second) + person_anchor(reader);

        let envelope = message::envelope_fragment(first, reader, test_body(), at(19.0), None, None);
        let id = envelope.root().unwrap();
        let mut message_facts = envelope.into_facts();
        message_facts += entity! { ExclusiveId::force_ref(&id) @ local::from: second }.into_facts();

        let identities = IdentityComponents::from_facts(&relation_facts).unwrap();
        let mine = settled_identity(&identities, reader);
        let delivered = inbox(&message_facts, &relation_facts, &mine);
        assert_eq!(delivered.len(), 2, "both senders witness the envelope");
        assert_eq!(envelopes_from(delivered.clone(), None), vec![id]);
        for sender in [first, second] {
            assert_eq!(
                envelopes_from(
                    delivered.clone(),
                    Some(&settled_identity(&identities, sender))
                ),
                vec![id],
                "selecting {sender:x} must find the envelope"
            );
        }
        let absent = settled_identity(&identities, test_id(0x59));
        assert!(envelopes_from(delivered, Some(&absent)).is_empty());
    }

    /// A second recipient naming another anchor of the same settled person is
    /// one more witness of one envelope. The query answers with a bag and the
    /// listing collapses it; nothing is rejected as malformed.
    #[test]
    fn a_repeated_recipient_is_one_more_witness_not_one_more_message() {
        let sender = test_id(0x39);
        let addressed = test_id(0x3A);
        let also_addressed = test_id(0x3B);
        let mut relation_facts = TribleSet::new();
        for person in [sender, addressed, also_addressed] {
            relation_facts += person_anchor(person);
        }
        relation_facts +=
            relations::identity_verdict_fragment(addressed, also_addressed, true, &[])
                .unwrap()
                .into_facts();

        let envelope =
            message::envelope_fragment(sender, addressed, test_body(), at(16.0), None, None);
        let id = envelope.root().unwrap();
        let mut message_facts = envelope.into_facts();
        message_facts +=
            entity! { ExclusiveId::force_ref(&id) @ local::to: also_addressed }.into_facts();

        let identities = IdentityComponents::from_facts(&relation_facts).unwrap();
        let mine = settled_identity(&identities, addressed);
        let delivered = inbox(&message_facts, &relation_facts, &mine);
        assert_eq!(delivered.len(), 2, "both recipients witness the envelope");
        assert_eq!(
            delivered
                .iter()
                .unique_by(|envelope| envelope_id(envelope))
                .count(),
            1,
            "and they are one message"
        );
    }
}